my-q-format-response-aws-lambda 1.0.1

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.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ my-q-format-response-aws-lambda
package/index.js ADDED
@@ -0,0 +1,322 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.controlResponseNull = exports.normaliseMongoPaginate = exports.normaliseMongoFilter = exports.optionsPaginationParams = exports.messagesREST = exports.CreateResponse = exports.ResponseVO = exports.ResponseBodyVO = exports.StatusCode = exports.StatusResult = void 0;
4
+ class StatusResult {
5
+ }
6
+ exports.StatusResult = StatusResult;
7
+ StatusResult.ok = 'Ok';
8
+ StatusResult.error = 'Error';
9
+ StatusResult.notFound = 'NotFound';
10
+ class StatusCode {
11
+ }
12
+ exports.StatusCode = StatusCode;
13
+ // static SwitchingProtocols = 101;
14
+ // static Continue = 100;
15
+ // static Processing = 102;
16
+ StatusCode.OK = 200;
17
+ StatusCode.Created = 201;
18
+ StatusCode.Accepted = 202;
19
+ StatusCode.NonAuthoritativeInformation = 203;
20
+ StatusCode.NoContent = 204;
21
+ // static ResetContent = 205;
22
+ // static PartialContent = 206;
23
+ // static MultiStatus = 207;
24
+ // static MultipleChoices = 300;
25
+ // static MovedPermanently = 301;
26
+ // static MovedTemporarily = 302;
27
+ // static SeeOther = 303;
28
+ // static UseProxy = 305;
29
+ // static NotModified = 304;
30
+ // static TemporaryRedirect = 307;
31
+ StatusCode.BadRequest = 400;
32
+ StatusCode.Unauthorized = 401;
33
+ StatusCode.PaymentRequired = 402;
34
+ StatusCode.NotFound = 404;
35
+ StatusCode.Forbidden = 403;
36
+ // static MethodNotAllowed = 405;
37
+ // static ProxyAuthenticationRequired = 407;
38
+ // static NotAcceptable = 406;
39
+ // static RequestTimeOut = 408;
40
+ // static Gone = 410;
41
+ // static Conflict = 409;
42
+ // static LengthRequired = 411;
43
+ // static RequestEntityTooLarge = 413;
44
+ // static PreconditionFailed = 412;
45
+ // static RequestURITooLarge = 414;
46
+ // static RequestedRangeNotSatisfiable = 416;
47
+ // static UnsupportedMediaType = 415;
48
+ // static ExpectationFailed = 417;
49
+ // static UnprocessableEntity = 422;
50
+ // static ImATeapot = 418;
51
+ // static Locked = 423;
52
+ // static FailedDependency = 424;
53
+ // static UnorderedCollection = 425;
54
+ // static UpgradeRequired = 426;
55
+ // static PreconditionRequired = 428;
56
+ // static TooManyRequests = 429;
57
+ // static RequestHeaderFieldsTooLarge = 431;
58
+ StatusCode.InternalServerError = 500;
59
+ StatusCode.NotImplemented = 501;
60
+ StatusCode.BadGateway = 502;
61
+ class ResponseBodyVO {
62
+ constructor() {
63
+ this.statusResult = StatusResult.ok;
64
+ this.message = '';
65
+ this.data = null;
66
+ this.count = null;
67
+ this.error = null;
68
+ }
69
+ }
70
+ exports.ResponseBodyVO = ResponseBodyVO;
71
+ class ResponseVO {
72
+ constructor() {
73
+ this.statusCode = StatusCode.OK;
74
+ this.body = '';
75
+ }
76
+ }
77
+ exports.ResponseVO = ResponseVO;
78
+ class Result {
79
+ constructor({ statusCode = StatusCode.OK, statusResult = StatusResult.ok, message, data = null, count = null, error = null, bodyWrap = true, }) {
80
+ this.statusCode = statusCode;
81
+ this.statusResult = statusResult;
82
+ this.message = !message ? '' : message;
83
+ this.count = count;
84
+ this.data = data;
85
+ this.error = error;
86
+ this.bodyWrap = bodyWrap;
87
+ }
88
+ /**
89
+ * Serverless: According to the API Gateway specs, the body content must be stringified
90
+ * If use to AWS Appsync need response value without body wrap
91
+ */
92
+ bodyToString() {
93
+ let _err = this.error && this.error.message ? this.error.message : !this.error ? null : JSON.stringify(this.error);
94
+ const valueBody = {
95
+ statusResult: this.statusResult, message: this.message, data: this.data, count: this.count, error: _err,
96
+ };
97
+ const valueBodyWrap = {
98
+ statusCode: this.statusCode, body: JSON.stringify(valueBody),
99
+ };
100
+ return this.bodyWrap ? valueBodyWrap : valueBody;
101
+ }
102
+ }
103
+ class CreateResponse {
104
+ /**
105
+ * Success
106
+ * @param data
107
+ * @param count
108
+ * @param message
109
+ * @param bodyWrap
110
+ */
111
+ static success({ data = null, count = null, message = 'success', bodyWrap = true }) {
112
+ const result = new Result({
113
+ statusCode: StatusCode.OK, statusResult: StatusResult.ok, message, data, count, bodyWrap,
114
+ });
115
+ return result.bodyToString();
116
+ }
117
+ /**
118
+ * Created
119
+ * @param data
120
+ * @param message
121
+ * @param bodyWrap
122
+ */
123
+ static created({ data, message = 'created', bodyWrap = true }) {
124
+ const result = new Result({
125
+ statusCode: StatusCode.Created, statusResult: StatusResult.ok, message, data, bodyWrap,
126
+ });
127
+ return result.bodyToString();
128
+ }
129
+ /**
130
+ * Update
131
+ * @param data
132
+ * @param message
133
+ * @param bodyWrap
134
+ */
135
+ static updated({ data, message = 'updated', bodyWrap = true }) {
136
+ const result = new Result({
137
+ statusCode: StatusCode.OK, statusResult: StatusResult.ok, message, data, bodyWrap,
138
+ });
139
+ return result.bodyToString();
140
+ }
141
+ /**
142
+ * Not Found
143
+ * @param error
144
+ * @param message
145
+ * @param bodyWrap
146
+ */
147
+ static notFound({ error = null, message = '', bodyWrap = true }) {
148
+ const result = new Result({
149
+ statusCode: StatusCode.NotFound, statusResult: StatusResult.notFound, message, error, bodyWrap,
150
+ });
151
+ return result.bodyToString();
152
+ }
153
+ /**
154
+ * Error
155
+ * @param error
156
+ * @param statusCode
157
+ * @param message
158
+ * @param bodyWrap
159
+ */
160
+ static error({ error = null, statusCode = StatusCode.BadRequest, message = 'Error', bodyWrap = true, }) {
161
+ const result = new Result({
162
+ statusCode, statusResult: StatusResult.error, error, message, bodyWrap,
163
+ });
164
+ return result.bodyToString();
165
+ }
166
+ /**
167
+ * Custom
168
+ * @param statusCode
169
+ * @param statusResult
170
+ * @param message
171
+ * @param error
172
+ * @param data
173
+ * @param count
174
+ * @param bodyWrap
175
+ */
176
+ static custom({ statusCode = StatusCode.OK, statusResult = StatusResult.ok, message = '', error = null, data = null, count = null, bodyWrap = true, }) {
177
+ const result = new Result({
178
+ statusCode, statusResult, message, error, data, count, bodyWrap,
179
+ });
180
+ return result.bodyToString();
181
+ }
182
+ }
183
+ exports.CreateResponse = CreateResponse;
184
+ const messagesREST = (prefix, suffix = '') => {
185
+ return {
186
+ TOTAL: `${prefix}_TOTAL${suffix}`,
187
+ CREATE: `${prefix}_ITEM_CREATE${suffix}`,
188
+ NOT_CREATE: `${prefix}_ITEM_NOT_CREATE${suffix}`,
189
+ ERROR_CREATE: `${prefix}_ITEM_ERROR_CREATE${suffix}`,
190
+ UPDATE: `${prefix}_ITEM_UPDATE${suffix}`,
191
+ UPDATE_MANY: `${prefix}_ITEM_UPDATE_MANY${suffix}`,
192
+ NOT_UPDATE: `${prefix}_ITEM_NOT_UPDATE${suffix}`,
193
+ NOT_UPDATE_MANY: `${prefix}_ITEM_NOT_UPDATE_MANY${suffix}`,
194
+ ERROR_UPDATE: `${prefix}_ITEM_ERROR_UPDATE${suffix}`,
195
+ ERROR_UPDATE_MANY: `${prefix}_ITEM_ERROR_UPDATE_MANY${suffix}`,
196
+ GET: `${prefix}_ITEM_GET${suffix}`,
197
+ NOT_GET: `${prefix}_ITEM_NOT_GET${suffix}`,
198
+ ERROR_GET: `${prefix}_ITEM_ERROR_GET${suffix}`,
199
+ GET_MANY: `${prefix}_GET_MANY${suffix}`,
200
+ NOT_GET_MANY: `${prefix}_NOT_GET_MANY${suffix}`,
201
+ ERROR_GET_MANY: `${prefix}_ERROR_GET_MANY${suffix}`,
202
+ GET_MANY_AND_COUNT: `${prefix}_GET_MANY_AND_COUNT${suffix}`,
203
+ NOT_GET_MANY_AND_COUNT: `${prefix}_NOT_GET_MANY_AND_COUNT${suffix}`,
204
+ ERROR_GET_MANY_AND_COUNT: `${prefix}_ERROR_GET_MANY_AND_COUNT${suffix}`,
205
+ GET_COUNT: `${prefix}_GET_COUNT${suffix}`,
206
+ NOT_GET_COUNT: `${prefix}_NOT_GET_COUNT${suffix}`,
207
+ ERROR_GET_COUNT: `${prefix}_ERROR_GET_COUNT${suffix}`,
208
+ DELETE: `${prefix}_ITEM_DELETE${suffix}`,
209
+ NOT_DELETE: `${prefix}_ITEM_NOT_DELETE${suffix}`,
210
+ ERROR_DELETE: `${prefix}_ITEM_ERROR_DELETE${suffix}`,
211
+ DELETE_MANY: `${prefix}_DELETE_MANY${suffix}`,
212
+ NOT_DELETE_MANY: `${prefix}_NOT_DELETE_MANY${suffix}`,
213
+ ERROR_DELETE_MANY: `${prefix}_ERROR_DELETE_MANY${suffix}`,
214
+ NOT_FOUND: `${prefix}_NOT_FOUND${suffix}`,
215
+ INITIALISE: `${prefix}_INITIALISE${suffix}`,
216
+ NOT_INITIALISE: `${prefix}_NOT_INITIALISE${suffix}`,
217
+ ERROR_INITIALISE: `${prefix}_ERROR_INITIALISE${suffix}`,
218
+ INCREMENT: `${prefix}_INCREMENT${suffix}`,
219
+ NOT_INCREMENT: `${prefix}_NOT_INCREMENT${suffix}`,
220
+ ERROR_INCREMENT: `${prefix}_ERROR_INCREMENT${suffix}`,
221
+ DECREMENT: `${prefix}_DECREMENT${suffix}`,
222
+ NOT_DECREMENT: `${prefix}_NOT_DECREMENT${suffix}`,
223
+ ERROR_DECREMENT: `${prefix}_ERROR_DECREMENT${suffix}`,
224
+ COUNTER_DAY: `${prefix}_COUNTER_DAY${suffix}`,
225
+ NOT_COUNTER_DAY: `${prefix}_NOT_COUNTER_DAY${suffix}`,
226
+ ERROR_COUNTER_DAY: `${prefix}_ERROR_COUNTER_DAY${suffix}`,
227
+ COUNTER_MONTH: `${prefix}_COUNTER_MONTH${suffix}`,
228
+ NOT_COUNTER_MONTH: `${prefix}_NOT_COUNTER_MONTH${suffix}`,
229
+ ERROR_COUNTER_MONTH: `${prefix}_ERROR_COUNTER_MONTH${suffix}`,
230
+ COUNTER_YEAR: `${prefix}_COUNTER_YEAR${suffix}`,
231
+ NOT_COUNTER_YEAR: `${prefix}_NOT_COUNTER_YEAR${suffix}`,
232
+ TEST: `${prefix}_TEST${suffix}`,
233
+ NOT_TEST: `${prefix}_NOT_TEST${suffix}`,
234
+ ERROR_TEST: `${prefix}_ERROR_TEST${suffix}`,
235
+ AGGREGATION: `${prefix}_AGGREGATION${suffix}`,
236
+ NOT_AGGREGATION: `${prefix}_NOT_AGGREGATION${suffix}`,
237
+ ERROR_AGGREGATION: `${prefix}_ERROR_AGGREGATION${suffix}`,
238
+ };
239
+ };
240
+ exports.messagesREST = messagesREST;
241
+ exports.optionsPaginationParams = ['limit', 'skip', 'count'];
242
+ /**
243
+ * Normalise filter for mongoose
244
+ * @param regexFields
245
+ * @param filter
246
+ * @param excludeFields
247
+ */
248
+ const normaliseMongoFilter = (filter, regexFields, excludeFields) => {
249
+ const _filter = {};
250
+ const excludeParams = excludeFields && Array.isArray(excludeFields) && excludeFields.length > 0 ? excludeFields : exports.optionsPaginationParams;
251
+ Object.keys(filter).forEach((f) => {
252
+ const v = filter[f];
253
+ if (!(v === null || (typeof v === 'number' && isNaN(v)) || v === Infinity || v === undefined || excludeParams.includes(f))) {
254
+ _filter[f] = filter[f];
255
+ if (regexFields.includes(f))
256
+ _filter[f] = { $regex: filter[f] };
257
+ }
258
+ });
259
+ return _filter;
260
+ };
261
+ exports.normaliseMongoFilter = normaliseMongoFilter;
262
+ /**
263
+ * Normalise Mongo Paginate params
264
+ * @param filter
265
+ */
266
+ const normaliseMongoPaginate = (filter) => {
267
+ let res = {
268
+ skip: 0, limit: 50,
269
+ };
270
+ res.skip = filter && filter.skip ? parseInt(filter.skip, 10) || 0 : 0;
271
+ res.limit = filter && filter.limit ? parseInt(filter.limit, 10) || 50 : 50;
272
+ return res;
273
+ };
274
+ exports.normaliseMongoPaginate = normaliseMongoPaginate;
275
+ const controlResponseNull = (data, okResultOf, prefix, bodyWrap = true) => {
276
+ let result;
277
+ if (data) {
278
+ if (okResultOf === 'create') {
279
+ result = CreateResponse.created({
280
+ data, message: (0, exports.messagesREST)(prefix).CREATE, bodyWrap,
281
+ });
282
+ }
283
+ if (okResultOf === 'update') {
284
+ result = CreateResponse.updated({
285
+ data, message: (0, exports.messagesREST)(prefix).UPDATE, bodyWrap,
286
+ });
287
+ }
288
+ if (okResultOf === 'update_many') {
289
+ result = CreateResponse.updated({
290
+ data, message: (0, exports.messagesREST)(prefix).UPDATE_MANY, bodyWrap,
291
+ });
292
+ }
293
+ if (okResultOf === 'increment') {
294
+ result = CreateResponse.updated({
295
+ data, message: (0, exports.messagesREST)(prefix).INCREMENT, bodyWrap,
296
+ });
297
+ }
298
+ if (okResultOf === 'decrement') {
299
+ result = CreateResponse.updated({
300
+ data, message: (0, exports.messagesREST)(prefix).DECREMENT, bodyWrap,
301
+ });
302
+ }
303
+ }
304
+ else {
305
+ let messageErr = '';
306
+ if (okResultOf === 'create')
307
+ messageErr = (0, exports.messagesREST)(prefix).NOT_CREATE;
308
+ if (okResultOf === 'update')
309
+ messageErr = (0, exports.messagesREST)(prefix).NOT_UPDATE;
310
+ if (okResultOf === 'update_many')
311
+ messageErr = (0, exports.messagesREST)(prefix).NOT_UPDATE_MANY;
312
+ if (okResultOf === 'increment')
313
+ messageErr = (0, exports.messagesREST)(prefix).NOT_INCREMENT;
314
+ if (okResultOf === 'decrement')
315
+ messageErr = (0, exports.messagesREST)(prefix).NOT_DECREMENT;
316
+ result = CreateResponse.error({
317
+ data: data, message: messageErr, bodyWrap,
318
+ });
319
+ }
320
+ return result;
321
+ };
322
+ exports.controlResponseNull = controlResponseNull;
package/index.ts ADDED
@@ -0,0 +1,405 @@
1
+ export class StatusResult {
2
+ static ok = 'Ok';
3
+ static error = 'Error';
4
+ static notFound = 'NotFound';
5
+ }
6
+
7
+ export class StatusCode {
8
+ // static SwitchingProtocols = 101;
9
+ // static Continue = 100;
10
+ // static Processing = 102;
11
+
12
+ static OK = 200;
13
+ static Created = 201;
14
+ static Accepted = 202;
15
+ static NonAuthoritativeInformation = 203;
16
+ static NoContent = 204;
17
+ // static ResetContent = 205;
18
+ // static PartialContent = 206;
19
+ // static MultiStatus = 207;
20
+
21
+
22
+ // static MultipleChoices = 300;
23
+ // static MovedPermanently = 301;
24
+ // static MovedTemporarily = 302;
25
+ // static SeeOther = 303;
26
+ // static UseProxy = 305;
27
+ // static NotModified = 304;
28
+ // static TemporaryRedirect = 307;
29
+
30
+
31
+ static BadRequest = 400;
32
+ static Unauthorized = 401;
33
+ static PaymentRequired = 402;
34
+ static NotFound = 404;
35
+ static Forbidden = 403;
36
+ // static MethodNotAllowed = 405;
37
+ // static ProxyAuthenticationRequired = 407;
38
+ // static NotAcceptable = 406;
39
+ // static RequestTimeOut = 408;
40
+ // static Gone = 410;
41
+ // static Conflict = 409;
42
+ // static LengthRequired = 411;
43
+ // static RequestEntityTooLarge = 413;
44
+ // static PreconditionFailed = 412;
45
+ // static RequestURITooLarge = 414;
46
+ // static RequestedRangeNotSatisfiable = 416;
47
+ // static UnsupportedMediaType = 415;
48
+ // static ExpectationFailed = 417;
49
+ // static UnprocessableEntity = 422;
50
+ // static ImATeapot = 418;
51
+ // static Locked = 423;
52
+ // static FailedDependency = 424;
53
+ // static UnorderedCollection = 425;
54
+ // static UpgradeRequired = 426;
55
+ // static PreconditionRequired = 428;
56
+ // static TooManyRequests = 429;
57
+ // static RequestHeaderFieldsTooLarge = 431;
58
+
59
+ static InternalServerError = 500;
60
+ static NotImplemented = 501;
61
+ static BadGateway = 502;
62
+ // static ServiceUnavailable = 503;
63
+ // static GatewayTimeOut = 504;
64
+ // static HTTPVersionNotSupported = 505;
65
+ // static VariantAlsoNegotiates = 506;
66
+ // static InsufficientStorage = 507;
67
+ // static BandwidthLimitExceeded = 509;
68
+ // static NotExtended = 510;
69
+ // static NetworkAuthenticationRequire = 511;
70
+ }
71
+
72
+ type TData = object | boolean | string | null;
73
+ type TCount = number | null;
74
+ type TError = any | null;
75
+
76
+ interface TResultIn {
77
+ statusCode?: StatusCode;
78
+ statusResult?: StatusResult;
79
+ message?: string;
80
+ data?: TData;
81
+ count?: TCount;
82
+ error?: TError;
83
+ bodyWrap: boolean;
84
+ }
85
+
86
+ interface TFuncParams {
87
+ statusCode?: StatusCode,
88
+ statusResult?: StatusResult,
89
+ message?: string,
90
+ error?: TError,
91
+ data?: TData,
92
+ count?: TCount,
93
+ bodyWrap?: boolean;
94
+ }
95
+
96
+ export class ResponseBodyVO {
97
+ statusResult: StatusResult = StatusResult.ok;
98
+ message: string = '';
99
+ data: TData = null;
100
+ count: TCount = null;
101
+ error: TError = null;
102
+ }
103
+
104
+ export class ResponseVO {
105
+ statusCode: StatusCode = StatusCode.OK;
106
+ body: string = '';
107
+ }
108
+
109
+ export type ResponseVoAWS = ResponseVO | ResponseBodyVO
110
+
111
+
112
+ class Result {
113
+ private statusCode: StatusCode;
114
+ private statusResult: StatusResult;
115
+ private message: string;
116
+ private data: TData;
117
+ private count: TCount;
118
+ private error: any;
119
+ private bodyWrap: boolean;
120
+
121
+ constructor({
122
+ statusCode = StatusCode.OK,
123
+ statusResult = StatusResult.ok,
124
+ message,
125
+ data = null,
126
+ count = null,
127
+ error = null,
128
+ bodyWrap = true,
129
+ }: TResultIn) {
130
+ this.statusCode = statusCode;
131
+ this.statusResult = statusResult;
132
+ this.message = !message ? '' : message;
133
+ this.count = count;
134
+ this.data = data;
135
+ this.error = error;
136
+ this.bodyWrap = bodyWrap;
137
+ }
138
+
139
+ /**
140
+ * Serverless: According to the API Gateway specs, the body content must be stringified
141
+ * If use to AWS Appsync need response value without body wrap
142
+ */
143
+ bodyToString(): ResponseVoAWS {
144
+ let _err = this.error && this.error.message ? this.error.message : !this.error ? null : JSON.stringify(this.error);
145
+
146
+ const valueBody: ResponseBodyVO = {
147
+ statusResult: this.statusResult, message: this.message, data: this.data, count: this.count, error: _err,
148
+ };
149
+ const valueBodyWrap: ResponseVO = {
150
+ statusCode: this.statusCode, body: JSON.stringify(valueBody),
151
+ };
152
+
153
+ return this.bodyWrap ? valueBodyWrap : valueBody;
154
+ }
155
+ }
156
+
157
+ export class CreateResponse {
158
+
159
+ /**
160
+ * Success
161
+ * @param data
162
+ * @param count
163
+ * @param message
164
+ * @param bodyWrap
165
+ */
166
+ static success({ data = null, count = null, message = 'success', bodyWrap = true }: TFuncParams): ResponseVoAWS {
167
+ const result = new Result({
168
+ statusCode: StatusCode.OK, statusResult: StatusResult.ok, message, data, count, bodyWrap,
169
+ });
170
+ return result.bodyToString();
171
+ }
172
+
173
+ /**
174
+ * Created
175
+ * @param data
176
+ * @param message
177
+ * @param bodyWrap
178
+ */
179
+ static created({ data, message = 'created', bodyWrap = true }: TFuncParams): ResponseVoAWS {
180
+ const result = new Result({
181
+ statusCode: StatusCode.Created, statusResult: StatusResult.ok, message, data, bodyWrap,
182
+ });
183
+ return result.bodyToString();
184
+ }
185
+
186
+ /**
187
+ * Update
188
+ * @param data
189
+ * @param message
190
+ * @param bodyWrap
191
+ */
192
+ static updated({ data, message = 'updated', bodyWrap = true }: TFuncParams): ResponseVoAWS {
193
+ const result = new Result({
194
+ statusCode: StatusCode.OK, statusResult: StatusResult.ok, message, data, bodyWrap,
195
+ });
196
+ return result.bodyToString();
197
+ }
198
+
199
+ /**
200
+ * Not Found
201
+ * @param error
202
+ * @param message
203
+ * @param bodyWrap
204
+ */
205
+ static notFound({ error = null, message = '', bodyWrap = true }: TFuncParams): ResponseVoAWS {
206
+ const result = new Result({
207
+ statusCode: StatusCode.NotFound, statusResult: StatusResult.notFound, message, error, bodyWrap,
208
+ });
209
+ return result.bodyToString();
210
+ }
211
+
212
+ /**
213
+ * Error
214
+ * @param error
215
+ * @param statusCode
216
+ * @param message
217
+ * @param bodyWrap
218
+ */
219
+ static error({
220
+ error = null, statusCode = StatusCode.BadRequest, message = 'Error', bodyWrap = true,
221
+ }: TFuncParams): ResponseVoAWS {
222
+ const result = new Result({
223
+ statusCode, statusResult: StatusResult.error, error, message, bodyWrap,
224
+ });
225
+ return result.bodyToString();
226
+ }
227
+
228
+ /**
229
+ * Custom
230
+ * @param statusCode
231
+ * @param statusResult
232
+ * @param message
233
+ * @param error
234
+ * @param data
235
+ * @param count
236
+ * @param bodyWrap
237
+ */
238
+ static custom({
239
+ statusCode = StatusCode.OK,
240
+ statusResult = StatusResult.ok,
241
+ message = '',
242
+ error = null,
243
+ data = null,
244
+ count = null,
245
+ bodyWrap = true,
246
+ }: TFuncParams): ResponseVoAWS {
247
+ const result = new Result({
248
+ statusCode, statusResult, message, error, data, count, bodyWrap,
249
+ });
250
+ return result.bodyToString();
251
+ }
252
+ }
253
+
254
+ export const messagesREST = (prefix: string, suffix: string = '') => {
255
+ return {
256
+ TOTAL: `${prefix}_TOTAL${suffix}`,
257
+ CREATE: `${prefix}_ITEM_CREATE${suffix}`,
258
+ NOT_CREATE: `${prefix}_ITEM_NOT_CREATE${suffix}`,
259
+ ERROR_CREATE: `${prefix}_ITEM_ERROR_CREATE${suffix}`,
260
+ UPDATE: `${prefix}_ITEM_UPDATE${suffix}`,
261
+ UPDATE_MANY: `${prefix}_ITEM_UPDATE_MANY${suffix}`,
262
+ NOT_UPDATE: `${prefix}_ITEM_NOT_UPDATE${suffix}`,
263
+ NOT_UPDATE_MANY: `${prefix}_ITEM_NOT_UPDATE_MANY${suffix}`,
264
+ ERROR_UPDATE: `${prefix}_ITEM_ERROR_UPDATE${suffix}`,
265
+ ERROR_UPDATE_MANY: `${prefix}_ITEM_ERROR_UPDATE_MANY${suffix}`,
266
+ GET: `${prefix}_ITEM_GET${suffix}`,
267
+ NOT_GET: `${prefix}_ITEM_NOT_GET${suffix}`,
268
+ ERROR_GET: `${prefix}_ITEM_ERROR_GET${suffix}`,
269
+ GET_MANY: `${prefix}_GET_MANY${suffix}`,
270
+ NOT_GET_MANY: `${prefix}_NOT_GET_MANY${suffix}`,
271
+ ERROR_GET_MANY: `${prefix}_ERROR_GET_MANY${suffix}`,
272
+ GET_MANY_AND_COUNT: `${prefix}_GET_MANY_AND_COUNT${suffix}`,
273
+ NOT_GET_MANY_AND_COUNT: `${prefix}_NOT_GET_MANY_AND_COUNT${suffix}`,
274
+ ERROR_GET_MANY_AND_COUNT: `${prefix}_ERROR_GET_MANY_AND_COUNT${suffix}`,
275
+ GET_COUNT: `${prefix}_GET_COUNT${suffix}`,
276
+ NOT_GET_COUNT: `${prefix}_NOT_GET_COUNT${suffix}`,
277
+ ERROR_GET_COUNT: `${prefix}_ERROR_GET_COUNT${suffix}`,
278
+ DELETE: `${prefix}_ITEM_DELETE${suffix}`,
279
+ NOT_DELETE: `${prefix}_ITEM_NOT_DELETE${suffix}`,
280
+ ERROR_DELETE: `${prefix}_ITEM_ERROR_DELETE${suffix}`,
281
+ DELETE_MANY: `${prefix}_DELETE_MANY${suffix}`,
282
+ NOT_DELETE_MANY: `${prefix}_NOT_DELETE_MANY${suffix}`,
283
+ ERROR_DELETE_MANY: `${prefix}_ERROR_DELETE_MANY${suffix}`,
284
+ NOT_FOUND: `${prefix}_NOT_FOUND${suffix}`,
285
+ INITIALISE: `${prefix}_INITIALISE${suffix}`,
286
+ NOT_INITIALISE: `${prefix}_NOT_INITIALISE${suffix}`,
287
+ ERROR_INITIALISE: `${prefix}_ERROR_INITIALISE${suffix}`,
288
+ INCREMENT: `${prefix}_INCREMENT${suffix}`,
289
+ NOT_INCREMENT: `${prefix}_NOT_INCREMENT${suffix}`,
290
+ ERROR_INCREMENT: `${prefix}_ERROR_INCREMENT${suffix}`,
291
+ DECREMENT: `${prefix}_DECREMENT${suffix}`,
292
+ NOT_DECREMENT: `${prefix}_NOT_DECREMENT${suffix}`,
293
+ ERROR_DECREMENT: `${prefix}_ERROR_DECREMENT${suffix}`,
294
+ COUNTER_DAY: `${prefix}_COUNTER_DAY${suffix}`,
295
+ NOT_COUNTER_DAY: `${prefix}_NOT_COUNTER_DAY${suffix}`,
296
+ ERROR_COUNTER_DAY: `${prefix}_ERROR_COUNTER_DAY${suffix}`,
297
+ COUNTER_MONTH: `${prefix}_COUNTER_MONTH${suffix}`,
298
+ NOT_COUNTER_MONTH: `${prefix}_NOT_COUNTER_MONTH${suffix}`,
299
+ ERROR_COUNTER_MONTH: `${prefix}_ERROR_COUNTER_MONTH${suffix}`,
300
+ COUNTER_YEAR: `${prefix}_COUNTER_YEAR${suffix}`,
301
+ NOT_COUNTER_YEAR: `${prefix}_NOT_COUNTER_YEAR${suffix}`,
302
+ TEST: `${prefix}_TEST${suffix}`,
303
+ NOT_TEST: `${prefix}_NOT_TEST${suffix}`,
304
+ ERROR_TEST: `${prefix}_ERROR_TEST${suffix}`,
305
+ AGGREGATION: `${prefix}_AGGREGATION${suffix}`,
306
+ NOT_AGGREGATION: `${prefix}_NOT_AGGREGATION${suffix}`,
307
+ ERROR_AGGREGATION: `${prefix}_ERROR_AGGREGATION${suffix}`,
308
+ };
309
+ };
310
+
311
+ export const optionsPaginationParams = ['limit', 'skip', 'count'];
312
+
313
+ export type TMongoFilterNormalise = {[fieldName: string]: any}
314
+
315
+ /**
316
+ * Normalise filter for mongoose
317
+ * @param regexFields
318
+ * @param filter
319
+ * @param excludeFields
320
+ */
321
+ export const normaliseMongoFilter = (filter: TMongoFilterNormalise, regexFields: string[], excludeFields?: string[]) => {
322
+ const _filter: TMongoFilterNormalise = {};
323
+ const excludeParams = excludeFields && Array.isArray(excludeFields) && excludeFields.length > 0 ? excludeFields : optionsPaginationParams;
324
+
325
+ Object.keys(filter).forEach((f) => {
326
+ const v = filter[f];
327
+ if (!(v === null || (typeof v === 'number' && isNaN(v)) || v === Infinity || v === undefined || excludeParams.includes(f))) {
328
+ _filter[f] = filter[f];
329
+
330
+ if (regexFields.includes(f)) _filter[f] = { $regex: filter[f] };
331
+ }
332
+ });
333
+
334
+ return _filter;
335
+ };
336
+
337
+ export interface TMongoPaginate {
338
+ skip: number;
339
+ limit: number;
340
+ }
341
+
342
+ /**
343
+ * Normalise Mongo Paginate params
344
+ * @param filter
345
+ */
346
+ export const normaliseMongoPaginate = (filter: TMongoFilterNormalise): TMongoPaginate => {
347
+ let res: TMongoPaginate = {
348
+ skip: 0, limit: 50,
349
+ };
350
+
351
+ res.skip = filter && filter.skip ? parseInt(filter.skip, 10) || 0 : 0;
352
+ res.limit = filter && filter.limit ? parseInt(filter.limit, 10) || 50 : 50;
353
+
354
+ return res;
355
+ };
356
+
357
+ export const controlResponseNull = (data: object, okResultOf: 'create' | 'update' | 'update_many' | 'increment' | 'decrement', prefix: string, bodyWrap: boolean = true) => {
358
+ let result;
359
+
360
+ if (data) {
361
+ if (okResultOf === 'create') {
362
+ result = CreateResponse.created({
363
+ data, message: messagesREST(prefix).CREATE, bodyWrap,
364
+ });
365
+ }
366
+
367
+ if (okResultOf === 'update') {
368
+ result = CreateResponse.updated({
369
+ data, message: messagesREST(prefix).UPDATE, bodyWrap,
370
+ });
371
+ }
372
+
373
+ if (okResultOf === 'update_many') {
374
+ result = CreateResponse.updated({
375
+ data, message: messagesREST(prefix).UPDATE_MANY, bodyWrap,
376
+ });
377
+ }
378
+
379
+ if (okResultOf === 'increment') {
380
+ result = CreateResponse.updated({
381
+ data, message: messagesREST(prefix).INCREMENT, bodyWrap,
382
+ });
383
+ }
384
+
385
+ if (okResultOf === 'decrement') {
386
+ result = CreateResponse.updated({
387
+ data, message: messagesREST(prefix).DECREMENT, bodyWrap,
388
+ });
389
+ }
390
+
391
+ } else {
392
+ let messageErr = '';
393
+ if (okResultOf === 'create') messageErr = messagesREST(prefix).NOT_CREATE;
394
+ if (okResultOf === 'update') messageErr = messagesREST(prefix).NOT_UPDATE;
395
+ if (okResultOf === 'update_many') messageErr = messagesREST(prefix).NOT_UPDATE_MANY;
396
+ if (okResultOf === 'increment') messageErr = messagesREST(prefix).NOT_INCREMENT;
397
+ if (okResultOf === 'decrement') messageErr = messagesREST(prefix).NOT_DECREMENT;
398
+
399
+ result = CreateResponse.error({
400
+ data: data, message: messageErr, bodyWrap,
401
+ });
402
+ }
403
+
404
+ return result;
405
+ };
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "my-q-format-response-aws-lambda",
3
+ "version": "1.0.1",
4
+ "homepage": "https://github.com/zhukyuri/my-q-format-response-aws-lambda",
5
+ "description": "my-q-format-response-aws-lambda",
6
+ "main": "index.js",
7
+ "private": false,
8
+ "scripts": {
9
+ "build": "npx tsc",
10
+ "test": "echo \"Error: no test specified\" && exit 1",
11
+ "prepare": "npm run build",
12
+ "version": "git add .",
13
+ "postversion": "git push && git push --tags",
14
+ "publish": "npm publish"
15
+ },
16
+ "author": "zhukyuri",
17
+ "license": "MIT",
18
+ "devDependencies": {
19
+ "typescript": "^4.7.4"
20
+ }
21
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,103 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "commonjs", /* Specify what module code is generated. */
29
+ // "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "resolveJsonModule": true, /* Enable importing .json files. */
39
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
40
+
41
+ /* JavaScript Support */
42
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
43
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
44
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
45
+
46
+ /* Emit */
47
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
48
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
49
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
50
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
51
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
52
+ // "outDir": "./build", /* Specify an output folder for all emitted files. */
53
+ // "removeComments": true, /* Disable emitting comments. */
54
+ // "noEmit": true, /* Disable emitting files from a compilation. */
55
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
56
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
57
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
58
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
59
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
60
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
61
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
62
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
63
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
64
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
65
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
66
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
67
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
68
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
69
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
70
+
71
+ /* Interop Constraints */
72
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
73
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
74
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
75
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
76
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
77
+
78
+ /* Type Checking */
79
+ "strict": true, /* Enable all strict type-checking options. */
80
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
81
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
82
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
83
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
84
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
85
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
86
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
87
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
88
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
89
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
90
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
91
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
92
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
93
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
94
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
95
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
96
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
97
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
98
+
99
+ /* Completeness */
100
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
101
+ "skipLibCheck": true /* Skip type checking all .d.ts files. */
102
+ }
103
+ }