@xrystal/core 3.23.0 → 3.23.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "author": "Yusuf Yasir KAYGUSUZ",
3
3
  "name": "@xrystal/core",
4
- "version": "3.23.0",
4
+ "version": "3.23.2",
5
5
  "description": "Project core for xrystal",
6
6
  "publishConfig": {
7
7
  "access": "public",
@@ -49,7 +49,6 @@ export declare abstract class BaseController {
49
49
  export default abstract class Controller extends BaseController implements IProvide<any> {
50
50
  constructor();
51
51
  onInit(): Promise<void>;
52
- private smartTranslate;
53
52
  private parseMessage;
54
53
  schema<T = any>({ checks, logic, response }: {
55
54
  checks?: (args: any) => Promise<any>;
@@ -64,7 +63,7 @@ export interface CustomRequest {
64
63
  headers: Record<string, any>;
65
64
  body?: any;
66
65
  params: Record<string, any>;
67
- query: any;
66
+ query: Record<string, any>;
68
67
  lang: string;
69
68
  t: (k: string, args?: any) => string;
70
69
  }
@@ -13,25 +13,24 @@ export class BaseController {
13
13
  get currentStore() { return getControllerCtx(); }
14
14
  get req() {
15
15
  const store = this.currentStore;
16
- const identityT = (k) => k;
17
16
  const ctx = store?.ctx || {};
18
17
  const query = typeof ctx.query === 'string' ? qs.parse(ctx.query) : (ctx.query || {});
19
18
  return {
20
- url: ctx.url || '',
21
- method: ctx.method || '',
22
- headers: ctx.headers || {},
23
- body: ctx.body || {},
24
- query: query,
25
- params: ctx.params || {},
26
- lang: ctx.lang || 'en',
27
- t: ctx.t || identityT,
28
- accounts: ctx.accounts || {}
19
+ url: ctx.url || '', method: ctx.method || '', headers: ctx.headers || {},
20
+ body: ctx.body || {}, query: query, params: ctx.params || {},
21
+ lang: ctx.lang || 'en', t: ctx.t || ((k) => k),
22
+ accounts: ctx.accounts || store?.req?.accounts
29
23
  };
30
24
  }
31
25
  get res() {
32
26
  const store = this.currentStore;
33
27
  const self = this;
34
- const fallbackRes = { status: function () { return this; }, send: (d) => d, json: function (d) { return this.send(d); }, locals: {} };
28
+ const fallbackRes = {
29
+ status: function () { return this; },
30
+ send: (d) => d,
31
+ json: function (d) { return this.send(d); },
32
+ locals: {}
33
+ };
35
34
  if (!store)
36
35
  return fallbackRes;
37
36
  if (!store.metadata)
@@ -45,13 +44,10 @@ export class BaseController {
45
44
  send(data) {
46
45
  if (self.protocol === ProtocolEnum.WEBSOCKET)
47
46
  return data;
48
- if (data instanceof Response)
49
- return data;
50
47
  const status = store.metadata?._code || 200;
51
48
  const body = (store.metadata?._isRaw) ? data : JSON.stringify(data?.getResponse ? data.getResponse : data);
52
49
  return new Response(body, { status, headers: { 'content-type': 'application/json' } });
53
- },
54
- json(data) { return this.send(data); }
50
+ }
55
51
  };
56
52
  }
57
53
  }
@@ -61,14 +57,6 @@ export default class Controller extends BaseController {
61
57
  const protocols = this.system?.tmp?.configs?.loaders?.controller?.protocols;
62
58
  this.supportedProtocols = Array.isArray(protocols) ? protocols : [protocols || ProtocolEnum.HTTP];
63
59
  }
64
- smartTranslate(word, t) {
65
- const keyPath = `keywords.${word}`;
66
- const translated = t(keyPath);
67
- if (translated !== keyPath)
68
- return translated;
69
- const direct = t(word);
70
- return direct !== word ? direct : word;
71
- }
72
60
  parseMessage(input, t) {
73
61
  if (!input || typeof input !== 'string' || !input.startsWith('@'))
74
62
  return input;
@@ -77,99 +65,65 @@ export default class Controller extends BaseController {
77
65
  const hasMethod = typeof responseMessageHelper[maybeMethod] === 'function';
78
66
  const methodName = hasMethod ? maybeMethod : 'successfully';
79
67
  const rawArgs = hasMethod ? parts.slice(1) : parts;
80
- const translatedArgs = rawArgs.map(arg => this.smartTranslate(arg, t));
68
+ const translatedArgs = rawArgs.map(arg => {
69
+ const res = t(`keywords.${arg}`);
70
+ return res !== `keywords.${arg}` ? res : (t(arg) !== arg ? t(arg) : arg);
71
+ });
81
72
  return responseMessageHelper[methodName](translatedArgs[0] || '', translatedArgs.slice(1).join(' '), t);
82
73
  }
83
74
  async schema({ checks, logic, response }) {
84
75
  try {
85
76
  const currentReq = this.req;
77
+ const currentRes = this.res;
86
78
  const store = this.currentStore;
87
79
  const t = currentReq.t;
88
- const p = {
89
- req: currentReq,
90
- res: this.res,
91
- body: currentReq.body,
92
- query: currentReq.query,
93
- params: currentReq.params,
94
- locals: store?.metadata?.locals || {},
95
- t
96
- };
80
+ const p = { req: currentReq, res: currentRes, body: currentReq.body, query: currentReq.query, params: currentReq.params, locals: store?.metadata?.locals || {}, t };
97
81
  if (checks) {
98
82
  const checkRes = await checks(p);
99
83
  if (checkRes !== true) {
100
84
  const isObj = checkRes && typeof checkRes === 'object';
101
85
  const code = isObj ? checkRes.code || 400 : 400;
102
- const rawMsg = isObj ? checkRes.message : (typeof checkRes === 'string' ? checkRes : '@schemaMissingDataChecks');
103
- const { message, status, code: _c, ...rest } = isObj ? checkRes : {};
104
- let errCoreData = rest.data !== undefined ? rest.data : rest.payload;
105
- let errExtras = { ...rest };
106
- if (rest.data !== undefined || rest.payload !== undefined) {
107
- delete errExtras.data;
108
- delete errExtras.payload;
109
- }
110
- else {
111
- errCoreData = Object.keys(rest).length > 0 ? rest : undefined;
112
- errExtras = {};
113
- }
114
- const errRes = {
86
+ let rawMsg = isObj ? checkRes.message : (typeof checkRes === 'string' ? checkRes : '@schemaMissingDataChecks');
87
+ if (typeof rawMsg === 'string' && !rawMsg.startsWith('@'))
88
+ rawMsg = '@' + rawMsg;
89
+ const { message, status, code: _c, data, payload, ...extras } = isObj ? checkRes : {};
90
+ const coreData = data || payload;
91
+ return currentRes.status(code).send(new ResponseSchema({
115
92
  status: false,
116
93
  message: this.parseMessage(rawMsg, t),
94
+ payload: (coreData !== undefined || Object.keys(extras).length > 0) ? { data: coreData, extraData: extras } : undefined,
117
95
  code
118
- };
119
- if (errCoreData !== undefined || Object.keys(errExtras).length > 0) {
120
- errRes.payload = {
121
- ...(errCoreData !== undefined && { data: errCoreData }),
122
- ...(Object.keys(errExtras).length > 0 && { extraData: errExtras })
123
- };
124
- }
125
- return this.res.status(code).send(new ResponseSchema(errRes).getResponse);
96
+ }).getResponse);
126
97
  }
127
98
  }
128
99
  let logicRes = logic ? await logic(p) : null;
129
100
  if (logic && logicRes === false) {
130
- return this.res.status(400).send(new ResponseSchema({ status: false, message: this.parseMessage('@unsuccessful logic', t), code: 400 }).getResponse);
101
+ return currentRes.status(400).send(new ResponseSchema({ status: false, message: this.parseMessage('@unsuccessful logic', t), code: 400 }).getResponse);
131
102
  }
132
103
  let finalRes = response ? await response({ ...p, logicResult: logicRes }) : logicRes;
133
104
  if (typeof finalRes === 'function')
134
105
  finalRes = await finalRes(p);
135
- if (Array.isArray(finalRes)) {
136
- finalRes = { message: `@successfully ${finalRes.join(' ')}`, data: logicRes };
137
- }
138
- else if (typeof finalRes === 'string' && !finalRes.startsWith('@')) {
139
- finalRes = { message: `@successfully ${finalRes}`, data: logicRes };
140
- }
106
+ if (Array.isArray(finalRes))
107
+ finalRes = { message: `@successfully ${finalRes.join(' ')}` };
141
108
  if (finalRes instanceof Response || finalRes?.constructor?.name === 'Response')
142
109
  return finalRes;
143
110
  const isSuccess = finalRes?.status !== false;
144
111
  const finalCode = finalRes?.code || store?.metadata?._code || 200;
145
- const msgSource = finalRes?.message || (typeof finalRes === 'string' ? finalRes : '@successfully');
146
- const rawOutput = (finalRes && typeof finalRes === 'object' && !Array.isArray(finalRes))
147
- ? finalRes
148
- : { data: finalRes || logicRes };
149
- const { message: _m, status: _s, code: _co, data, payload, ...restExtras } = rawOutput;
150
- let coreData;
151
- let extraData;
152
- if (data !== undefined || payload !== undefined) {
153
- coreData = data !== undefined ? data : payload;
154
- extraData = restExtras;
155
- }
156
- else {
157
- coreData = Object.keys(restExtras).length > 0 ? restExtras : (finalRes || logicRes);
158
- extraData = {};
159
- }
112
+ let msgSource = finalRes?.message || (typeof finalRes === 'string' ? finalRes : '@successfully');
113
+ if (typeof msgSource === 'string' && !msgSource.startsWith('@'))
114
+ msgSource = '@' + msgSource;
115
+ const rawOutput = (finalRes && typeof finalRes === 'object' && !Array.isArray(finalRes)) ? finalRes : { data: finalRes };
116
+ const { message, status, code, data, payload, ...extraData } = rawOutput;
117
+ const coreData = data !== undefined ? data : payload;
160
118
  const responseData = {
161
119
  status: isSuccess,
162
120
  message: this.parseMessage(msgSource, t)
163
121
  };
164
- const finalPayload = {};
165
- if (coreData !== undefined && coreData !== null)
166
- finalPayload.data = coreData;
167
- if (Object.keys(extraData).length > 0)
168
- finalPayload.extraData = extraData;
169
- if (Object.keys(finalPayload).length > 0)
170
- responseData.payload = finalPayload;
122
+ if (coreData !== undefined || Object.keys(extraData).length > 0) {
123
+ responseData.payload = { data: coreData, extraData: Object.keys(extraData).length > 0 ? extraData : undefined };
124
+ }
171
125
  responseData.code = finalCode;
172
- return this.res.status(finalCode).send(new ResponseSchema(responseData).getResponse);
126
+ return currentRes.status(finalCode).send(new ResponseSchema(responseData).getResponse);
173
127
  }
174
128
  catch (error) {
175
129
  this.logger?.log(LoggerLayerEnum.ERROR, `Controller Error: ${error.message}`);