@xrystal/core 3.5.1 → 3.5.2

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.
@@ -1,448 +1,164 @@
1
1
  import qs from 'qs';
2
2
  import { LoggerService } from '../../../loader';
3
- import { LoggerLayerEnum, ProtocolEnum, responseMessageHelper, ResponseSchema, x } from '../../index';
3
+ import { responseMessageHelper, ResponseSchema, x } from '../../index';
4
4
  class Controller {
5
5
  logger = x.get(LoggerService);
6
6
  protocol = null;
7
- socket = null;
8
7
  req = null;
9
8
  res = null;
10
- accounts = null;
11
- startDate = null;
12
- date = null;
13
- dateStart = null;
14
- endDate = null;
15
- sort = null;
16
- offset = null;
17
- limit = null;
18
- defaultLimitSize = 20;
19
- maxLimitSize = 100;
20
- constructor({ protocol, socket, req, res, ctx }) {
21
- // Eğer ctx varsa, otomatik req/res'e çevir
9
+ constructor({ protocol, req, res, ctx }) {
10
+ this.protocol = protocol;
22
11
  if (ctx) {
23
- req = {
12
+ this.req = {
24
13
  url: ctx.request.url,
25
14
  method: ctx.request.method,
26
15
  headers: Object.fromEntries(ctx.request.headers),
27
16
  body: ctx.body,
28
17
  params: ctx.params,
29
- query: ctx.query,
30
- accounts: ctx.accounts || ctx.user,
18
+ query: ctx.query || {},
19
+ accounts: ctx.user || ctx.accounts,
31
20
  t: ctx.t
32
21
  };
33
- res = {
34
- status: (code) => res,
35
- send: (data) => data,
36
- json: (data) => data,
37
- locals: {}
38
- };
39
- }
40
- this.protocol = protocol;
41
- this.socket = socket;
42
- this.req = req;
43
- this.res = res;
44
- }
45
- createResponse(data, statusCode = 200) {
46
- return new Response(JSON.stringify(data), {
47
- status: statusCode,
48
- headers: {
49
- 'Content-Type': 'application/json'
50
- }
51
- });
52
- }
53
- payloadProtocolSwitch = async ({ protocol, socket, req, res }) => {
54
- let payload = {};
55
- switch (protocol) {
56
- case ProtocolEnum.HTTP:
57
- case ProtocolEnum.HTTPS:
58
- if ((protocol === ProtocolEnum.HTTP || protocol === ProtocolEnum.HTTPS) && (!req || !res)) {
59
- throw new Error('Req and res required');
22
+ this.res = {
23
+ locals: {},
24
+ status(code) {
25
+ this.locals._code = code;
26
+ return this;
27
+ },
28
+ send(data) {
29
+ return new Response(JSON.stringify(data), {
30
+ status: this.locals._code || 200,
31
+ headers: { 'content-type': 'application/json' }
32
+ });
33
+ },
34
+ json(data) {
35
+ return this.send(data);
60
36
  }
61
- this.req = req;
62
- this.res = res;
63
- const parsedQuerys = this.parsedQuerys(req?.url ? req.url : '');
64
- payload = {
65
- req: this.req,
66
- res: this.res,
67
- accounts: this.req?.accounts && this.req.accounts,
68
- parsedQuerys: parsedQuerys,
69
- };
70
- break;
71
- case ProtocolEnum.SOCKETIO:
72
- payload = {};
73
- break;
74
- case ProtocolEnum.NONE:
75
- payload = {};
76
- break;
77
- default:
78
- throw new Error('Protocol not match.');
79
- }
80
- return payload;
81
- };
82
- convertedPayloadProtocolSwitch = async ({ protocol, socket, req, res, }) => {
83
- let convertedPayload = {};
84
- switch (protocol) {
85
- case ProtocolEnum.HTTP:
86
- case ProtocolEnum.HTTPS:
87
- const parsedQuerys = this.parsedQuerys(req?.url ? req.url : '');
88
- const parsedQuerysWithTrueType = this.parsedQuerysWithTrueType(req?.url ? req.url : '');
89
- convertedPayload = {
90
- req: this.req,
91
- res: this.res,
92
- accounts: this.req?.accounts,
93
- parsedQuerys: parsedQuerys,
94
- parsedQuerysWithTrueType: parsedQuerysWithTrueType,
95
- startDate: parsedQuerysWithTrueType?.['start-date']
96
- ? this.dateNativeUTCToUTCConverter(parsedQuerysWithTrueType['start-date'])
97
- : this.startDate,
98
- startDateTimezone: parsedQuerysWithTrueType?.['start-date']
99
- ? parsedQuerysWithTrueType['start-date'].split('+')[1]
100
- : this.startDate,
101
- date: this.date ? this.dateNativeUTCToUTCConverter(parsedQuerysWithTrueType.date) : this.date,
102
- dateTimezone: this.date ? parsedQuerysWithTrueType.date.split('+')[1] : this.date,
103
- endDate: parsedQuerysWithTrueType?.['end-date']
104
- ? this.dateNativeUTCToUTCConverter(parsedQuerysWithTrueType['end-date'])
105
- : this.endDate,
106
- endDateTimezone: parsedQuerysWithTrueType?.['end-date']
107
- ? parsedQuerysWithTrueType['end-date'].split('+')[1]
108
- : this.endDate,
109
- sort: parsedQuerysWithTrueType.sort ? this.sortParser(parsedQuerys.sort) : this.sort,
110
- offset: parsedQuerysWithTrueType.offset ? parsedQuerys.offset : this.offset,
111
- limit: parsedQuerysWithTrueType.limit
112
- ? parsedQuerysWithTrueType.limit > this.maxLimitSize
113
- ? String(this.maxLimitSize)
114
- : parsedQuerys.limit
115
- : this.defaultLimitSize
116
- };
117
- break;
118
- case ProtocolEnum.WEBSOCKET:
119
- convertedPayload = {};
120
- break;
121
- case ProtocolEnum.SOCKETIO:
122
- convertedPayload = {};
123
- break;
124
- case ProtocolEnum.NONE:
125
- convertedPayload = {};
126
- break;
127
- default:
128
- throw new Error('Protocol not match.');
37
+ };
129
38
  }
130
- return convertedPayload;
131
- };
132
- responseProtocolSwitch = async ({ protocol, socket, req, res, resStatus = 200, context }) => {
133
- switch (protocol) {
134
- case ProtocolEnum.HTTP:
135
- case ProtocolEnum.HTTPS:
136
- if (!req || !res) {
137
- throw new Error(`req or res not found`);
39
+ else {
40
+ this.req = {
41
+ url: req?.originalUrl || req?.url,
42
+ method: req?.method,
43
+ headers: req?.headers || {},
44
+ body: req?.body,
45
+ params: req?.params,
46
+ query: req?.query || {},
47
+ accounts: req?.accounts,
48
+ t: req?.t
49
+ };
50
+ this.res = {
51
+ locals: res?.locals || {},
52
+ status(code) {
53
+ res.status(code);
54
+ return this;
55
+ },
56
+ send(data) {
57
+ return res.send(data);
58
+ },
59
+ json(data) {
60
+ return res.json(data);
138
61
  }
139
- const responseData = context({
140
- localeLanguageConverter: req.t
141
- });
142
- return this.createResponse(responseData, resStatus);
143
- case ProtocolEnum.WEBSOCKET:
144
- return context({});
145
- case ProtocolEnum.SOCKETIO:
146
- return context({});
147
- case ProtocolEnum.NONE:
148
- return context({});
149
- default:
150
- throw new Error('Protocol not match.');
62
+ };
151
63
  }
64
+ }
65
+ responseProtocolSwitch = async ({ protocol, req, res, resStatus = 200, context }) => {
66
+ const responseData = context({ localeLanguageConverter: req.t });
67
+ return res.status(resStatus).send(responseData);
152
68
  };
153
69
  parsedQuerys = (url) => {
154
- const parseUrlForQuerys = url.split('?')?.[1];
155
- let convertedQuerys;
156
- if (parseUrlForQuerys) {
157
- convertedQuerys = qs.parse(parseUrlForQuerys, { decoder: decodeURIComponent });
158
- }
159
- else {
160
- convertedQuerys = {};
161
- }
162
- return convertedQuerys;
163
- };
164
- parsedQuerysWithTrueType = (url) => {
165
- const parsedParams = {};
166
- Object.entries(this.parsedQuerys(url))?.forEach(([key, value]) => {
167
- if (value === 'undefined') {
168
- parsedParams[key] = undefined;
169
- }
170
- else if (value === 'null') {
171
- parsedParams[key] = null;
172
- }
173
- else if (value === '') {
174
- parsedParams[key] = '';
175
- }
176
- else if (!isNaN(value)) {
177
- parsedParams[key] = Number(value);
178
- }
179
- else if (value?.toLowerCase() === 'true' || value?.toLowerCase() === 'false') {
180
- parsedParams[key] = value?.toLowerCase() === 'true';
181
- }
182
- else {
183
- parsedParams[key] = value;
184
- }
185
- });
186
- return parsedParams;
70
+ const queryString = url.includes('?') ? url.split('?')[1] : '';
71
+ if (!queryString)
72
+ return {};
73
+ return qs.parse(queryString, { decoder: decodeURIComponent });
187
74
  };
188
- dateNativeUTCToUTCConverter = (date) => {
189
- const convertedDate = (new Date(date)).toISOString();
190
- return convertedDate;
75
+ log = async (level, message) => {
76
+ this.logger.winston.log({ level, message });
191
77
  };
192
- sortParser = (sort) => {
193
- if (String(sort)) {
194
- const parsed = sort.split('+');
195
- if (!parsed[0] || !parsed[1]) {
196
- this.log({
197
- level: LoggerLayerEnum[LoggerLayerEnum.ERROR].toLowerCase(),
198
- message: 'sort query parameter invalid.'
199
- });
200
- return null;
201
- }
202
- return {
203
- key: parsed[0],
204
- value: Number(parsed[1])
205
- };
206
- }
207
- else {
208
- return null;
209
- }
210
- };
211
- aprotator(value) {
212
- return value === 0 ? true : !!value;
213
- }
214
- log = async ({ level, message }) => {
215
- this.logger.winston.log({
216
- level: level,
217
- message,
218
- });
219
- };
220
- getErrorMessage(error) {
221
- if (error instanceof Error)
222
- return error.message;
223
- return String(error);
224
- }
225
78
  }
226
- class ControllerSchema extends Controller {
227
- constructor({ protocol, socket, req, res, ctx }) {
228
- super({
229
- protocol,
230
- socket,
231
- req,
232
- res,
233
- ctx
234
- });
235
- }
79
+ export class ControllerSchema extends Controller {
236
80
  async schema({ checks, logic, response, }) {
237
- const { res, req } = this;
81
+ const payload = { req: this.req, res: this.res };
82
+ const convertedPayload = {
83
+ ...payload,
84
+ parsedQuerys: this.parsedQuerys(this.req.url)
85
+ };
238
86
  try {
239
- let logicCallbackFunc;
240
- // Checks
241
- try {
242
- if (checks) {
243
- const checksCallbackFunc = await checks({
244
- payload: this.payloadProtocolSwitch,
245
- convertedPayload: await this.convertedPayloadProtocolSwitch({
246
- protocol: this.protocol,
247
- socket: this.socket,
248
- req: req,
249
- res: res
250
- })
251
- });
252
- let checked = false;
253
- if (Array.isArray(checksCallbackFunc)) {
254
- checked = checksCallbackFunc.every((check) => check !== undefined && check !== null && check !== "");
255
- }
256
- else if (!Array.isArray(checksCallbackFunc) && checksCallbackFunc?.message) {
257
- return this.responseProtocolSwitch({
258
- protocol: this.protocol,
259
- req: this.req,
260
- res: this.res,
261
- resStatus: 200,
262
- context: ({ localeLanguageConverter }) => new ResponseSchema({
263
- status: checksCallbackFunc.status || false,
264
- message: checksCallbackFunc?.message,
265
- ...(this.aprotator(checksCallbackFunc?.payload) && { payload: checksCallbackFunc?.payload }),
266
- code: checksCallbackFunc?.code
267
- }).getResponse
268
- });
269
- }
270
- else if (typeof checksCallbackFunc === 'object' && typeof checksCallbackFunc?.response === 'function') {
271
- if (typeof checksCallbackFunc.response() === 'boolean') {
272
- checked = checksCallbackFunc.response();
273
- }
274
- else {
275
- return checksCallbackFunc.response();
276
- }
277
- }
278
- if (!checked) {
279
- return this.responseProtocolSwitch({
280
- protocol: this.protocol,
281
- socket: this.socket,
282
- req: this.req,
283
- res: this.res,
284
- resStatus: 400,
285
- context: ({ localeLanguageConverter }) => new ResponseSchema({
286
- status: false,
287
- message: Array.isArray(checksCallbackFunc)
288
- ? `${responseMessageHelper.schemaMissingDataChecks(localeLanguageConverter)}`
289
- : checksCallbackFunc?.invalid
290
- ? `${responseMessageHelper.schemaInvalidDataChecks(localeLanguageConverter)}`
291
- : `${responseMessageHelper.schemaMissingDataChecks(localeLanguageConverter)}`,
292
- }).getResponse
293
- });
294
- }
87
+ if (checks) {
88
+ const checkResult = await checks({ payload, convertedPayload });
89
+ let isInvalid = false;
90
+ if (Array.isArray(checkResult)) {
91
+ isInvalid = !checkResult.every(c => c !== undefined && c !== null && c !== "");
295
92
  }
296
- }
297
- catch (error) {
298
- this.log({
299
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
300
- message: this.getErrorMessage(`Schema check controller handler: ${error.message}. Extra: ${JSON.stringify(error.response?.data)}`),
301
- });
302
- return this.responseProtocolSwitch({
303
- protocol: this.protocol,
304
- socket: this.socket,
305
- req: this.req,
306
- res: this.res,
307
- resStatus: 500,
308
- context: ({ localeLanguageConverter }) => new ResponseSchema({
309
- status: false,
310
- message: `${responseMessageHelper.schemaUnknowErrorChecks(error.message, JSON.stringify(error.response?.data), localeLanguageConverter)}`,
311
- }).getResponse
312
- });
313
- }
314
- // Logic
315
- try {
316
- logicCallbackFunc = await logic({
317
- payload: this.payloadProtocolSwitch,
318
- convertedPayload: await this.convertedPayloadProtocolSwitch({
93
+ else if (typeof checkResult === 'object' && checkResult.message) {
94
+ return await this.responseProtocolSwitch({
319
95
  protocol: this.protocol,
320
- socket: this.socket,
321
- req: req,
322
- res: res
323
- })
324
- });
325
- if (logicCallbackFunc?.response) {
326
- if (logicCallbackFunc.response instanceof Function) {
327
- return logicCallbackFunc.response(logicCallbackFunc?.payload);
328
- }
329
- else {
330
- throw new Error('Invalid type for logicCallbackFunc.response');
331
- }
96
+ req: this.req,
97
+ res: this.res,
98
+ context: () => new ResponseSchema({
99
+ status: checkResult.status || false,
100
+ message: checkResult.message,
101
+ payload: checkResult.payload,
102
+ code: checkResult.code
103
+ }).getResponse
104
+ });
332
105
  }
333
- if (logicCallbackFunc?.message) {
334
- return this.responseProtocolSwitch({
106
+ if (isInvalid) {
107
+ return await this.responseProtocolSwitch({
335
108
  protocol: this.protocol,
336
- socket: this.socket,
337
109
  req: this.req,
338
110
  res: this.res,
339
111
  resStatus: 400,
340
112
  context: ({ localeLanguageConverter }) => new ResponseSchema({
341
- status: logicCallbackFunc?.status || false,
342
- message: logicCallbackFunc?.message,
343
- ...(this.aprotator(logicCallbackFunc?.payload) && { payload: logicCallbackFunc?.payload }),
344
- code: logicCallbackFunc?.code
113
+ status: false,
114
+ message: responseMessageHelper.schemaMissingDataChecks(localeLanguageConverter)
345
115
  }).getResponse
346
116
  });
347
117
  }
348
118
  }
349
- catch (error) {
350
- this.log({
351
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
352
- message: this.getErrorMessage(`Schema logic controller handler: ${error.message}. Extra: ${JSON.stringify(error?.response?.data)}`),
353
- });
354
- return this.responseProtocolSwitch({
119
+ const logicResult = await logic({ payload, convertedPayload });
120
+ if (logicResult.response instanceof Function) {
121
+ return logicResult.response(logicResult.payload);
122
+ }
123
+ if (logicResult.message) {
124
+ return await this.responseProtocolSwitch({
355
125
  protocol: this.protocol,
356
- socket: this.socket,
357
126
  req: this.req,
358
127
  res: this.res,
359
- resStatus: 500,
360
- context: ({ localeLanguageConverter }) => new ResponseSchema({
361
- status: false,
362
- message: `${responseMessageHelper.schemaUnknowErrorLogic(error.message, JSON.stringify(error?.response?.data), localeLanguageConverter)}`,
128
+ resStatus: 400,
129
+ context: () => new ResponseSchema({
130
+ status: logicResult.status || false,
131
+ message: logicResult.message,
132
+ payload: logicResult.payload,
133
+ code: logicResult.code
363
134
  }).getResponse
364
135
  });
365
136
  }
366
- // Response
367
- try {
368
- if (response) {
369
- const responseCallbackFunc = await response({
370
- payload: this.payloadProtocolSwitch,
371
- convertedPayload: await this.convertedPayloadProtocolSwitch({
372
- protocol: this.protocol,
373
- socket: this.socket,
374
- req: req,
375
- res: res
376
- })
377
- });
378
- if (!responseCallbackFunc?.message) {
379
- throw new Error('Message required: Please add the responseObj.message');
380
- }
381
- if (responseCallbackFunc?.response) {
382
- if (responseCallbackFunc.response instanceof Function) {
383
- return responseCallbackFunc.response(responseCallbackFunc);
384
- }
385
- else {
386
- throw new Error('Invalid type for responseCallbackFunc.response');
387
- }
388
- }
389
- if (logicCallbackFunc) {
390
- return this.responseProtocolSwitch({
391
- protocol: this.protocol,
392
- socket: this.socket,
393
- req: this.req,
394
- res: this.res,
395
- resStatus: 200,
396
- context: ({ localeLanguageConverter }) => new ResponseSchema({
397
- status: true,
398
- message: `${responseMessageHelper.successFully(responseCallbackFunc.message?.[0], responseCallbackFunc.message?.[1], localeLanguageConverter)}`,
399
- ...(this.aprotator(logicCallbackFunc?.payload) && { payload: logicCallbackFunc?.payload })
400
- }).getResponse
401
- });
402
- }
403
- else {
404
- throw new Error("logicCallbackFunc values not found.");
405
- }
137
+ if (response) {
138
+ const resResult = await response({ payload, convertedPayload });
139
+ if (resResult.response instanceof Function) {
140
+ return resResult.response(resResult);
406
141
  }
407
- else {
408
- throw new Error('Please use response scope.');
409
- }
410
- }
411
- catch (error) {
412
- this.log({
413
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
414
- message: this.getErrorMessage(`Schema response controller handler: ${error.message}. Extra: ${JSON.stringify(error?.response?.data)}`),
415
- });
416
- return this.responseProtocolSwitch({
142
+ return await this.responseProtocolSwitch({
417
143
  protocol: this.protocol,
418
- socket: this.socket,
419
144
  req: this.req,
420
145
  res: this.res,
421
- resStatus: 500,
146
+ resStatus: 200,
422
147
  context: ({ localeLanguageConverter }) => new ResponseSchema({
423
- status: false,
424
- message: `${responseMessageHelper.schemaUnknowErrorResponse(error.message, JSON.stringify(error?.response?.data), localeLanguageConverter)}`,
148
+ status: true,
149
+ message: responseMessageHelper.successFully(resResult.message[0], resResult.message[1], localeLanguageConverter),
150
+ payload: logicResult.payload
425
151
  }).getResponse
426
152
  });
427
153
  }
428
154
  }
429
155
  catch (error) {
430
- this.log({
431
- level: LoggerLayerEnum[LoggerLayerEnum.CRITICAL].toLowerCase(),
432
- message: this.getErrorMessage(`Schema main controller handler: ${error.message}. Extra: ${JSON.stringify(error?.response?.data)}`),
433
- });
434
- return this.responseProtocolSwitch({
435
- protocol: this.protocol,
436
- socket: this.socket,
437
- req: this.req,
438
- res: this.res,
439
- resStatus: 500,
440
- context: ({ localeLanguageConverter }) => new ResponseSchema({
441
- status: false,
442
- message: `${responseMessageHelper.schemaUnknowErrorMain(error.message, JSON.stringify(error?.response?.data), localeLanguageConverter)}`,
443
- }).getResponse
156
+ await this.log('error', `Schema Error: ${error.message}`);
157
+ return this.res.status(500).send({
158
+ status: false,
159
+ message: error.message
444
160
  });
445
161
  }
446
162
  }
447
163
  }
448
- export { Controller, ControllerSchema };
164
+ export { Controller };