@vasrefil/api-toolkit 1.0.3 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.js +6 -0
  3. package/dist/out-tsc/api-response/user.response.d.ts +48 -0
  4. package/dist/out-tsc/api-response/user.response.js +33 -0
  5. package/dist/out-tsc/app-middlewares/airbrake.d.ts +10 -0
  6. package/dist/out-tsc/app-middlewares/airbrake.js +58 -0
  7. package/dist/out-tsc/controllers/_root.control.d.ts +53 -0
  8. package/dist/out-tsc/controllers/_root.control.js +127 -0
  9. package/dist/out-tsc/controllers/index.d.ts +1 -0
  10. package/dist/out-tsc/controllers/index.js +17 -0
  11. package/dist/out-tsc/controllers/sample.control.d.ts +6 -0
  12. package/dist/out-tsc/controllers/sample.control.js +13 -0
  13. package/dist/out-tsc/env.d.ts +12 -0
  14. package/dist/out-tsc/env.js +16 -0
  15. package/dist/out-tsc/helpers/currency-formatter.helper.d.ts +1 -0
  16. package/dist/out-tsc/helpers/currency-formatter.helper.js +11 -0
  17. package/dist/out-tsc/helpers/query.helper.d.ts +22 -0
  18. package/dist/out-tsc/helpers/query.helper.js +133 -0
  19. package/dist/out-tsc/index.d.ts +1 -0
  20. package/dist/out-tsc/index.js +41 -0
  21. package/dist/out-tsc/interfaces/interface.d.ts +27 -0
  22. package/dist/out-tsc/interfaces/interface.js +2 -0
  23. package/dist/out-tsc/interfaces/root-controller.interface.d.ts +21 -0
  24. package/dist/out-tsc/interfaces/root-controller.interface.js +2 -0
  25. package/dist/out-tsc/interfaces/status.interface.d.ts +13 -0
  26. package/dist/out-tsc/interfaces/status.interface.js +17 -0
  27. package/dist/out-tsc/middlewares/auth.midware.d.ts +8 -0
  28. package/dist/out-tsc/middlewares/auth.midware.js +52 -0
  29. package/dist/out-tsc/middlewares/validator.midware.d.ts +12 -0
  30. package/dist/out-tsc/middlewares/validator.midware.js +32 -0
  31. package/dist/out-tsc/models/_config.d.ts +1 -0
  32. package/dist/out-tsc/models/_config.js +27 -0
  33. package/dist/out-tsc/models/sample.model.d.ts +33 -0
  34. package/dist/out-tsc/models/sample.model.js +14 -0
  35. package/dist/out-tsc/public-api.d.ts +1 -0
  36. package/dist/out-tsc/public-api.js +17 -0
  37. package/dist/out-tsc/routes/index.route.d.ts +9 -0
  38. package/dist/out-tsc/routes/index.route.js +54 -0
  39. package/dist/out-tsc/routes/sample.route.d.ts +16 -0
  40. package/dist/out-tsc/routes/sample.route.js +53 -0
  41. package/dist/out-tsc/services/_root.service.d.ts +12 -0
  42. package/dist/out-tsc/services/_root.service.js +75 -0
  43. package/dist/out-tsc/services/sample.service.d.ts +16 -0
  44. package/dist/out-tsc/services/sample.service.js +127 -0
  45. package/dist/out-tsc/utilities/date.util.d.ts +42 -0
  46. package/dist/out-tsc/utilities/date.util.js +93 -0
  47. package/dist/out-tsc/utilities/logger.util.d.ts +4 -0
  48. package/dist/out-tsc/utilities/logger.util.js +48 -0
  49. package/dist/out-tsc/utilities/token.util.d.ts +6 -0
  50. package/dist/out-tsc/utilities/token.util.js +48 -0
  51. package/dist/out-tsc/validations/sample.validator.d.ts +6 -0
  52. package/dist/out-tsc/validations/sample.validator.js +35 -0
  53. package/package.json +2 -2
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export {};
1
+ export declare const customMiddleware: (req: Request, res: Response, next: any) => void;
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.customMiddleware = void 0;
6
7
  const express_1 = __importDefault(require("express"));
7
8
  const path_1 = __importDefault(require("path"));
