@xrystal/core 3.23.1 → 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.1",
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,13 +63,12 @@ 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
  }
71
70
  export interface CustomResponse {
72
71
  status: (code: number) => CustomResponse;
73
- setRaw: (isRaw?: boolean) => CustomResponse;
74
72
  send: (data: any) => any;
75
73
  json: (data: any) => any;
76
74
  locals: Record<string, any>;
@@ -13,19 +13,13 @@ 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() {
@@ -35,7 +29,6 @@ export class BaseController {
35
29
  status: function () { return this; },
36
30
  send: (d) => d,
37
31
  json: function (d) { return this.send(d); },
38
- setRaw: function () { return this; },
39
32
  locals: {}
40
33
  };
41
34
  if (!store)
@@ -48,25 +41,13 @@ export class BaseController {
48
41
  store.metadata._code = code;
49
42
  return this;
50
43
  },
51
- setRaw(isRaw = true) {
52
- store.metadata._isRaw = isRaw;
53
- return this;
54
- },
55
44
  send(data) {
56
45
  if (self.protocol === ProtocolEnum.WEBSOCKET)
57
46
  return data;
58
- if (data instanceof Response)
59
- return data;
60
47
  const status = store.metadata?._code || 200;
61
- const isRaw = store.metadata?._isRaw;
62
- if (isRaw) {
63
- const contentType = store.metadata?._contentType || (typeof data === 'string' ? 'text/plain' : 'application/octet-stream');
64
- return new Response(data, { status, headers: { 'content-type': contentType } });
65
- }
66
- const body = JSON.stringify(data?.getResponse ? data.getResponse : data);
48
+ const body = (store.metadata?._isRaw) ? data : JSON.stringify(data?.getResponse ? data.getResponse : data);
67
49
  return new Response(body, { status, headers: { 'content-type': 'application/json' } });
68
- },
69
- json(data) { return this.send(data); }
50
+ }
70
51
  };
71
52
  }
72
53
  }
@@ -76,14 +57,6 @@ export default class Controller extends BaseController {
76
57
  const protocols = this.system?.tmp?.configs?.loaders?.controller?.protocols;
77
58
  this.supportedProtocols = Array.isArray(protocols) ? protocols : [protocols || ProtocolEnum.HTTP];
78
59
  }
79
- smartTranslate(word, t) {
80
- const keyPath = `keywords.${word}`;
81
- const translated = t(keyPath);
82
- if (translated !== keyPath)
83
- return translated;
84
- const direct = t(word);
85
- return direct !== word ? direct : word;
86
- }
87
60
  parseMessage(input, t) {
88
61
  if (!input || typeof input !== 'string' || !input.startsWith('@'))
89
62
  return input;
@@ -92,85 +65,65 @@ export default class Controller extends BaseController {
92
65
  const hasMethod = typeof responseMessageHelper[maybeMethod] === 'function';
93
66
  const methodName = hasMethod ? maybeMethod : 'successfully';
94
67
  const rawArgs = hasMethod ? parts.slice(1) : parts;
95
- 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
+ });
96
72
  return responseMessageHelper[methodName](translatedArgs[0] || '', translatedArgs.slice(1).join(' '), t);
97
73
  }
98
74
  async schema({ checks, logic, response }) {
99
75
  try {
100
76
  const currentReq = this.req;
77
+ const currentRes = this.res;
101
78
  const store = this.currentStore;
102
79
  const t = currentReq.t;
103
- const p = {
104
- req: currentReq,
105
- res: this.res,
106
- body: currentReq.body,
107
- query: currentReq.query,
108
- params: currentReq.params,
109
- locals: store?.metadata?.locals || {},
110
- t
111
- };
80
+ const p = { req: currentReq, res: currentRes, body: currentReq.body, query: currentReq.query, params: currentReq.params, locals: store?.metadata?.locals || {}, t };
112
81
  if (checks) {
113
82
  const checkRes = await checks(p);
114
83
  if (checkRes !== true) {
115
84
  const isObj = checkRes && typeof checkRes === 'object';
116
85
  const code = isObj ? checkRes.code || 400 : 400;
117
- const rawMsg = isObj ? checkRes.message : (typeof checkRes === 'string' ? checkRes : '@schemaMissingDataChecks');
118
- const { message: _m, status: _s, code: _c, data, payload, ...rest } = isObj ? checkRes : {};
119
- const errCoreData = data ?? payload ?? (Object.keys(rest).length > 0 ? rest : undefined);
120
- 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({
121
92
  status: false,
122
93
  message: this.parseMessage(rawMsg, t),
94
+ payload: (coreData !== undefined || Object.keys(extras).length > 0) ? { data: coreData, extraData: extras } : undefined,
123
95
  code
124
- };
125
- if (errCoreData !== undefined) {
126
- errRes.payload = { data: errCoreData };
127
- }
128
- return this.res.status(code).send(new ResponseSchema(errRes).getResponse);
96
+ }).getResponse);
129
97
  }
130
98
  }
131
99
  let logicRes = logic ? await logic(p) : null;
132
100
  if (logic && logicRes === false) {
133
- 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);
134
102
  }
135
103
  let finalRes = response ? await response({ ...p, logicResult: logicRes }) : logicRes;
136
104
  if (typeof finalRes === 'function')
137
105
  finalRes = await finalRes(p);
106
+ if (Array.isArray(finalRes))
107
+ finalRes = { message: `@successfully ${finalRes.join(' ')}` };
138
108
  if (finalRes instanceof Response || finalRes?.constructor?.name === 'Response')
139
109
  return finalRes;
140
- if (store?.metadata?._isRaw)
141
- return this.res.send(finalRes);
142
110
  const isSuccess = finalRes?.status !== false;
143
111
  const finalCode = finalRes?.code || store?.metadata?._code || 200;
144
- const msgSource = finalRes?.message || (typeof finalRes === 'string' ? finalRes : '@successfully');
145
- let coreData;
146
- let extraData = {};
147
- if (finalRes && typeof finalRes === 'object' && !Array.isArray(finalRes)) {
148
- const { message: _m, status: _s, code: _co, data, payload, ...rest } = finalRes;
149
- coreData = data ?? payload;
150
- if (coreData === undefined) {
151
- coreData = Object.keys(rest).length > 0 ? rest : logicRes;
152
- }
153
- else {
154
- extraData = rest;
155
- }
156
- }
157
- else {
158
- coreData = finalRes ?? logicRes;
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
- message: this.parseMessage(msgSource, t),
163
- code: finalCode
120
+ message: this.parseMessage(msgSource, t)
164
121
  };
165
- const payloadContainer = {};
166
- if (coreData !== undefined && coreData !== null)
167
- payloadContainer.data = coreData;
168
- if (Object.keys(extraData).length > 0)
169
- payloadContainer.extraData = extraData;
170
- if (Object.keys(payloadContainer).length > 0) {
171
- responseData.payload = payloadContainer;
122
+ if (coreData !== undefined || Object.keys(extraData).length > 0) {
123
+ responseData.payload = { data: coreData, extraData: Object.keys(extraData).length > 0 ? extraData : undefined };
172
124
  }
173
- return this.res.status(finalCode).send(new ResponseSchema(responseData).getResponse);
125
+ responseData.code = finalCode;
126
+ return currentRes.status(finalCode).send(new ResponseSchema(responseData).getResponse);
174
127
  }
175
128
  catch (error) {
176
129
  this.logger?.log(LoggerLayerEnum.ERROR, `Controller Error: ${error.message}`);