All files / src base.controller.ts

98.61% Statements 142/144
92.86% Branches 78/84
100% Functions 28/28
98.61% Lines 142/144

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 4091x                                       1x             1x   1x           57x 57x       5x                       5x   5x 2x   3x     5x   5x             5x 1x   4x   4x                 2x 1x   1x   1x       5x 5x     5x 5x 5x           5x 5x 3x   2x                 5x 1x   5x   5x 4x   4x 5x   4x   4x 4x 2x   2x       1x               3x       2x 2x 2x   2x 2x 1x   1x       1x               3x 2x 2x 2x 1x   1x       1x                     5x 4x 3x     4x   4x 1x   3x 1x   2x   2x       1x       3x 3x 1x   2x 1x   2x   2x         2x 1x     2x     6x 3x 3x 3x 1x   2x 1x   2x   2x       3x                     4x 4x 4x 4x 3x 2x   1x 1x   3x 3x 3x 3x 3x   3x 2x   3x         3x     4x           5x                     5x 1x   5x 1x   5x 3x   5x 3x     5x     9x 9x 9x 9x 9x                         9x 10x 10x     9x       9x           7x   7x 7x   4x     7x 7x 21x 1x       7x       3x 3x   3x         3x                                                     1x  
import {
  Types,
} from 'mongoose';
import {
  Response,
  Request,
  NextFunction,
} from 'express';
import {
  ObjectID,
} from 'bson';
import {
  IApiRequest,
  IApiModel,
} from './types';
 
import {
  IPopulate,
  IApiParsedQuery,
} from './types/IApiQuery';
import {
  isString,
  toNumber,
} from './helpers';
import {
  IApiDocument,
} from './types/IApiModel';
import ApiController from './api.controller';
 
const isValidId = Types.ObjectId.isValid;
 
abstract class BaseController<T extends IApiModel<K, R>, K, R> extends ApiController<T> {
  protected filters: string[];
 
  constructor(model: T) {
    super(model);
    this.filters = [ 'type', 'deleted' ];
  }
 