8
9
  const cors_1 = __importDefault(require("cors"));
@@ -39,3 +40,8 @@ app.use(errorHandler());
39
40
  app.listen(port, () => {
40
41
  console.log(`Server is running on port ${port}`);
41
42
  });
43
+ const customMiddleware = (req, res, next) => {
44
+ // Your middleware logic here
45
+ next();
46
+ };
47
+ exports.customMiddleware = customMiddleware;
@@ -0,0 +1,48 @@
1
+ import { Status } from '../interfaces/status.interface';
2
+ export declare const UserApiResp: {
3
+ NO_AUTHORIZATION_HEADER: {
4
+ code: string;
5
+ status: Status;
6
+ message: string;
7
+ };
8
+ NOT_AUTHORIZED: {
9
+ code: string;
10
+ status: Status;
11
+ message: string;
12
+ };
13
+ USER_NOT_FOUND: {
14
+ code: string;
15
+ status: Status;
16
+ message: string;
17
+ };
18
+ USER_DEACTIVATED: {
19
+ code: string;
20
+ status: Status;
21
+ message: string;
22
+ };
23
+ UNVERIFIED_EMAIL: {
24
+ code: string;
25
+ status: Status;
26
+ message: string;
27
+ };
28
+ UNCOMPELETE_ACCOUNT_SETUP: {
29
+ code: string;
30
+ status: Status;
31
+ message: string;
32
+ };
33
+ UNCOMPELETE_PIN_SETUP: {
34
+ code: string;
35
+ status: Status;
36
+ message: string;
37
+ };
38
+ NO_PIN_TOKEN_HEADER: {
39
+ code: string;
40
+ status: Status;
41
+ message: string;
42
+ };
43
+ EXPIRED_PIN_TOKEN: {
44
+ code: string;
45
+ status: Status;
46
+ message: string;
47
+ };
48
+ };
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UserApiResp = void 0;
4
+ const status_interface_1 = require("../interfaces/status.interface");
5
+ exports.UserApiResp = {
6
+ NO_AUTHORIZATION_HEADER: {
7
+ code: 'NAH0401', status: status_interface_1.Status.UN_AUTHORIZED, message: 'Please specify authorization header'
8
+ },
9
+ NOT_AUTHORIZED: {
10
+ code: 'NA00401', status: status_interface_1.Status.UN_AUTHORIZED, message: 'You are not authorized'
11
+ },
12
+ USER_NOT_FOUND: {
13
+ code: 'UNF0401', status: status_interface_1.Status.UN_AUTHORIZED, message: 'User not found'
14
+ },
15
+ USER_DEACTIVATED: {
16
+ code: 'UD00401', status: status_interface_1.Status.UN_AUTHORIZED, message: 'Your account has been deactivated'
17
+ },
18
+ UNVERIFIED_EMAIL: {
19
+ code: 'UE00403', status: status_interface_1.Status.FORBIDDEN, message: 'Your email address is not verified'
20
+ },
21
+ UNCOMPELETE_ACCOUNT_SETUP: {
22
+ code: 'UAS0403', status: status_interface_1.Status.FORBIDDEN, message: 'Account setup is not completed'
23
+ },
24
+ UNCOMPELETE_PIN_SETUP: {
25
+ code: 'UPS0403', status: status_interface_1.Status.FORBIDDEN, message: 'Pin setup is not completed'
26
+ },
27
+ NO_PIN_TOKEN_HEADER: {
28
+ code: 'NPTH401', status: status_interface_1.Status.UN_AUTHORIZED, message: 'Please specify pin_token header'
29
+ },
30
+ EXPIRED_PIN_TOKEN: {
31
+ code: 'EPT0401', status: status_interface_1.Status.UN_AUTHORIZED, message: 'Your session has expired, Please login with your pin'
32
+ },
33
+ };
@@ -0,0 +1,10 @@
1
+ import { ServiceRespI } from '../interfaces/interface';
2
+ declare class AirbrakeLogger {
3
+ private airbrake;
4
+ constructor(projectId: string, projectKey: string);
5
+ logRequestError(serviceResponse: ServiceRespI): void;
6
+ logError(error: any, params: any, route: any): void;
7
+ getAirbrakeInstance(): any;
8
+ getAirbrakeExpress(): any;
9
+ }
10
+ export { AirbrakeLogger };
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AirbrakeLogger = void 0;
7
+ const env_1 = __importDefault(require("../env"));
8
+ const Airbrake = require('@airbrake/node');
9
+ const airbrakeExpress = require('@airbrake/node/dist/instrumentation/express');
10
+ const json_stringify_safe = require('json-stringify-safe');
11
+ class AirbrakeLogger {
12
+ constructor(projectId, projectKey) {
13
+ this.airbrake = new Airbrake.Notifier({
14
+ projectId: projectId,
15
+ projectKey: projectKey,
16
+ environment: `${env_1.default.NODE_ENV}`
17
+ });
18
+ }
19
+ logRequestError(serviceResponse) {
20
+ try {
21
+ const { request, error, data, message, actionType } = serviceResponse;
22
+ const dataErr = data ? json_stringify_safe(data) : null;
23
+ const errorErr = error ? json_stringify_safe(error, null) : null;
24
+ const messageErr = message ? json_stringify_safe(message) : null;
25
+ const error_ = messageErr || errorErr || dataErr;
26
+ const actionType_ = actionType || 'App Error';
27
+ const body = request && request.body ? request.body : 'no body';
28
+ const url = request && request.url ? request.url : 'no url';
29
+ this.airbrake.notify({
30
+ error: error_,
31
+ params: { url, body, actionType: actionType_ },
32
+ route: url
33
+ });
34
+ }
35
+ catch (error) {
36
+ this.airbrake.notify(error);
37
+ }
38
+ }
39
+ logError(error, params, route) {
40
+ try {
41
+ this.airbrake.notify({
42
+ error: json_stringify_safe(error, null),
43
+ params,
44
+ route
45
+ });
46
+ }
47
+ catch (error) {
48
+ this.airbrake.notify(error);
49
+ }
50
+ }
51
+ getAirbrakeInstance() {
52
+ return this.airbrake;
53
+ }
54
+ getAirbrakeExpress() {
55
+ return airbrakeExpress;
56
+ }
57
+ }
58
+ exports.AirbrakeLogger = AirbrakeLogger;
@@ -0,0 +1,53 @@
1
+ /// <reference types="mongoose/types/aggregate" />
2
+ /// <reference types="mongoose/types/callback" />
3
+ /// <reference types="mongoose/types/collection" />
4
+ /// <reference types="mongoose/types/connection" />
5
+ /// <reference types="mongoose/types/cursor" />
6
+ /// <reference types="mongoose/types/document" />
7
+ /// <reference types="mongoose/types/error" />
8
+ /// <reference types="mongoose/types/expressions" />
9
+ /// <reference types="mongoose/types/helpers" />
10
+ /// <reference types="mongoose/types/middlewares" />
11
+ /// <reference types="mongoose/types/indexes" />
12
+ /// <reference types="mongoose/types/models" />
13
+ /// <reference types="mongoose/types/mongooseoptions" />
14
+ /// <reference types="mongoose/types/pipelinestage" />
15
+ /// <reference types="mongoose/types/populate" />
16
+ /// <reference types="mongoose/types/query" />
17
+ /// <reference types="mongoose/types/schemaoptions" />
18
+ /// <reference types="mongoose/types/schematypes" />
19
+ /// <reference types="mongoose/types/session" />
20
+ /// <reference types="mongoose/types/types" />
21
+ /// <reference types="mongoose/types/utility" />
22
+ /// <reference types="mongoose/types/validation" />
23
+ /// <reference types="mongoose/types/virtuals" />
24
+ /// <reference types="mongoose/types/inferschematype" />
25
+ import { Model } from 'mongoose';
26
+ import { FetchAllQuery, FetchWithPaginationDataI, ModelPopulateI, NestedRecordQueryOptionsI } from '../interfaces/root-controller.interface';
27
+ export declare class RootController {
28
+ private model;
29
+ private modelName;
30
+ constructor(model: Model<any>, modelName?: string);
31
+ unique: (conditions: {
32
+ key: string;
33
+ value: string;
34
+ }) => Promise<boolean>;
35
+ getDocumentCount: (conditon?: {}, query?: object) => Promise<number>;
36
+ create: (payload: any) => Promise<any>;
37
+ fetchAll(condition?: object, query?: FetchAllQuery, select?: string | object, populate?: any): import("mongoose").Query<Omit<any, never>[], any, {}, any>;
38
+ fetchAllWithPagination: (conditon: object, query?: FetchAllQuery, select?: string | object, populate?: ModelPopulateI[]) => Promise<FetchWithPaginationDataI>;
39
+ getOneP: (condition: object, select?: any) => Promise<any>;
40
+ getOne(condition: object, select?: string | object, populate?: any): any;
41
+ getById: (id: string, select?: string | object) => Promise<any>;
42
+ updateOne(condition: object, updateValues: object): any;
43
+ updateMany(condition: object, updateValues: object): import("mongoose").Query<import("mongodb").UpdateResult, any, {}, any>;
44
+ updateById(id: string, updateValues: object): any;
45
+ deleteOne(condition: object): import("mongoose").Query<import("mongodb").DeleteResult, any, {}, any>;
46
+ deleteMany(condition: object): import("mongoose").Query<import("mongodb").DeleteResult, any, {}, any>;
47
+ deleteById(id: string): import("mongoose").Query<any, any, {}, any>;
48
+ search: (payload: {
49
+ key: any;
50
+ value: any;
51
+ }, select?: string) => Promise<never>;
52
+ getNestedRecord: (options: NestedRecordQueryOptionsI, errorMessage?: string) => Promise<any>;
53
+ }
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RootController = void 0;
4
+ const query_helper_1 = require("../helpers/query.helper");
5
+ class RootController {
6
+ constructor(model, modelName = 'Document') {
7
+ this.unique = async (conditions) => {
8
+ const { key, value } = conditions;
9
+ const res = await this.model.findOne({ [key]: value });
10
+ if (res) {
11
+ return false;
12
+ }
13
+ else {
14
+ return true;
15
+ }
16
+ };
17
+ this.getDocumentCount = async (conditon = {}, query) => {
18
+ const { filter } = query_helper_1.QueryHelper.build_query(query);
19
+ return await this.model.countDocuments({ ...filter, ...conditon });
20
+ };
21
+ this.create = async (payload) => {
22
+ try {
23
+ const document = await (this.model.create({ ...payload }));
24
+ return document.toJSON();
25
+ }
26
+ catch (error) {
27
+ throw error;
28
+ }
29
+ };
30
+ this.fetchAllWithPagination = async (conditon, query, select = '', populate) => {
31
+ try {
32
+ const records = await this.fetchAll(conditon, query, select, populate);
33
+ const total_records = await this.getDocumentCount(conditon, query);
34
+ return { records, total_records };
35
+ }
36
+ catch (error) {
37
+ throw error;
38
+ }
39
+ };
40
+ this.getOneP = async (condition, select) => {
41
+ try {
42
+ select = select ? select : '';
43
+ const document = await this.model.findOne(condition).select(select).lean();
44
+ if (!document)
45
+ throw { message: `${this.modelName} not found` };
46
+ return document;
47
+ }
48
+ catch (error) {
49
+ throw error;
50
+ }
51
+ };
52
+ this.getById = async (id, select = '') => {
53
+ try {
54
+ const document = await this.model.findById(id).select(select).lean();
55
+ if (!document)
56
+ throw { message: `${this.modelName} not found` };
57
+ return document;
58
+ }
59
+ catch (error) {
60
+ throw error;
61
+ }
62
+ };
63
+ this.search = async (payload, select = '') => {
64
+ try {
65
+ const regrex = new RegExp(`${payload.value}`, 'i');
66
+ const records = await this.model.find({ [payload.key]: { $regex: regrex } }).select(select);
67
+ if (!records)
68
+ throw { message: `${this.modelName} not found` };
69
+ throw records;
70
+ }
71
+ catch (error) {
72
+ throw error;
73
+ }
74
+ };
75
+ this.getNestedRecord = async (options, errorMessage) => {
76
+ const { parentField, childIdField = '_id', parentId, childId } = options;
77
+ // Build the query
78
+ const query = {
79
+ _id: parentId,
80
+ [`${parentField}.${childIdField}`]: { $eq: childId }
81
+ };
82
+ // Build the projection
83
+ const projection = {
84
+ [parentField]: {
85
+ $elemMatch: {
86
+ [childIdField]: childId
87
+ }
88
+ }
89
+ };
90
+ // Execute the query
91
+ const result = await this.model.findOne(query, projection);
92
+ if (!result) {
93
+ throw new Error(errorMessage || `Nested record not found in ${parentField}`);
94
+ }
95
+ // Return the first element of the matched array
96
+ return result[parentField][0];
97
+ };
98
+ this.model = model;
99
+ this.modelName = modelName;
100
+ }
101
+ fetchAll(condition = {}, query, select = '', populate) {
102
+ const { filter, skip, limit, sort } = query_helper_1.QueryHelper.build_query(query);
103
+ return this.model.find({ ...filter, ...condition }).select(select).skip(skip).limit(limit).sort(sort).populate(populate);
104
+ }
105
+ getOne(condition, select = '', populate) {
106
+ return this.model.findOne(condition).select(select).populate(populate).lean();
107
+ }
108
+ updateOne(condition, updateValues) {
109
+ return this.model.updateOne({ ...condition }, { ...updateValues }, { new: true });
110
+ }
111
+ updateMany(condition, updateValues) {
112
+ return this.model.updateMany({ ...condition }, { ...updateValues }).lean();
113
+ }
114
+ updateById(id, updateValues) {
115
+ return this.model.findByIdAndUpdate(id, { ...updateValues }, { new: true }).lean();
116
+ }
117
+ deleteOne(condition) {
118
+ return this.model.deleteOne({ ...condition });
119
+ }
120
+ deleteMany(condition) {
121
+ return this.model.deleteMany({ ...condition });
122
+ }
123
+ deleteById(id) {
124
+ return this.model.findByIdAndDelete(id);
125
+ }
126
+ }
127
+ exports.RootController = RootController;
@@ -0,0 +1 @@
1
+ export * from "./_root.control";
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./_root.control"), exports);
@@ -0,0 +1,6 @@
1
+ import { RootController } from './_root.control';
2
+ declare class SampleController extends RootController {
3
+ constructor();
4
+ }
5
+ declare const _default: SampleController;
6
+ export default _default;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const _root_control_1 = require("./_root.control");
7
+ const sample_model_1 = __importDefault(require("../models/sample.model"));
8
+ class SampleController extends _root_control_1.RootController {
9
+ constructor() {
10
+ super(sample_model_1.default);
11
+ }
12
+ }
13
+ exports.default = new SampleController;
@@ -0,0 +1,12 @@
1
+ declare const env: {
2
+ MONGODB_URI: string | undefined;
3
+ ADMIN_JWT_KEY: string;
4
+ NODE_ENV: string | undefined;
5
+ RATE_LIMIT_REDIS_URL: string | undefined;
6
+ API_KEY: string | undefined;
7
+ AIRBRAKE: {
8
+ PROJECT_ID: string | undefined;
9
+ PROJECT_KEY: string | undefined;
10
+ };
11
+ };
12
+ export default env;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const dotenv = require('dotenv');
4
+ dotenv.config();
5
+ const env = {
6
+ MONGODB_URI: process.env.MONGODB_URI,
7
+ ADMIN_JWT_KEY: process.env.ADMIN_JWT_KEY,
8
+ NODE_ENV: process.env.NODE_ENV,
9
+ RATE_LIMIT_REDIS_URL: process.env.RATE_LIMIT_REDIS_URL,
10
+ API_KEY: process.env.API_KEY,
11
+ AIRBRAKE: {
12
+ PROJECT_ID: process.env.AIRBRAKE_PROJECT_ID,
13
+ PROJECT_KEY: process.env.AIRBRAKE_PROJECT_KEY
14
+ },
15
+ };
16
+ exports.default = env;
@@ -0,0 +1 @@
1
+ export declare const currency_fmt: (value: any) => string;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.currency_fmt = void 0;
4
+ const currency_fmt = (value) => {
5
+ const result = new Intl.NumberFormat('en-NG', {
6
+ style: 'currency',
7
+ currency: 'NGN',
8
+ }).format(value);
9
+ return result;
10
+ };
11
+ exports.currency_fmt = currency_fmt;
@@ -0,0 +1,22 @@
1
+ declare class QueryHelper_ {
2
+ build_query(query: any): {
3
+ sort: any;
4
+ limit: number;
5
+ skip: number;
6
+ filter: any;
7
+ page: number;
8
+ };
9
+ get_date_range(payload: {
10
+ date_type: string;
11
+ date_range: {
12
+ start_date: Date;
13
+ end_date: Date;
14
+ };
15
+ }): {};
16
+ get_filters(filter: any): any;
17
+ process_filters: (query: any) => {} | undefined;
18
+ private get_sort;
19
+ private str_to_obj;
20
+ }
21
+ declare const QueryHelper: QueryHelper_;
22
+ export { QueryHelper };
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryHelper = void 0;
4
+ const date_util_1 = require("../utilities/date.util");
5
+ class QueryHelper_ {
6
+ constructor() {
7
+ this.process_filters = (query) => {
8
+ try {
9
+ const { filters } = query;
10
+ let result = [];
11
+ let filter_query = {};
12
+ const filters_ = filters ? this.str_to_obj(filters) : {};
13
+ if (filters_ && filters_.filterSet && filters_.filterSet.length && filters_.conjunction) {
14
+ const logical_operator = filters_.conjunction == 'and' ? '$and' : '$or';
15
+ filters_.filterSet.forEach(fit => {
16
+ if (fit.operator === 'contains') {
17
+ result.push({ [fit.field]: { $regex: fit.value, $options: 'i' } });
18
+ }
19
+ else if (fit.operator === 'does_not_contain') {
20
+ result.push({ [fit.field]: { $not: { $regex: fit.value, $options: 'i' } } });
21
+ }
22
+ else if (fit.operator === 'is') {
23
+ result.push({ [fit.field]: { $eq: fit.value } });
24
+ }
25
+ else if (fit.operator === 'is_not') {
26
+ result.push({ [fit.field]: { $ne: fit.value } });
27
+ }
28
+ });
29
+ filter_query = { [logical_operator]: result };
30
+ }
31
+ return filter_query;
32
+ }
33
+ catch (error) {
34
+ console.log(error);
35
+ }
36
+ };
37
+ }
38
+ build_query(query) {
39
+ if (!query)
40
+ query = {};
41
+ const { filter, limit, page, filterRange, date_range, date_type, search } = query;
42
+ let range = filterRange ? this.str_to_obj(filterRange) : null;
43
+ const filterx = filter ? this.str_to_obj(filter) : {};
44
+ let searchx = search ? this.str_to_obj(search) : {};
45
+ const date_rangex = date_range ? this.str_to_obj(date_range) : {};
46
+ const pagex = page ? Number(page) : 1;
47
+ const skipx = page ? ((Number(page) - 1) * limit) : 0;
48
+ const limitx = Number(limit) || 20;
49
+ if (range) {
50
+ const { field, ranges: { from, to } } = range;
51
+ range = { [field]: { $gte: from, $lt: to } };
52
+ }
53
+ searchx = searchx.key && searchx.value ? searchx : null;
54
+ const filterResult = range || filterx || {};
55
+ const date_range_ = this.get_date_range({ date_type, date_range: date_rangex });
56
+ const search_ = searchx ? { [searchx.key]: { $regex: new RegExp(`${searchx.value}`, 'i') } } : {};
57
+ const filters = this.process_filters(query);
58
+ const sort = this.get_sort(query);
59
+ const filter_result = { ...filterResult, ...date_range_, ...search_, ...filters };
60
+ return { sort, limit: limitx, filter: filter_result, skip: skipx, page: pagex };
61
+ }
62
+ get_date_range(payload) {
63
+ let date_filter_range = null;
64
+ let filter = {};
65
+ const { date_type, date_range } = payload;
66
+ if (date_type === 'today') {
67
+ date_filter_range = date_util_1.DateUtil.get_today_date_range();
68
+ }
69
+ else if (date_type === 'this_week') {
70
+ date_filter_range = date_util_1.DateUtil.this_week_date_range();
71
+ }
72
+ else if (date_type === 'this_month') {
73
+ date_filter_range = date_util_1.DateUtil.this_month_date_range();
74
+ }
75
+ else if (date_type === 'this_year') {
76
+ date_filter_range = date_util_1.DateUtil.this_year_date_range();
77
+ }
78
+ else if (date_type === 'custom' && date_range && (date_range.start_date && date_range.end_date)) {
79
+ date_filter_range = date_util_1.DateUtil.get_custom_date_range(date_range);
80
+ }
81
+ else if (date_type === 'last_30_days') {
82
+ const d = date_util_1.DateUtil.get_date_range({ date: new Date(), number_of_days: 30 });
83
+ filter = { createdAt: { $gte: d.start_date } };
84
+ }
85
+ if (date_filter_range) {
86
+ filter = { createdAt: { $gte: date_filter_range.start_date, $lt: date_filter_range.end_date } };
87
+ }
88
+ return filter;
89
+ }
90
+ get_filters(filter) {
91
+ const filters = {};
92
+ if (!filter)
93
+ return filters;
94
+ for (const [key, value] of Object.entries(filter)) {
95
+ const value_ = value;
96
+ if (key === 'createdAt') {
97
+ filters.startDate = value_['$gte'];
98
+ filters.endDate = value_['$lt'];
99
+ }
100
+ else if (key === '$or' || key === '$and') {
101
+ const values = value;
102
+ if (values && values.length) {
103
+ values.forEach(item => {
104
+ const arrKey = Object.keys(item)[0];
105
+ const arrValue = Object.values(item)[0];
106
+ filters[arrKey] = arrValue ? arrValue['$eq'] : null;
107
+ });
108
+ }
109
+ }
110
+ else {
111
+ filters[key] = value;
112
+ }
113
+ }
114
+ return filters;
115
+ }
116
+ get_sort(query) {
117
+ try {
118
+ const { key, value } = query.sort ? this.str_to_obj(query.sort) : {};
119
+ const single_sort = { [key || 'createdAt']: value || '-1' };
120
+ const sorts = query.sorts ? this.str_to_obj(query.sorts) : {};
121
+ const sort = Object.values(sorts).length ? sorts : single_sort;
122
+ return sort;
123
+ }
124
+ catch (error) {
125
+ throw error;
126
+ }
127
+ }
128
+ str_to_obj(string) {
129
+ return JSON.parse(string);
130
+ }
131
+ }
132
+ const QueryHelper = new QueryHelper_;
133
+ exports.QueryHelper = QueryHelper;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const express_1 = __importDefault(require("express"));
7
+ const path_1 = __importDefault(require("path"));
8
+ const cors_1 = __importDefault(require("cors"));
9
+ const helmet_1 = __importDefault(require("helmet"));
10
+ const errorHandler = require("errorhandler");
11
+ const _config_1 = require("./models/_config");
12
+ const index_route_1 = require("./routes/index.route");
13
+ const logger_util_1 = require("./utilities/logger.util");
14
+ // import { airbrake, airbrakeExpress } from './app-middlewares/airbrake';
15
+ const port = process.env.PORT || 8082;
16
+ const app = (0, express_1.default)();
17
+ //configure application
18
+ app.use(express_1.default.static(path_1.default.join(__dirname, "public")));
19
+ //mount json form parser
20
+ app.use(express_1.default.json());
21
+ //mount query string parser
22
+ app.use(express_1.default.urlencoded({ extended: true }));
23
+ app.use((0, helmet_1.default)());
24
+ app.use(logger_util_1.morgan);
25
+ //cors error allow
26
+ app.options("*", (0, cors_1.default)());
27
+ app.use((0, cors_1.default)());
28
+ // catch 404 and forward to error handler
29
+ app.use(function (err, req, res, next) {
30
+ err.status = 404;
31
+ next(err);
32
+ });
33
+ //error handling
34
+ app.use(errorHandler());
35
+ (0, _config_1.dbConfig)();
36
+ // app.use(airbrakeExpress.makeMiddleware(airbrake));
37
+ (0, index_route_1.routes)(app);
38
+ // app.use(airbrakeExpress.makeErrorHandler(airbrake));
39
+ app.listen(port, () => {
40
+ console.log(`Server is running on port ${port}`);
41
+ });