@xrystal/core 3.24.3 → 3.24.5

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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.24.3",
4
+ "version": "3.24.5",
5
5
  "description": "Project core for xrystal",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -10,6 +10,7 @@ export declare const controllerContextStorage: AsyncLocalStorage<{
10
10
  metadata?: {
11
11
  locals: Record<string, any>;
12
12
  _code?: number;
13
+ _statusCode?: number;
13
14
  _contentType?: string;
14
15
  _isRaw?: boolean;
15
16
  };
@@ -22,6 +23,7 @@ export declare const getControllerCtx: () => {
22
23
  metadata?: {
23
24
  locals: Record<string, any>;
24
25
  _code?: number;
26
+ _statusCode?: number;
25
27
  _contentType?: string;
26
28
  _isRaw?: boolean;
27
29
  };
@@ -39,6 +41,7 @@ export declare abstract class BaseController {
39
41
  metadata?: {
40
42
  locals: Record<string, any>;
41
43
  _code?: number;
44
+ _statusCode?: number;
42
45
  _contentType?: string;
43
46
  _isRaw?: boolean;
44
47
  };
@@ -49,7 +52,7 @@ export declare abstract class BaseController {
49
52
  export default abstract class Controller extends BaseController implements IProvide<any> {
50
53
  constructor();
51
54
  onInit(): Promise<void>;
52
- private parseMessage;
55
+ protected parseMessage(msg: any, t: Function, isError?: boolean): string;
53
56
  schema({ checks, logic, response }: {
54
57
  checks?: (args: any) => Promise<any>;
55
58
  logic?: (args: any) => Promise<any>;
@@ -26,15 +26,13 @@ export class BaseController {
26
26
  if (Object.keys(query).length === 0 && typeof urlStr === 'string' && urlStr.includes('?')) {
27
27
  query = qs.parse(urlStr.split('?')[1]);
28
28
  }
29
- const params = ctx.params || req.params || {};
30
- const headers = ctx.headers || req.headers || ctx.request?.headers || {};
31
29
  return {
32
30
  url: urlStr,
33
31
  method: ctx.method || req.method || ctx.request?.method || '',
34
- headers,
32
+ headers: ctx.headers || req.headers || ctx.request?.headers || {},
35
33
  body,
36
34
  query,
37
- params,
35
+ params: ctx.params || req.params || {},
38
36
  lang: ctx.lang || req.lang || 'en',
39
37
  t: ctx.t || req.t || identityT,
40
38
  accounts: ctx.accounts || req.accounts || ctx.user
@@ -43,12 +41,7 @@ export class BaseController {
43
41
  get res() {
44
42
  const store = this.currentStore;
45
43
  const self = this;
46
- const fallbackRes = {
47
- status: function () { return this; },
48
- send: (d) => d,
49
- json: function (d) { return this.send(d); },
50
- locals: {}
51
- };
44
+ const fallbackRes = { status: function () { return this; }, send: (d) => d, json: function (d) { return this.send(d); }, locals: {} };
52
45
  if (!store)
53
46
  return fallbackRes;
54
47
  if (!store.metadata)
@@ -66,28 +59,21 @@ export class BaseController {
66
59
  return data;
67
60
  const isBinary = data instanceof Blob || data instanceof Uint8Array || data instanceof ArrayBuffer || (typeof data?.pipe === 'function');
68
61
  const isRaw = store.metadata?._isRaw || isBinary;
69
- let contentType = store.metadata?._contentType;
70
- if (!contentType) {
71
- contentType = isRaw ? 'application/octet-stream' : 'application/json';
62
+ let contentType = store.metadata?._contentType || (isRaw ? 'application/octet-stream' : 'application/json');
63
+ let bizCode = store.metadata._code || 200;
64
+ let httpStatus = store.metadata._statusCode;
65
+ if (!httpStatus) {
66
+ httpStatus = (bizCode >= 100 && bizCode <= 101) || (bizCode >= 200 && bizCode <= 599) ? bizCode : (bizCode === 0 || (bizCode >= 200 && bizCode <= 299) ? 200 : 400);
72
67
  }
73
- let rawCode = store.metadata._code || 200;
74
- let httpStatus = (rawCode >= 100 && rawCode <= 101) || (rawCode >= 200 && rawCode <= 599) ? rawCode : (rawCode === 0 || (rawCode >= 200 && rawCode <= 299) ? 200 : 400);
75
- const body = isRaw || typeof data === 'string'
76
- ? data
77
- : JSON.stringify(data?.getResponse ? data.getResponse : data);
78
- return new Response(body, {
79
- status: httpStatus,
80
- headers: { 'content-type': contentType }
81
- });
68
+ const body = isRaw || typeof data === 'string' ? data : JSON.stringify(data?.getResponse ? data.getResponse : data);
69
+ return new Response(body, { status: httpStatus, headers: { 'content-type': contentType } });
82
70
  },
83
71
  json(data) { return this.send(data); }
84
72
  };
85
73
  }
86
74
  }
87
75
  export default class Controller extends BaseController {
88
- constructor() {
89
- super();
90
- }
76
+ constructor() { super(); }
91
77
  async onInit() {
92
78
  const protocols = this.system?.tmp?.configs?.loaders?.controller?.protocols;
93
79
  this.supportedProtocols = Array.isArray(protocols) ? protocols : [protocols || ProtocolEnum.HTTP];
@@ -111,70 +97,59 @@ export default class Controller extends BaseController {
111
97
  const p1Raw = params[0] || '';
112
98
  const p1 = (p1Raw === method || p1Raw === 'unsuccessful' || p1Raw === 'success_process') ? '' : t(p1Raw);
113
99
  const p2 = params.slice(1).map(v => t(v)).join(' ');
114
- if (responseMessageHelper[method]) {
100
+ if (responseMessageHelper[method])
115
101
  return responseMessageHelper[method](p1, p2, t);
116
- }
117
- return isError
118
- ? responseMessageHelper.unsuccessful(p1, p2, t)
119
- : responseMessageHelper.successfully(p1, p2, t);
102
+ return isError ? responseMessageHelper.unsuccessful(p1, p2, t) : responseMessageHelper.successfully(p1, p2, t);
120
103
  }
121
104
  async schema({ checks, logic, response }) {
122
- let currentReq = this.req;
105
+ const currentReq = this.req;
106
+ const currentRes = this.res;
107
+ const store = this.currentStore;
123
108
  try {
124
- const currentRes = this.res;
125
- const p = {
126
- req: currentReq,
127
- res: currentRes,
128
- body: currentReq.body,
129
- query: currentReq.query,
130
- params: currentReq.params,
131
- t: currentReq.t,
132
- accounts: currentReq.accounts
109
+ const p = { req: currentReq, res: currentRes, body: currentReq.body, query: currentReq.query, params: currentReq.params, t: currentReq.t, accounts: currentReq.accounts };
110
+ const extractMeta = (obj) => {
111
+ if (!obj || typeof obj !== 'object')
112
+ return;
113
+ if (obj.code !== undefined && store?.metadata)
114
+ store.metadata._code = obj.code;
115
+ if (obj.statusCode !== undefined && store?.metadata)
116
+ store.metadata._statusCode = obj.statusCode;
133
117
  };
134
118
  if (checks) {
135
119
  const checkResult = await checks(p);
136
120
  if (checkResult !== true) {
137
- const bizCode = checkResult?.code ?? 400;
138
- const msg = checkResult?.message || checkResult;
121
+ extractMeta(checkResult);
122
+ const bizCode = store?.metadata._code ?? 400;
139
123
  let errorPayload = undefined;
140
124
  if (checkResult?.payload) {
141
- errorPayload = {
142
- data: checkResult.payload.data ?? checkResult.payload,
143
- extraData: checkResult.payload.extraData ?? {}
144
- };
125
+ const d = checkResult.payload.data ?? checkResult.payload;
126
+ errorPayload = { data: d };
127
+ if (checkResult.payload.extraData !== undefined)
128
+ errorPayload.extraData = checkResult.payload.extraData;
145
129
  }
146
- return currentRes.status(bizCode).send(new ResponseSchema({
147
- status: false,
148
- message: this.parseMessage(msg, currentReq.t, true),
149
- code: bizCode,
150
- payload: errorPayload
151
- }).getResponse);
130
+ return currentRes.status(bizCode).send(new ResponseSchema({ status: false, message: this.parseMessage(checkResult?.message || checkResult, currentReq.t, true), code: bizCode, payload: errorPayload }).getResponse);
152
131
  }
153
132
  }
154
133
  let logicResult = logic ? await logic(p) : {};
155
- if (logicResult instanceof Response || logicResult?.constructor?.name === 'Response') {
134
+ extractMeta(logicResult);
135
+ if (logicResult instanceof Response || logicResult?.constructor?.name === 'Response')
156
136
  return logicResult;
157
- }
158
137
  if (logicResult && typeof logicResult === 'object' && typeof logicResult.response === 'function') {
159
138
  logicResult = await logicResult.response();
139
+ extractMeta(logicResult);
160
140
  }
161
141
  if (logicResult?.status === false) {
162
- const bizCode = logicResult.code ?? 400;
163
- return currentRes.status(bizCode).send(new ResponseSchema({
164
- status: false,
165
- message: this.parseMessage(logicResult.message, currentReq.t, true),
166
- code: bizCode
167
- }).getResponse);
142
+ const bizCode = store?.metadata._code ?? 400;
143
+ return currentRes.status(bizCode).send(new ResponseSchema({ status: false, message: this.parseMessage(logicResult.message, currentReq.t, true), code: bizCode }).getResponse);
168
144
  }
169
145
  const resResult = response ? await response({ ...p, logicResult }) : logicResult;
170
- if (resResult instanceof Response || resResult instanceof Blob || resResult instanceof Uint8Array || resResult instanceof ArrayBuffer) {
146
+ extractMeta(resResult);
147
+ if (resResult instanceof Response || resResult instanceof Blob || resResult instanceof Uint8Array || resResult instanceof ArrayBuffer)
171
148
  return currentRes.status(200).send(resResult);
172
- }
173
149
  let finalData = undefined;
174
150
  let finalExtraData = undefined;
175
151
  let messageSource = 'success_process';
176
- let bizSuccessCode = this.currentStore?.metadata?._code || 200;
177
- const extract = (obj) => {
152
+ const extractData = (obj) => {
178
153
  if (!obj || typeof obj !== 'object')
179
154
  return;
180
155
  if (obj.payload && typeof obj.payload === 'object') {
@@ -186,44 +161,35 @@ export default class Controller extends BaseController {
186
161
  finalExtraData = obj.extraData;
187
162
  }
188
163
  else {
189
- const hasMeta = obj.status !== undefined || obj.message !== undefined || obj.code !== undefined;
164
+ const hasMeta = obj.status !== undefined || obj.message !== undefined || obj.code !== undefined || obj.statusCode !== undefined;
190
165
  if (!hasMeta && Object.keys(obj).length > 0)
191
166
  finalData = obj;
192
167
  }
193
168
  if (obj.message)
194
169
  messageSource = obj.message;
195
- if (obj.code !== undefined)
196
- bizSuccessCode = obj.code;
197
170
  };
198
171
  if (typeof resResult === 'string') {
199
172
  messageSource = resResult;
200
- extract(logicResult);
173
+ extractData(logicResult);
201
174
  }
202
175
  else {
203
- extract(resResult !== undefined ? resResult : logicResult);
176
+ extractData(resResult !== undefined ? resResult : logicResult);
204
177
  }
178
+ const bizSuccessCode = store?.metadata._code || 200;
205
179
  let payload = undefined;
206
180
  if (finalData !== undefined || finalExtraData !== undefined) {
207
- payload = {
208
- data: finalData ?? {},
209
- extraData: finalExtraData ?? {}
210
- };
181
+ payload = {};
182
+ if (finalData !== undefined)
183
+ payload.data = finalData;
184
+ if (finalExtraData !== undefined)
185
+ payload.extraData = finalExtraData;
211
186
  }
212
- return currentRes.status(bizSuccessCode).send(new ResponseSchema({
213
- status: true,
214
- message: this.parseMessage(messageSource, currentReq.t, false),
215
- payload,
216
- code: bizSuccessCode
217
- }).getResponse);
187
+ return currentRes.status(bizSuccessCode).send(new ResponseSchema({ status: true, message: this.parseMessage(messageSource, currentReq.t, false), payload, code: bizSuccessCode }).getResponse);
218
188
  }
219
189
  catch (error) {
220
190
  this.logger?.log(LoggerLayerEnum.ERROR, `Controller Error: ${error.message}`);
221
191
  const t = currentReq?.t || ((k) => k);
222
- return this.res.status(500).send(new ResponseSchema({
223
- status: false,
224
- message: this.parseMessage(error.message, t, true),
225
- code: 500
226
- }).getResponse);
192
+ return this.res.status(500).send(new ResponseSchema({ status: false, message: this.parseMessage(error.message, t, true), code: 500 }).getResponse);
227
193
  }
228
194
  }
229
195
  }