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.js CHANGED
@@ -34,23 +34,30 @@ var __publicField = (obj, key, value) => {
34
34
  var src_exports = {};
35
35
  __export(src_exports, {
36
36
  $S: () => $S,
37
+ BadGatewayException: () => BadGatewayException,
37
38
  BadRequestException: () => BadRequestException,
39
+ Base: () => Base,
38
40
  BaseParam: () => BaseParam,
39
41
  Body: () => Body,
42
+ ConflictException: () => ConflictException,
40
43
  Controller: () => Controller,
41
44
  Delete: () => Delete,
42
45
  Factory: () => Factory,
43
46
  ForbiddenException: () => ForbiddenException,
47
+ FrameworkException: () => FrameworkException,
44
48
  Get: () => Get,
45
49
  Guard: () => Guard,
46
50
  Header: () => Header,
47
51
  HttpException: () => HttpException,
48
52
  Inject: () => Inject,
49
53
  Interceptor: () => Interceptor,
54
+ InvalidInputException: () => InvalidInputException,
50
55
  MQ: () => MQ,
56
+ Meta: () => Meta,
51
57
  Middle: () => Middle,
52
58
  NotFoundException: () => NotFoundException,
53
59
  Param: () => Param,
60
+ PayloadLargeException: () => PayloadLargeException,
54
61
  Pcompiler: () => Pcompiler,
55
62
  Pcontext: () => Pcontext,
56
63
  Pmeta: () => Pmeta,
@@ -60,9 +67,12 @@ __export(src_exports, {
60
67
  RabbitMqContext: () => RabbitMqContext,
61
68
  Route: () => Route,
62
69
  ServerContext: () => ServerContext,
70
+ ServiceUnavailableException: () => ServiceUnavailableException,
71
+ TimeoutException: () => TimeoutException,
72
+ UnauthorizedException: () => UnauthorizedException,
63
73
  UndefinedException: () => UndefinedException,
74
+ UnsupportedMediaTypeException: () => UnsupportedMediaTypeException,
64
75
  ValidateException: () => ValidateException,
65
- WrongMetaException: () => WrongMetaException,
66
76
  addGuard: () => addGuard,
67
77
  addInterceptor: () => addInterceptor,
68
78
  addMiddleware: () => addMiddleware,
@@ -136,6 +146,8 @@ var defaultPipe = {
136
146
  args[i].arg = ret.data;
137
147
  } else {
138
148
  args[i].arg = reflect[i](arg);
149
+ if (reflect[i] === Number && Object.is(args[i].arg, NaN))
150
+ throw new ValidateException(`parameter ${Number(i) + 1} should be a number`);
139
151
  }
140
152
  }
141
153
  return args.map((item) => item.arg);
@@ -166,14 +178,6 @@ var BadRequestException = class extends HttpException {
166
178
  };
167
179
  __name(BadRequestException, "BadRequestException");
168
180
 
169
- // src/exception/wrong-meta.ts
170
- var WrongMetaException = class extends HttpException {
171
- constructor(message) {
172
- super(message, 500, "Meta is not correct");
173
- }
174
- };
175
- __name(WrongMetaException, "WrongMetaException");
176
-
177
181
  // src/exception/not-found.ts
178
182
  var NotFoundException = class extends HttpException {
179
183
  constructor(message) {
@@ -182,6 +186,78 @@ var NotFoundException = class extends HttpException {
182
186
  };
183
187
  __name(NotFoundException, "NotFoundException");
184
188
 
189
+ // src/exception/conflict.ts
190
+ var ConflictException = class extends HttpException {
191
+ constructor(message) {
192
+ super(message, 409, "Conflict");
193
+ }
194
+ };
195
+ __name(ConflictException, "ConflictException");
196
+
197
+ // src/exception/bad-gateway.ts
198
+ var BadGatewayException = class extends HttpException {
199
+ constructor(message) {
200
+ super(message, 400, "Bad Gatrway");
201
+ }
202
+ };
203
+ __name(BadGatewayException, "BadGatewayException");
204
+
205
+ // src/exception/invalid-input.ts
206
+ var InvalidInputException = class extends HttpException {
207
+ constructor(message) {
208
+ super(message, 502, "Invalid Input");
209
+ }
210
+ };
211
+ __name(InvalidInputException, "InvalidInputException");
212
+
213
+ // src/exception/media-type.ts
214
+ var UnsupportedMediaTypeException = class extends HttpException {
215
+ constructor(message) {
216
+ super(message, 415, "Unsupported Media Type");
217
+ }
218
+ };
219
+ __name(UnsupportedMediaTypeException, "UnsupportedMediaTypeException");
220
+
221
+ // src/exception/payload-large.ts
222
+ var PayloadLargeException = class extends HttpException {
223
+ constructor(message) {
224
+ super(message, 413, "Payload Too Large");
225
+ }
226
+ };
227
+ __name(PayloadLargeException, "PayloadLargeException");
228
+
229
+ // src/exception/timeout.ts
230
+ var TimeoutException = class extends HttpException {
231
+ constructor(message) {
232
+ super(message, 408, "Request Timeout");
233
+ }
234
+ };
235
+ __name(TimeoutException, "TimeoutException");
236
+
237
+ // src/exception/unauthorized.ts
238
+ var UnauthorizedException = class extends HttpException {
239
+ constructor(message) {
240
+ super(message, 401, "Unauthorized");
241
+ }
242
+ };
243
+ __name(UnauthorizedException, "UnauthorizedException");
244
+
245
+ // src/exception/unavailable-service.ts
246
+ var ServiceUnavailableException = class extends HttpException {
247
+ constructor(message) {
248
+ super(message, 503, "Service Unavailable");
249
+ }
250
+ };
251
+ __name(ServiceUnavailableException, "ServiceUnavailableException");
252
+
253
+ // src/exception/framework.ts
254
+ var FrameworkException = class extends HttpException {
255
+ constructor(message) {
256
+ super(`[phecda-server] ${message}`, 500, "Framework Error");
257
+ }
258
+ };
259
+ __name(FrameworkException, "FrameworkException");
260
+
185
261
  // src/filter.ts
186
262
  var serverFilter = /* @__PURE__ */ __name((e) => {
187
263
  if (!(e instanceof HttpException))
@@ -230,7 +306,7 @@ var _Pcontext = class {
230
306
  for (const guard of guards) {
231
307
  if (this.history.record(guard, "guard")) {
232
308
  if (!(guard in _Pcontext.guardsRecord))
233
- throw new WrongMetaException(`can't find guard named ${guard}`);
309
+ throw new FrameworkException(`can't find guard named ${guard}`);
234
310
  if (!await _Pcontext.guardsRecord[guard](this.data, isMerge))
235
311
  throw new ForbiddenException(`Guard exception--${guard}`);
236
312
  }
@@ -241,7 +317,7 @@ var _Pcontext = class {
241
317
  for (const interceptor of interceptors) {
242
318
  if (this.history.record(interceptor, "interceptor")) {
243
319
  if (!(interceptor in _Pcontext.interceptorsRecord))
244
- throw new WrongMetaException(`can't find guard named ${interceptor}`);
320
+ throw new FrameworkException(`can't find guard named ${interceptor}`);
245
321
  const post = await _Pcontext.interceptorsRecord[interceptor](this.data, isMerge);
246
322
  if (post)
247
323
  ret.push(post);
@@ -300,13 +376,16 @@ var _ServerContext = class extends Pcontext {
300
376
  static useMiddleware(middlewares) {
301
377
  return middlewares.map((m) => {
302
378
  if (!(m in _ServerContext.middlewareRecord))
303
- throw new WrongMetaException(`can't find middleware named ${m}`);
379
+ throw new FrameworkException(`can't find middleware named ${m}`);
304
380
  return _ServerContext.middlewareRecord[m];
305
381
  });
306
382
  }
307
383
  async usePipe(args, reflect) {
308
384
  return _ServerContext.pipe.transform?.(args, reflect);
309
385
  }
386
+ static useFilter(arg, data) {
387
+ return _ServerContext.filter(arg, data);
388
+ }
310
389
  useFilter(arg) {
311
390
  return _ServerContext.filter(arg, this.data);
312
391
  }
@@ -334,13 +413,16 @@ var _RabbitMqContext = class extends Pcontext {
334
413
  static useMiddleware(middlewares) {
335
414
  return middlewares.map((m) => {
336
415
  if (!(m in _RabbitMqContext.middlewareRecord))
337
- throw new WrongMetaException(`can't find middleware named ${m}`);
416
+ throw new FrameworkException(`can't find middleware named ${m}`);
338
417
  return _RabbitMqContext.middlewareRecord[m];
339
418
  });
340
419
  }
341
420
  async usePipe(args, reflect) {
342
421
  return _RabbitMqContext.pipe.transform?.(args, reflect);
343
422
  }
423
+ static useFilter(arg, data) {
424
+ return _RabbitMqContext.filter(arg, data);
425
+ }
344
426
  useFilter(arg) {
345
427
  return _RabbitMqContext.filter(arg, this.data);
346
428
  }
@@ -359,6 +441,12 @@ function useMqFilter(filter) {
359
441
  }
360
442
  __name(useMqFilter, "useMqFilter");
361
443
 
444
+ // src/types.ts
445
+ var Base = class {
446
+ context;
447
+ };
448
+ __name(Base, "Base");
449
+
362
450
  // src/compiler.ts
363
451
  var Pcompiler = class {
364
452
  content = "";
@@ -375,28 +463,17 @@ var Pcompiler = class {
375
463
  }
376
464
  return content;
377
465
  }
378
- addMethod(className, methodName, route = "", requestType = "", params = []) {
466
+ addMethod(args) {
467
+ const { route: { route = "/", type = "get" } = {}, name, method, params, tag } = args;
379
468
  const url = route.replace(/\/\:([^\/]*)/g, "");
380
- if (!this.classMap[className])
381
- this.classMap[className] = {};
382
- this.classMap[className][methodName] = `
383
- ${methodName}(${genParams(params)}){
384
- const ret={tag:"${className}-${methodName}",body:{},query:{},params:{},realParam:'',method:"${requestType}",url:"${url}"}
469
+ if (!this.classMap[name])
470
+ this.classMap[name] = {};
471
+ this.classMap[name][method] = `
472
+ ${method}(${genParams(params)}){
473
+ const ret={tag:"${tag}-${method}",body:{},query:{},params:{},realParam:'',method:"${type}",url:"${url}"}
385
474
  ${params.filter((item) => item.key).reduce((p, c, i) => `${p}ret.${c.type}.${c.key}=arg${i}
386
475
  ${c.type === "params" ? `ret.realParam+='/'+arg${i}
387
476
  ` : ""}`, "")}
388
- return ret
389
- }
390
- `;
391
- }
392
- addMqMethod(className, methodName, exchange = "", routeKey = "", queue = "", params = []) {
393
- if (!this.classMap[className])
394
- this.classMap[className] = {};
395
- this.classMap[className][methodName] = `
396
- ${methodName}(${genParams(params)}){
397
- const ret={tag:"${className}-${methodName}",exchange:"${exchange}",routeKey:"${routeKey}",queue:"${queue}",args:{}}
398
- ${params.reduce((p, c, i) => `${p}ret.args.${c.key}=arg${i}
399
- `, "")}
400
477
  return ret
401
478
  }
402
479
  `;
@@ -404,10 +481,9 @@ return ret
404
481
  };
405
482
  __name(Pcompiler, "Pcompiler");
406
483
  function genParams(decorators) {
407
- let index = 0;
408
- return decorators.reduce((p) => {
409
- return `${`${p}arg${index++}`},`;
410
- }, "");
484
+ return decorators.map((_, i) => {
485
+ return `${`arg${i}`}`;
486
+ }).join(",");
411
487
  }
412
488
  __name(genParams, "genParams");
413
489
 
@@ -424,7 +500,7 @@ __name(resolveDep, "resolveDep");
424
500
 
425
501
  // src/common.ts
426
502
  var SERIES_SYMBOL = "__symbol_series__";
427
- var REQ_SYMBOL = "__symbol_req__";
503
+ var MERGE_SYMBOL = "__symbol_req__";
428
504
 
429
505
  // src/server/express.ts
430
506
  function bindApp(app, { meta, moduleMap }, options = {}) {
@@ -436,12 +512,14 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
436
512
  ...options
437
513
  };
438
514
  const methodMap = {};
515
+ const contextMeta = {};
439
516
  for (const i of meta) {
440
- const { name, method, route: route2, header } = i.data;
441
- const instance = moduleMap.get(name);
442
- const tag = `${name}-${method}`;
443
- Pcontext.metaRecord[tag] = i;
444
- let { guards, reflect, interceptors, params, middlewares } = Pcontext.metaDataRecord[tag] ? Pcontext.metaDataRecord[tag] : Pcontext.metaDataRecord[tag] = parseMeta(i);
517
+ const { name, method, route: route2, header, tag } = i.data;
518
+ const instance = moduleMap.get(tag);
519
+ const methodTag = `${tag}-${method}`;
520
+ contextMeta[methodTag] = i;
521
+ Pcontext.metaRecord[methodTag] = i;
522
+ let { guards, reflect, interceptors, params, middlewares } = Pcontext.metaDataRecord[methodTag] ? Pcontext.metaDataRecord[methodTag] : Pcontext.metaDataRecord[methodTag] = parseMeta(i);
445
523
  guards = [
446
524
  ...globalGuards,
447
525
  ...guards
@@ -451,16 +529,16 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
451
529
  ...interceptors
452
530
  ];
453
531
  const handler = instance[method].bind(instance);
454
- methodMap[tag] = handler;
532
+ methodMap[methodTag] = handler;
455
533
  Pcontext.instanceRecord[name] = instance;
456
534
  if (route2) {
457
535
  app[route2.type](route2.route, ...ServerContext.useMiddleware(middlewares), async (req, res) => {
458
536
  const contextData = {
459
537
  request: req,
460
- tag,
538
+ meta: i,
461
539
  response: res
462
540
  };
463
- const context = new ServerContext(tag, contextData);
541
+ const context = new ServerContext(methodTag, contextData);
464
542
  try {
465
543
  for (const name2 in header)
466
544
  res.set(name2, header[name2]);
@@ -472,7 +550,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
472
550
  validate
473
551
  };
474
552
  }), reflect);
475
- instance.meta = contextData;
553
+ instance.context = contextData;
476
554
  const ret = await context.usePost(await handler(...args));
477
555
  if (isObject(ret))
478
556
  res.json(ret);
@@ -487,16 +565,20 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
487
565
  }
488
566
  }
489
567
  app.post(route, (req, _res, next) => {
490
- req[REQ_SYMBOL] = true;
568
+ req[MERGE_SYMBOL] = true;
491
569
  next();
492
570
  }, ...ServerContext.useMiddleware(proMiddle), async (req, res) => {
571
+ const { body: { category, data } } = req;
493
572
  const contextData = {
494
573
  request: req,
495
- response: res
574
+ response: res,
575
+ meta: contextMeta
496
576
  };
577
+ if (!Array.isArray(data))
578
+ return res.json(await ServerContext.useFilter(new BadRequestException("data format should be an array"), contextData));
579
+ contextData.tags = data.map((item) => item.tag);
497
580
  const context = new ServerContext(route, contextData);
498
581
  const ret = [];
499
- const { body: { category, data } } = req;
500
582
  if (category === "series") {
501
583
  for (const item of data) {
502
584
  const { tag } = item;
@@ -505,7 +587,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
505
587
  const instance = moduleMap.get(name);
506
588
  try {
507
589
  if (!params)
508
- throw new NotFoundException(`"${tag}" doesn't exist`);
590
+ throw new BadRequestException(`"${tag}" doesn't exist`);
509
591
  await context.useGuard(guards, true);
510
592
  await context.useInterceptor(interceptors, true);
511
593
  const args = await context.usePipe(params.map(({ type, key, validate }) => {
@@ -522,7 +604,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
522
604
  validate
523
605
  };
524
606
  }), reflect);
525
- instance.meta = contextData;
607
+ instance.context = contextData;
526
608
  ret.push(await context.usePost(await methodMap[tag](...args)));
527
609
  } catch (e) {
528
610
  const m = Pcontext.metaRecord[tag];
@@ -541,7 +623,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
541
623
  const instance = moduleMap.get(name);
542
624
  try {
543
625
  if (!params)
544
- throw new NotFoundException(`"${tag}" doesn't exist`);
626
+ throw new BadRequestException(`"${tag}" doesn't exist`);
545
627
  await context.useGuard(guards, true);
546
628
  await context.useInterceptor(interceptors, true);
547
629
  const args = await context.usePipe(params.map(({ type, key, validate }) => {
@@ -551,7 +633,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
551
633
  validate
552
634
  };
553
635
  }), reflect);
554
- instance.meta = contextData;
636
+ instance.context = contextData;
555
637
  resolve(await context.usePost(await methodMap[tag](...args)));
556
638
  } catch (e) {
557
639
  const m = Pcontext.metaRecord[tag];
@@ -563,7 +645,7 @@ function bindApp(app, { meta, moduleMap }, options = {}) {
563
645
  res.json(ret2);
564
646
  });
565
647
  }
566
- res.json(await context.useFilter(new NotFoundException("category should be 'parallel' or 'series'")));
648
+ res.json(await context.useFilter(new BadRequestException("category should be 'parallel' or 'series'")));
567
649
  });
568
650
  }
569
651
  __name(bindApp, "bindApp");
@@ -604,35 +686,36 @@ async function Factory(Modules) {
604
686
  return {
605
687
  moduleMap,
606
688
  meta,
607
- output: (p) => import_fs.default.writeFileSync(p, JSON.stringify(meta.map((item) => item.data)))
689
+ output: (p = "pmeta.js") => import_fs.default.writeFileSync(p, JSON.stringify(meta.map((item) => item.data)))
608
690
  };
609
691
  }
610
692
  __name(Factory, "Factory");
611
693
  async function buildNestModule(Module, map, meta) {
612
694
  const paramtypes = getParamtypes(Module);
613
695
  let instance;
614
- const name = Module.prototype._namespace?.__TAG__ || Module.name;
615
- if (map.has(name)) {
616
- instance = map.get(name);
696
+ const tag = Module.prototype?.__TAG__ || Module.name;
697
+ if (map.has(tag)) {
698
+ instance = map.get(tag);
617
699
  if (!instance)
618
700
  throw new Error(`exist Circular Module dep--${Module}`);
619
701
  return instance;
620
702
  }
621
- map.set(name, void 0);
703
+ map.set(tag, void 0);
622
704
  if (paramtypes) {
705
+ const paramtypesInstances = [];
623
706
  for (const i in paramtypes)
624
- paramtypes[i] = await buildNestModule(paramtypes[i], map, meta);
625
- instance = new Module(...paramtypes);
707
+ paramtypesInstances[i] = await buildNestModule(paramtypes[i], map, meta);
708
+ instance = new Module(...paramtypesInstances);
626
709
  } else {
627
710
  instance = new Module();
628
711
  }
629
- meta.push(...getMetaFromInstance(instance, Module.name));
712
+ meta.push(...getMetaFromInstance(instance, Module.name, tag));
630
713
  await (0, import_phecda_core2.registerAsync)(instance);
631
- map.set(name, instance);
714
+ map.set(tag, instance);
632
715
  return instance;
633
716
  }
634
717
  __name(buildNestModule, "buildNestModule");
635
- function getMetaFromInstance(instance, name) {
718
+ function getMetaFromInstance(instance, name, tag) {
636
719
  const vars = (0, import_phecda_core2.getExposeKey)(instance).filter((item) => item !== "__CLASS");
637
720
  const baseState = (0, import_phecda_core2.getState)(instance, "__CLASS") || {};
638
721
  initState(baseState);
@@ -641,6 +724,7 @@ function getMetaFromInstance(instance, name) {
641
724
  if (baseState.route && state.route)
642
725
  state.route.route = baseState.route.route + state.route.route;
643
726
  state.name = name;
727
+ state.tag = tag;
644
728
  state.method = i;
645
729
  const params = [];
646
730
  for (const i2 of state.params || []) {
@@ -860,6 +944,17 @@ function Header(name, value) {
860
944
  };
861
945
  }
862
946
  __name(Header, "Header");
947
+ function Meta(key, value) {
948
+ return (target, k) => {
949
+ (0, import_phecda_core6.setModalVar)(target, k);
950
+ (0, import_phecda_core6.mergeState)(target, k, {
951
+ meta: {
952
+ [key]: value
953
+ }
954
+ });
955
+ };
956
+ }
957
+ __name(Meta, "Meta");
863
958
 
864
959
  // src/index.ts
865
960
  __reExport(src_exports, require("phecda-core"), module.exports);
@@ -1018,23 +1113,30 @@ __name(createMqReq, "createMqReq");
1018
1113
  // Annotate the CommonJS export names for ESM import in node:
1019
1114
  0 && (module.exports = {
1020
1115
  $S,
1116
+ BadGatewayException,
1021
1117
  BadRequestException,
1118
+ Base,
1022
1119
  BaseParam,
1023
1120
  Body,
1121
+ ConflictException,
1024
1122
  Controller,
1025
1123
  Delete,
1026
1124
  Factory,
1027
1125
  ForbiddenException,
1126
+ FrameworkException,
1028
1127
  Get,
1029
1128
  Guard,
1030
1129
  Header,
1031
1130
  HttpException,
1032
1131
  Inject,
1033
1132
  Interceptor,
1133
+ InvalidInputException,
1034
1134
  MQ,
1135
+ Meta,
1035
1136
  Middle,
1036
1137
  NotFoundException,
1037
1138
  Param,
1139
+ PayloadLargeException,
1038
1140
  Pcompiler,
1039
1141
  Pcontext,
1040
1142
  Pmeta,
@@ -1044,9 +1146,12 @@ __name(createMqReq, "createMqReq");
1044
1146
  RabbitMqContext,
1045
1147
  Route,
1046
1148
  ServerContext,
1149
+ ServiceUnavailableException,
1150
+ TimeoutException,
1151
+ UnauthorizedException,
1047
1152
  UndefinedException,
1153
+ UnsupportedMediaTypeException,
1048
1154
  ValidateException,
1049
- WrongMetaException,
1050
1155
  addGuard,
1051
1156
  addInterceptor,
1052
1157
  addMiddleware,