All files / src api.controller.ts

100% Statements 32/32
100% Branches 18/18
100% Functions 11/11
100% Lines 32/32

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                          1x                       57x         3x             1x             1x         1x             1x         4x             4x         2x             2x         5x 2x             2x       3x 1x             2x       2x 2x 2x 1x     2x     4x   4x 4x 1x   3x 3x 3x             3x         13x       1x  
import {
  ObjectID,
} from 'bson';
import {
  Response,
  NextFunction,
} from 'express';
import {
  IApiRequest,
} from './types/IApiRequest';
import {
  IApiError,
} from './types/IApiError';
import {
  isString,
} from './helpers/isString';
import {
  IApiDocument,
  IApiModel,
} from './types/IApiModel';
 
abstract class ApiController<T extends IApiModel<K, R>, K = unknown, R = unknown> {
  protected model: T;
 
  constructor(model: T) {
    this.model = model;
  }
 
  // ERROR Responses
  public respondServerError(res: Response, error: any): Response {
    return res.status(500).json({ error });
  }
  public respondNotFound(
    id: string | number | ObjectID,
    res: Response,
    modelName: string,
  ): Response {
    const error: IApiError = {
      id: 'notFound',
      message: `${ modelName } ${ id } does not exist`,
      fields: {},
      errors: [],
    };
 
    return res.status(404).json({
      error: error,
    });
  }
  public respondInvalidId(res: Response): Response {
    const error: IApiError = {
      id: 'invalidId',
      message: 'Invalid id',
      fields: {},
      errors: [],
    };
 
    return res.status(400).json({
      error: error,
    });
  }
  public respondModelMissingError(res: Response): Response {
    const error: IApiError = {
      id: 'modelMissing',
      message: 'the model is missing in the request',
      fields: {},
      errors: [],
    };
 
    return res.status(400).json({
      error: error,
    });
  }
  public respondDeletionError(res: Response, err: IApiError): Response {
    const error: IApiError = {
      id: 'delete',
      message: err.message,
      fields: {},
      errors: [],
    };
 
    return res.status(400).json({
      error: error,
    });
  }
  public respondValidationError(err: any, res: Response, next: NextFunction): Response | void {
    if (err.name === 'ValidationError') {
      const error: IApiError = {
        id: 'validationError',
        message: err.message,
        fields: err.errors,
        errors: [],
      };
 
      return res.status(400).json({
        error: error,
      });
    }
    if (err.code === 11000) {
      return res.status(400).json({
        error: {
          id: 'duplicate',
          message: `${ this.model.modelName } already exists`,
        },
      });
    } else {
      return next(err);
    }
  }
  public apiResponse(req: IApiRequest, res: Response, _next: NextFunction): Response {
    const hasMetaError = req.meta && req.meta.error;
    let status = 200;
    if (hasMetaError) {
      status = 500;
    }
 
    return res.status(status).json({ meta: req.meta, data: req.data });
  }
  public populateMeta(req: IApiRequest, _res: Response, next: NextFunction): void {
    const qTotal = req.modelQuery.total || {};
 
    this.model.countDocuments(qTotal, (err: any, total: number) => {
      if (err) {
        return next(err);
      } else {
        const offset = req.modelQuery.offset;
        const limit = req.modelQuery.limit;
        req.meta = {
          total: total,
          count: req.data ? req.data.length : 0,
          offset: isString(offset) ? parseInt(offset, 10) : offset,
          limit: isString(limit) ? parseInt(limit, 10) : limit,
        };
 
        return next();
      }
    });
  }
  protected hasModel(model?: IApiDocument): model is IApiDocument {
    return typeof model !== 'undefined';
  }
}
 
export default ApiController;