phecda-server 1.2.4 → 1.4.0

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/dist/index.mjs CHANGED
@@ -55,6 +55,8 @@ var defaultPipe = {
55
55
  args[i].arg = ret.data;
56
56
  } else {
57
57
  args[i].arg = reflect[i](arg);
58
+ if (reflect[i] === Number && Object.is(args[i].arg, NaN))
59
+ throw new ValidateException(`parameter ${Number(i) + 1} should be a number`);
58
60
  }
59
61
  }
60
62
  return args.map((item) => item.arg);
@@ -85,14 +87,6 @@ var BadRequestException = class extends HttpException {
85
87
  };
86
88
  __name(BadRequestException, "BadRequestException");
87
89
 
88
- // src/exception/wrong-meta.ts
89
- var WrongMetaException = class extends HttpException {
90
- constructor(message) {
91
- super(message, 500, "Meta is not correct");
92
- }
93
- };
94
- __name(WrongMetaException, "WrongMetaException");
95
-
96
90
  // src/exception/not-found.ts
97
91
  var NotFoundException = class extends HttpException {
98
92
  constructor(message) {
@@ -101,6 +95,78 @@ var NotFoundException = class extends HttpException {
101
95
  };
102
96
  __name(NotFoundException, "NotFoundException");
103
97
 
98
+ // src/exception/conflict.ts
99
+ var ConflictException = class extends HttpException {
100
+ constructor(message) {
101
+ super(message, 409, "Conflict");
102
+ }
103
+ };
104
+ __name(ConflictException, "ConflictException");
105
+
106
+ // src/exception/bad-gateway.ts
107
+ var BadGatewayException = class extends HttpException {
108
+ constructor(message) {
109
+ super(message, 400, "Bad Gatrway");
110
+ }
111
+ };
112
+ __name(BadGatewayException, "BadGatewayException");
113
+
114
+ // src/exception/invalid-input.ts
115
+ var InvalidInputException = class extends HttpException {
116
+ constructor(message) {
117
+ super(message, 502, "Invalid Input");
118
+ }
119
+ };
120
+ __name(InvalidInputException, "InvalidInputException");
121
+
122
+ // src/exception/media-type.ts
123
+ var UnsupportedMediaTypeException = class extends HttpException {
124
+ constructor(message) {
125
+ super(message, 415, "Unsupported Media Type");
126
+ }
127
+ };
128
+ __name(UnsupportedMediaTypeException, "UnsupportedMediaTypeException");
129
+
130
+ // src/exception/payload-large.ts
131
+ var PayloadLargeException = class extends HttpException {
132
+ constructor(message) {
133
+ super(message, 413, "Payload Too Large");
134
+ }
135
+ };
136
+ __name(PayloadLargeException, "PayloadLargeException");
137
+
138
+ // src/exception/timeout.ts
139
+ var TimeoutException = class extends HttpException {
140
+ constructor(message) {
141
+ super(message, 408, "Request Timeout");
142
+ }
143
+ };
144
+ __name(TimeoutException, "TimeoutException");
145
+
146
+ // src/exception/unauthorized.ts
147
+ var UnauthorizedException = class extends HttpException {
148
+ constructor(message) {
149
+ super(message, 401, "Unauthorized");
150
+ }
151
+ };
152
+ __name(UnauthorizedException, "UnauthorizedException");
153
+
154
+ // src/exception/unavailable-service.ts
155
+ var ServiceUnavailableException = class extends HttpException {
156
+ constructor(message) {
157
+ super(message, 503, "Service Unavailable");
158
+ }
159
+ };
160
+ __name(ServiceUnavailableException, "ServiceUnavailableException");
161
+
162
+ // src/exception/framework.ts
163
+ var FrameworkException = class extends HttpException {
164
+ constructor(message) {
165
+ super(`[phecda-server] ${message}`, 500, "Framework Error");
166
+ }
167
+ };
168
+ __name(FrameworkException, "FrameworkException");
169
+
104
170
  // src/filter.ts
105
171
  var serverFilter = /* @__PURE__ */ __name((e) => {
106
172
  if (!(e instanceof HttpException))
@@ -149,7 +215,7 @@ var _Pcontext = class {
149
215
  for (const guard of guards) {
150
216
  if (this.history.record(guard, "guard")) {
151
217
  if (!(guard in _Pcontext.guardsRecord))
152
- throw new WrongMetaException(`can't find guard named ${guard}`);
218
+ throw new FrameworkException(`can't find guard named ${guard}`);
153
219
  if (!await _Pcontext.guardsRecord[guard](this.data, isMerge))
154
220
  throw new ForbiddenException(`Guard exception--${guard}`);
155
221
  }
@@ -160,7 +226,7 @@ var _Pcontext = class {
160
226
  for (const interceptor of interceptors) {
161
227
  if (this.history.record(interceptor, "interceptor")) {
162
228
  if (!(interceptor in _Pcontext.interceptorsRecord))
163
- throw new WrongMetaException(`can't find guard named ${interceptor}`);
229
+ throw new FrameworkException(`can't find guard named ${interceptor}`);
164
230
  const post = await _Pcontext.interceptorsRecord[interceptor](this.data, isMerge);
165
231
  if (post)
166
232
  ret.push(post);
@@ -219,13 +285,16 @@ var _ServerContext = class extends Pcontext {
219
285
  static useMiddleware(middlewares) {
220
286
  return middlewares.map((m) => {
221
287
  if (!(m in _ServerContext.middlewareRecord))
222
- throw new WrongMetaException(`can't find middleware named ${m}`);
288
+ throw new FrameworkException(`can't find middleware named ${m}`);
223
289
  return _ServerContext.middlewareRecord[m];
224
290
  });
225
291
  }
226
292
  async usePipe(args, reflect) {
227
293
  return _ServerContext.pipe.transform?.(args, reflect);
228
294
  }
295
+ static useFilter(arg, data) {
296
+ return _ServerContext.filter(arg, data);
297
+ }
229
298
  useFilter(arg) {
230
299
  return _ServerContext.filter(arg, this.data);
231
300
  }
@@ -253,13 +322,16 @@ var _RabbitMqContext = class extends Pcontext {
253
322
  static useMiddleware(middlewares) {
254
323
  return middlewares.map((m) => {
255
324
  if (!(m in _RabbitMqContext.middlewareRecord))
256
- throw new WrongMetaException(`can't find middleware named ${m}`);
325
+ throw new FrameworkException(`can't find middleware named ${m}`);
257
326
  return _RabbitMqContext.middlewareRecord[m];
258
327
  });
259
328
  }
260
329
  async usePipe(args, reflect) {
261
330
  return _RabbitMqContext.pipe.transform?.(args, reflect);
262
331
  }
332
+ static useFilter(arg, data) {
333
+ return _RabbitMqContext.filter(arg, data);
334
+ }
263
335
  useFilter(arg) {
264
336
  return _RabbitMqContext.filter(arg, this.data);
265
337
  }
@@ -278,6 +350,12 @@ function useMqFilter(filter) {
278
350
  }
279
351
  __name(useMqFilter, "useMqFilter");
280
352
 
353
+ // src/types.ts
354
+ var Base = class {
355
+ context;
356
+ };
357
+ __name(Base, "Base");
358
+
281
359
  // src/compiler.ts
282
360
  var Pcompiler = class {
283
361
  content = "";
@@ -294,28 +372,17 @@ var Pcompiler = class {
294
372
  }
295
373
  return content;
296
374
  }
297
- addMethod(className, methodName, route = "", requestType = "", params = []) {
375
+ addMethod(args) {
376
+ const { route: { route = "/", type = "get" } = {}, name, method, params, tag } = args;
298
377
  const url = route.replace(/\/\:([^\/]*)/g, "");
299
- if (!this.classMap[className])
300
- this.classMap[className] = {};
301
- this.classMap[className][methodName] = `
302
- ${methodName}(${genParams(params)}){
303
- const ret={tag:"${className}-${methodName}",body:{},query:{},params:{},realParam:'',method:"${requestType}",url:"${url}"}
378
+ if (!this.classMap[name])
379
+ this.classMap[name] = {};
380
+ this.classMap[name][method] = `
381
+ ${method}(${genParams(params)}){
382
+ const ret={tag:"${tag}-${method}",body:{},query:{},params:{},realParam:'',method:"${type}",url:"${url}"}
304
383
  ${params.filter((item) => item.key).reduce((p, c, i) => `${p}ret.${c.type}.${c.key}=arg${i}
305
384
  ${c.type === "params" ? `ret.realParam+='/'+arg${i}
306
385
  ` : ""}`, "")}
307
- return ret
308
- }
309
- `;
310
- }
311
- addMqMethod(className, methodName, exchange = "", routeKey = "", queue = "", params = []) {
312
- if (!this.classMap[className])
313
- this.classMap[className] = {};
314
- this.classMap[className][methodName] = `
315
- ${methodName}(${genParams(params)}){
316
- const ret={tag:"${className}-${methodName}",exchange:"${exchange}",routeKey:"${routeKey}",queue:"${queue}",args:{}}
317
- ${params.reduce((p, c, i) => `${p}ret.args.${c.key}=arg${i}
318
- `, "")}
319
386
  return ret
320
387
  }
321
388
  `;
@@ -323,10 +390,9 @@ return ret
323
390
  };
324
391
  __name(Pcompiler, "Pcompiler");
325
392
  function genParams(decorators) {
326
- let index = 0;
327
- return decorators.reduce((p) => {
328
- return `${`${p}arg${index++}`},`;
329
- }, "");
393
+ return decorators.map((_, i) => {
394
+ return `${`arg${i}`}`;
395
+ }).join(",");
330
396
  }
331
397
  __name(genParams, "genParams");
332
398
 
@@ -343,7 +409,7 @@ __name(resolveDep, "resolveDep");
343
409
 
344
410
  // src/common.ts
345
411
  var SERIES_SYMBOL = "__symbol_series__";
346
- var REQ_SYMBOL = "__symbol_req__";
412
+ var MERGE_SYMBOL = "__symbol_req__";
347
413
 
348
414
  // src/server/express.ts
349
415
  function bindApp(app, { meta, moduleMap }, options = {}) {
@@ -355,12 +421,14 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
355
421
  ...options
356
422
  };
357
423
  const methodMap = {};
424
+ const contextMeta = {};
358
425
  for (const i of meta) {
359
- const { name, method, route: route2, header } = i.data;
360
- const instance = moduleMap.get(name);
361
- const tag = `${name}-${method}`;
362
- Pcontext.metaRecord[tag] = i;
363
- let { guards, reflect, interceptors, params, middlewares } = Pcontext.metaDataRecord[tag] ? Pcontext.metaDataRecord[tag] : Pcontext.metaDataRecord[tag] = parseMeta(i);
426
+ const { name, method, route: route2, header, tag } = i.data;
427
+ const instance = moduleMap.get(tag);
428
+ const methodTag = `${tag}-${method}`;
429
+ contextMeta[methodTag] = i;
430
+ Pcontext.metaRecord[methodTag] = i;
431
+ let { guards, reflect, interceptors, params, middlewares } = Pcontext.metaDataRecord[methodTag] ? Pcontext.metaDataRecord[methodTag] : Pcontext.metaDataRecord[methodTag] = parseMeta(i);
364
432
  guards = [
365
433
  ...globalGuards,
366
434
  ...guards
@@ -370,16 +438,16 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
370
438
  ...interceptors
371
439
  ];
372
440
  const handler = instance[method].bind(instance);
373
- methodMap[tag] = handler;
441
+ methodMap[methodTag] = handler;
374
442
  Pcontext.instanceRecord[name] = instance;
375
443
  if (route2) {
376
444
  app[route2.type](route2.route, ...ServerContext.useMiddleware(middlewares), async (req, res) => {
377
445
  const contextData = {
378
446
  request: req,
379
- tag,
447
+ meta: i,
380
448
  response: res
381
449
  };
382
- const context = new ServerContext(tag, contextData);
450
+ const context = new ServerContext(methodTag, contextData);
383
451
  try {
384
452
  for (const name2 in header)
385
453
  res.set(name2, header[name2]);
@@ -391,7 +459,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
391
459
  validate
392
460
  };
393
461
  }), reflect);
394
- instance.meta = contextData;
462
+ instance.context = contextData;
395
463
  const ret = await context.usePost(await handler(...args));
396
464
  if (isObject(ret))
397
465
  res.json(ret);
@@ -406,16 +474,20 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
406
474
  }
407
475
  }
408
476
  app.post(route, (req, _res, next) => {
409
- req[REQ_SYMBOL] = true;
477
+ req[MERGE_SYMBOL] = true;
410
478
  next();
411
479
  }, ...ServerContext.useMiddleware(proMiddle), async (req, res) => {
480
+ const { body: { category, data } } = req;
412
481
  const contextData = {
413
482
  request: req,
414
- response: res
483
+ response: res,
484
+ meta: contextMeta
415
485
  };
486
+ if (!Array.isArray(data))
487
+ return res.json(await ServerContext.useFilter(new BadRequestException("data format should be an array"), contextData));
488
+ contextData.tags = data.map((item) => item.tag);
416
489
  const context = new ServerContext(route, contextData);
417
490
  const ret = [];
418
- const { body: { category, data } } = req;
419
491
  if (category === "series") {
420
492
  for (const item of data) {
421
493
  const { tag } = item;
@@ -424,7 +496,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
424
496
  const instance = moduleMap.get(name);
425
497
  try {
426
498
  if (!params)
427
- throw new NotFoundException(`"${tag}" doesn't exist`);
499
+ throw new BadRequestException(`"${tag}" doesn't exist`);
428
500
  await context.useGuard(guards, true);
429
501
  await context.useInterceptor(interceptors, true);
430
502
  const args = await context.usePipe(params.map(({ type, key, validate }) => {
@@ -441,7 +513,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
441
513
  validate
442
514
  };
443
515
  }), reflect);
444
- instance.meta = contextData;
516
+ instance.context = contextData;
445
517
  ret.push(await context.usePost(await methodMap[tag](...args)));
446
518
  } catch (e) {
447
519
  const m = Pcontext.metaRecord[tag];
@@ -460,7 +532,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
460
532
  const instance = moduleMap.get(name);
461
533
  try {
462
534
  if (!params)
463
- throw new NotFoundException(`"${tag}" doesn't exist`);
535
+ throw new BadRequestException(`"${tag}" doesn't exist`);
464
536
  await context.useGuard(guards, true);
465
537
  await context.useInterceptor(interceptors, true);
466
538
  const args = await context.usePipe(params.map(({ type, key, validate }) => {
@@ -470,7 +542,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
470
542
  validate
471
543
  };
472
544
  }), reflect);
473
- instance.meta = contextData;
545
+ instance.context = contextData;
474
546
  resolve(await context.usePost(await methodMap[tag](...args)));
475
547
  } catch (e) {
476
548
  const m = Pcontext.metaRecord[tag];
@@ -482,7 +554,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
482
554
  res.json(ret2);
483
555
  });
484
556
  }
485
- res.json(await context.useFilter(new NotFoundException("category should be 'parallel' or 'series'")));
557
+ res.json(await context.useFilter(new BadRequestException("category should be 'parallel' or 'series'")));
486
558
  });
487
559
  }
488
560
  __name(bindApp, "bindApp");
@@ -523,35 +595,36 @@ async function Factory(Modules) {
523
595
  return {
524
596
  moduleMap,
525
597
  meta,
526
- output: (p) => fs.writeFileSync(p, JSON.stringify(meta.map((item) => item.data)))
598
+ output: (p = "pmeta.js") => fs.writeFileSync(p, JSON.stringify(meta.map((item) => item.data)))
527
599
  };
528
600
  }
529
601
  __name(Factory, "Factory");
530
602
  async function buildNestModule(Module, map, meta) {
531
603
  const paramtypes = getParamtypes(Module);
532
604
  let instance;
533
- const name = Module.prototype._namespace?.__TAG__ || Module.name;
534
- if (map.has(name)) {
535
- instance = map.get(name);
605
+ const tag = Module.prototype?.__TAG__ || Module.name;
606
+ if (map.has(tag)) {
607
+ instance = map.get(tag);
536
608
  if (!instance)
537
609
  throw new Error(`exist Circular Module dep--${Module}`);
538
610
  return instance;
539
611
  }
540
- map.set(name, void 0);
612
+ map.set(tag, void 0);
541
613
  if (paramtypes) {
614
+ const paramtypesInstances = [];
542
615
  for (const i in paramtypes)
543
- paramtypes[i] = await buildNestModule(paramtypes[i], map, meta);
544
- instance = new Module(...paramtypes);
616
+ paramtypesInstances[i] = await buildNestModule(paramtypes[i], map, meta);
617
+ instance = new Module(...paramtypesInstances);
545
618
  } else {
546
619
  instance = new Module();
547
620
  }
548
- meta.push(...getMetaFromInstance(instance, Module.name));
621
+ meta.push(...getMetaFromInstance(instance, Module.name, tag));
549
622
  await registerAsync(instance);
550
- map.set(name, instance);
623
+ map.set(tag, instance);
551
624
  return instance;
552
625
  }
553
626
  __name(buildNestModule, "buildNestModule");
554
- function getMetaFromInstance(instance, name) {
627
+ function getMetaFromInstance(instance, name, tag) {
555
628
  const vars = getExposeKey(instance).filter((item) => item !== "__CLASS");
556
629
  const baseState = getState(instance, "__CLASS") || {};
557
630
  initState(baseState);
@@ -560,6 +633,7 @@ function getMetaFromInstance(instance, name) {
560
633
  if (baseState.route && state.route)
561
634
  state.route.route = baseState.route.route + state.route.route;
562
635
  state.name = name;
636
+ state.tag = tag;
563
637
  state.method = i;
564
638
  const params = [];
565
639
  for (const i2 of state.params || []) {
@@ -779,6 +853,17 @@ function Header(name, value) {
779
853
  };
780
854
  }
781
855
  __name(Header, "Header");
856
+ function Meta(key, value) {
857
+ return (target, k) => {
858
+ setModalVar4(target, k);
859
+ mergeState4(target, k, {
860
+ meta: {
861
+ [key]: value
862
+ }
863
+ });
864
+ };
865
+ }
866
+ __name(Meta, "Meta");
782
867
 
783
868
  // src/index.ts
784
869
  export * from "phecda-core";
@@ -936,23 +1021,30 @@ function createMqReq(channel) {
936
1021
  __name(createMqReq, "createMqReq");
937
1022
  export {
938
1023
  $S,
1024
+ BadGatewayException,
939
1025
  BadRequestException,
1026
+ Base,
940
1027
  BaseParam,
941
1028
  Body,
1029
+ ConflictException,
942
1030
  Controller,
943
1031
  Delete,
944
1032
  Factory,
945
1033
  ForbiddenException,
1034
+ FrameworkException,
946
1035
  Get,
947
1036
  Guard,
948
1037
  Header,
949
1038
  HttpException,
950
1039
  Inject,
951
1040
  Interceptor,
1041
+ InvalidInputException,
952
1042
  MQ,
1043
+ Meta,
953
1044
  Middle,
954
1045
  NotFoundException,
955
1046
  Param,
1047
+ PayloadLargeException,
956
1048
  Pcompiler,
957
1049
  Pcontext,
958
1050
  Pmeta,
@@ -962,9 +1054,12 @@ export {
962
1054
  RabbitMqContext,
963
1055
  Route,
964
1056
  ServerContext,
1057
+ ServiceUnavailableException,
1058
+ TimeoutException,
1059
+ UnauthorizedException,
965
1060
  UndefinedException,
1061
+ UnsupportedMediaTypeException,
966
1062
  ValidateException,
967
- WrongMetaException,
968
1063
  addGuard,
969
1064
  addInterceptor,
970
1065
  addMiddleware,