  public index(req: IApiRequest, _res: Response, next: NextFunction): void {
    let query: IApiParsedQuery = {
      deleted: false,
      filter: null,
      limit: 100,
      offset: 0,
      populate: null,
      q: {},
      select: null,
      sort: null,
      total: 0,
    };
 
    req.modelQuery = this.processQuery(req.query, query);
 
    if (typeof this.model.parseQuery === 'function') {
      query = this.model.parseQuery(req.modelQuery );
    } else {
      query = this.parseQuery(req.modelQuery );
    }
 
    query.populate = query.populate ? query.populate : [];
 
    return this.model.find(query.q)
      .limit(toNumber(query.limit))
      .skip(toNumber(query.offset))
      .sort(query.sort)
      .select(query.select)
      .populate(query.populate)
      .exec((err: any, models: any) => {
        if (err) {
          return next(err);
        } else {
          req.data = models;
 
          return next();
        }
      });
  }
  public read(
    req: IApiRequest,
    res: Response,
    _next: NextFunction,
  ): Response {
    if (this.hasModel(req.model)) {
      const model = req.model.toObject();
 
      return res.jsonp(model);
    } else {
      return this.respondModelMissingError(res);
    }
  }
  public create(req: IApiRequest, res: Response, next: NextFunction): void {
    delete req.body._id;
    delete req.body.timestamps;
 
    // eslint-disable-next-line @typescript-eslint/naming-convention
    const Model = this.model;
    const model = new Model(req.body);
    (<any>model).timestamps = {
      created: {
        by: req.user.username,
      },
    };
 
    model.save((err, resModel) => {
      if (err) {
        return this.respondValidationError(err, res, next);
      } else {
        res.status(201).json(resModel.toObject());
      }
    });
  }
  public update(
    req: IApiRequest,
    res: Response,
    next: NextFunction,
  ): Response | void {
    if (req.body._id === null) {
      delete req.body._id;
    }
    delete req.body.timestamps;
 
    if (this.hasModel(req.model)) {
      const model = req.model;
 
      Object.keys(req.body).forEach((key) => {
        model[key] = req.body[key];
      });
      model.timestamps.updated.by = req.user.username;
 
      model.save((err: any, resModel: IApiDocument) => {
        if (err) {
          return this.respondValidationError(err, res, next);
        } else {
          return res.status(200).json(resModel.toObject());
        }
      });
    } else {
      return this.respondModelMissingError(res);
    }
  }
  public softDelete(
    req: IApiRequest,
    res: Response,
    _next: NextFunction,
  ): Response | void {
    if (this.hasModel(req.model)) {
 
      // FIXME: potential problem, here someone could inject admin as property,
      // when deleting a user
      const model = req.model;
      model.mark.deleted = true;
      model.timestamps.updated.by = req.user.username;
 
      model.save((err: any, resModel: IApiDocument) => {
        if (err) {
          return this.respondDeletionError(res, err);
        } else {
          return res.status(200).jsonp(resModel.toObject());
        }
      });
    } else {
      return this.respondModelMissingError(res);
    }
  }
  public delete(
    req: IApiRequest,
    res: Response,
    _next: NextFunction,
  ): Response | void {
    if (this.hasModel(req.model)) {
      const model: any = req.model;
      model.remove((err: any) => {
        if (err) {
          return this.respondDeletionError(res, err);
        } else {
          return res.status(200).jsonp(model.toObject());
        }
      });
    } else {
      return this.respondModelMissingError(res);
    }
  }
  public findById(
    req: IApiRequest,
    res: Response,
    next: NextFunction,
    id: string | number | ObjectID,
    _urlParam?: any,
    populate?: IPopulate[],
  ): Response | void {
    if (isValidId(id)) {
      if (typeof populate === 'undefined') {
        populate = [];
      }
 
      this.model.findById(id).populate(populate)
        .exec((err, model) => {
          if (err) {
            return this.respondServerError(res, err);
          }
          if (!model) {
            return this.respondNotFound(id, res, this.model.modelName);
          } else {
            req.model = model;
 
            return next();
          }
        });
    } else {
      return this.respondInvalidId(res);
    }
  }
  public stats(req: IApiRequest, res: Response, next: NextFunction): void {
    this.model.countDocuments((err, result) => {
      if (err) {
        return this.respondServerError(res, err);
      } else {
        if (typeof req.stats !== 'object') {
          req.stats = {};
        }
        req.stats[this.model.collection.name] = result;
 
        return next();
      }
    });
  }
  public statsResponse(req: IApiRequest, res: Response, _next: NextFunction): Response {
    if (typeof req.stats !== 'object') {
      req.stats = {};
    }
 
    return res.status(200).json(req.stats);
  }
  public statistics(req: IApiRequest, res: Response, next: NextFunction): void {
    if (typeof this.model.statistics === 'function') {
      const query = req.dateRange || {};
      this.model.statistics(query, (err, result) => {
        if (err) {
          return this.respondServerError(res, err);
        } else {
          if (typeof req.stats !== 'object') {
            req.stats = {};
          }
          req.stats[this.model.collection.name] = result;
 
          return next();
        }
      });
    } else {
      return this.stats(req, res, next);
    }
  }
  public parseDateRange(
    req: IApiRequest,
    _res: Response,
    next: NextFunction,
    _id: string,
    _urlParam: string,
  ): void {
    // FIXME: this function is called twice for /year/month ....
    const year = parseInt(req.params.year, 10);
    let month = parseInt(req.params.month, 10);
    let toMonth = 12;
    if (!isNaN(year)) {
      if (isNaN(month)) {
        month = 0;
      } else {
        month = Math.max(Math.min(month, 12), 1);
        toMonth = --month + 1;
      }
      let from: Date = new Date();
      from = new Date(from.setFullYear(year, month, 1));
      from = new Date(from.setHours(0, 0, 0, 0));
      let to = new Date(from.valueOf());
      to = new Date(to.setFullYear(year, toMonth, 1));
 
      if (typeof req.stats !== 'object') {
        req.stats = {};
      }
      req.stats.range = {
        from: from,
        to: to,
      };
 
      req.dateRange = { $and: [{ date: { $gte: from }}, { date: { $lt: to }}]};
    }
 
    return next();
  }
  public processQuery(
    query: Request['query'],
    defaultQuery: IApiParsedQuery,
  ): IApiParsedQuery {
    const modelQuery = {
      offset: 0,
      deleted: false,
      filter: null,
      limit: 100,
      populate: null,
      q: {},
      select: null,
      sort: null,
      total: 0,
    };
    if (typeof query.offset === 'string') {
      modelQuery.offset = this.parsePagination(query.offset, defaultQuery.offset);
    }
    if (typeof query.limit === 'string') {
      modelQuery.limit = this.parsePagination(query.limit, defaultQuery.limit);
    }
    if (typeof query.sort === 'string') {
      modelQuery.sort = this.parseSort(query.sort);
    }
    if (typeof query.filter === 'string') {
      modelQuery.filter = this.parseFilter(query.filter);
    }
 
    return modelQuery;
  }
  public parseSort(sort: string | null = null): Record<string, -1 | 1> | null {
    Eif (sort) {
      const parsedSort: Record<string, -1 | 1> = {};
      let _sort: Record<string, string | number> = {};
      try {
        _sort = JSON.parse(sort);
 
      } catch (e) {
        /* istanbul ignore next */
        if (e.name === 'SyntaxError') {
          _sort = sort.split(' ')
            .filter(s => /^\w+$/.test(s))
            .reduce((acc: any, cur) => {
              acc[cur] = 1;
              return acc;
            }, {});
        }
      }
      Object.entries(_sort).forEach(([ key, value ]) => {
        const order = isString(value) ? parseInt(value, 10) : value;
        parsedSort[key] = isNaN(order) ? 1 : Math.min(Math.max(order, -1), 1) as -1 | 1;
      });
 
      Iif (Object.keys(parsedSort).length === 0) {
        parsedSort['date'] = -1;
      }
 
      return parsedSort;
    } else {
      return null;
    }
  }
  public parseFilter(filterQuery: string | null = null): Record<string, string> {
    let filter: Record<string, string> = {};
 
    try {
      filter = filterQuery ? JSON.parse(filterQuery.replace(/\'/g, '"')) : {};
    } catch (e) {
      filter = {};
    }
 
    const allowedFilters: Record<string, string> = {};
    this.filters.forEach(f => {
      if (typeof filter[f] !== 'undefined' && filter[f] !== null) {
        allowedFilters[f] = filter[f].toString();
      }
    });
 
    return allowedFilters;
  }
 
  public parsePagination(value: string, defaultValue: string | number): number {
    const _value = toNumber(value);
    const _default = toNumber(defaultValue);
 
    return isNaN(_value) ? _default : _value;
  }
 
 
  public parseQuery(query: IApiParsedQuery): IApiParsedQuery {
    return {
      q: {},
      offset: query.offset,
      limit: query.limit,
      sort: query.sort
        ? {
          ...query.sort,
        }
        : null,
      filter: {
        ...query.filter,
      },
      populate: query.populate
        ? [ ...query.populate ]
        : [],
      deleted: !!query.deleted,
      select: typeof query.select === 'string'
        ? query.select
        : {
          ...query.select,
        },
      total: 0,
    };
  }
 
}
 
export default BaseController;