@miqro/core 1.3.3 → 1.3.8

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.
Files changed (132) hide show
  1. package/README.md +81 -253
  2. package/dist/handler/api-router-utils.d.ts +11 -7
  3. package/dist/handler/api-router-utils.js +102 -15
  4. package/dist/handler/api-router-utils.js.map +1 -1
  5. package/dist/handler/api-router.d.ts +29 -2
  6. package/dist/handler/api-router.js +2 -2
  7. package/dist/handler/api-router.js.map +1 -1
  8. package/dist/handler/app.d.ts +4 -9
  9. package/dist/handler/app.js +10 -9
  10. package/dist/handler/app.js.map +1 -1
  11. package/dist/handler/common/context.d.ts +1 -1
  12. package/dist/handler/common/context.js +14 -9
  13. package/dist/handler/common/context.js.map +1 -1
  14. package/dist/handler/common/router-utils.d.ts +34 -1
  15. package/dist/handler/common/router-utils.js +139 -9
  16. package/dist/handler/common/router-utils.js.map +1 -1
  17. package/dist/handler/common/router.d.ts +19 -8
  18. package/dist/handler/common/router.js +32 -15
  19. package/dist/handler/common/router.js.map +1 -1
  20. package/dist/handler/index.d.ts +0 -3
  21. package/dist/handler/index.js +0 -3
  22. package/dist/handler/index.js.map +1 -1
  23. package/dist/handler/middleware/form.js +7 -1
  24. package/dist/handler/middleware/form.js.map +1 -1
  25. package/dist/handler/middleware/group.js +44 -2
  26. package/dist/handler/middleware/group.js.map +1 -1
  27. package/dist/handler/middleware/index.js +2 -6
  28. package/dist/handler/middleware/index.js.map +1 -1
  29. package/dist/handler/middleware/json.js +8 -2
  30. package/dist/handler/middleware/json.js.map +1 -1
  31. package/dist/handler/middleware/text.js +8 -1
  32. package/dist/handler/middleware/text.js.map +1 -1
  33. package/dist/handler/proxy.d.ts +2 -5
  34. package/dist/handler/proxy.js +2 -3
  35. package/dist/handler/proxy.js.map +1 -1
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.js +1 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/{util/test → test/common}/app.d.ts +2 -2
  40. package/dist/{util/test → test/common}/app.js +3 -2
  41. package/dist/test/common/app.js.map +1 -0
  42. package/dist/{util/test → test/common}/common.d.ts +0 -0
  43. package/dist/{util/test → test/common}/common.js +0 -0
  44. package/dist/test/common/common.js.map +1 -0
  45. package/dist/{util/test → test/common}/index.d.ts +1 -0
  46. package/dist/{util/test → test/common}/index.js +1 -0
  47. package/dist/test/common/index.js.map +1 -0
  48. package/dist/test/common/runner.d.ts +13 -0
  49. package/dist/test/common/runner.js +92 -0
  50. package/dist/test/common/runner.js.map +1 -0
  51. package/dist/test/index.d.ts +1 -0
  52. package/dist/{handler/response → test}/index.js +1 -3
  53. package/dist/test/index.js.map +1 -0
  54. package/dist/test/main.d.ts +1 -0
  55. package/dist/test/main.js +19 -0
  56. package/dist/test/main.js.map +1 -0
  57. package/dist/util/cli/index.d.ts +1 -1
  58. package/dist/util/cookie/cookie.d.ts +0 -1
  59. package/dist/util/error/parsererror.d.ts +2 -1
  60. package/dist/util/error/parsererror.js +5 -1
  61. package/dist/util/error/parsererror.js.map +1 -1
  62. package/dist/util/index.d.ts +0 -1
  63. package/dist/util/index.js +0 -1
  64. package/dist/util/index.js.map +1 -1
  65. package/dist/util/loader/index.d.ts +0 -3
  66. package/dist/util/loader/index.js +2 -9
  67. package/dist/util/loader/index.js.map +1 -1
  68. package/dist/util/parser/get.js +3 -6
  69. package/dist/util/parser/get.js.map +1 -1
  70. package/dist/util/request/common.d.ts +0 -1
  71. package/dist/util/request/index.d.ts +1 -1
  72. package/dist/util/request/index.js +1 -3
  73. package/dist/util/request/index.js.map +1 -1
  74. package/dist/util/session/common.d.ts +0 -1
  75. package/dist/util/session/common.js +0 -46
  76. package/dist/util/session/common.js.map +1 -1
  77. package/package.json +6 -12
  78. package/src/handler/api-router-utils.ts +108 -22
  79. package/src/handler/api-router.ts +30 -4
  80. package/src/handler/app.ts +10 -15
  81. package/src/handler/common/context.ts +14 -10
  82. package/src/handler/common/router-utils.ts +221 -49
  83. package/src/handler/common/router.ts +43 -15
  84. package/src/handler/index.ts +0 -3
  85. package/src/handler/middleware/form.ts +8 -2
  86. package/src/handler/middleware/group.ts +44 -2
  87. package/src/handler/middleware/index.ts +0 -4
  88. package/src/handler/middleware/json.ts +9 -3
  89. package/src/handler/middleware/text.ts +8 -1
  90. package/src/handler/proxy.ts +3 -8
  91. package/src/index.ts +1 -0
  92. package/src/{util/test → test/common}/app.ts +6 -5
  93. package/src/{util/test → test/common}/common.ts +0 -0
  94. package/src/{util/test → test/common}/index.ts +1 -0
  95. package/src/test/common/runner.ts +97 -0
  96. package/src/test/index.ts +1 -0
  97. package/src/test/main.ts +17 -0
  98. package/src/util/cli/index.ts +1 -1
  99. package/src/util/error/parsererror.ts +6 -1
  100. package/src/util/index.ts +0 -1
  101. package/src/util/loader/index.ts +1 -7
  102. package/src/util/parser/get.ts +3 -5
  103. package/src/util/request/index.ts +1 -1
  104. package/src/util/session/common.ts +0 -43
  105. package/tsconfig-test.json +13 -0
  106. package/tsconfig.json +2 -2
  107. package/dist/handler/api-handler.d.ts +0 -30
  108. package/dist/handler/api-handler.js +0 -42
  109. package/dist/handler/api-handler.js.map +0 -1
  110. package/dist/handler/feature-router.d.ts +0 -10
  111. package/dist/handler/feature-router.js +0 -90
  112. package/dist/handler/feature-router.js.map +0 -1
  113. package/dist/handler/response/html.d.ts +0 -10
  114. package/dist/handler/response/html.js +0 -34
  115. package/dist/handler/response/html.js.map +0 -1
  116. package/dist/handler/response/index.d.ts +0 -3
  117. package/dist/handler/response/index.js.map +0 -1
  118. package/dist/handler/response/json.d.ts +0 -2
  119. package/dist/handler/response/json.js +0 -21
  120. package/dist/handler/response/json.js.map +0 -1
  121. package/dist/handler/response/result.d.ts +0 -4
  122. package/dist/handler/response/result.js +0 -46
  123. package/dist/handler/response/result.js.map +0 -1
  124. package/dist/util/test/app.js.map +0 -1
  125. package/dist/util/test/common.js.map +0 -1
  126. package/dist/util/test/index.js.map +0 -1
  127. package/src/handler/api-handler.ts +0 -56
  128. package/src/handler/feature-router.ts +0 -90
  129. package/src/handler/response/html.ts +0 -36
  130. package/src/handler/response/index.ts +0 -3
  131. package/src/handler/response/json.ts +0 -19
  132. package/src/handler/response/result.ts +0 -40
@@ -1,67 +1,239 @@
1
1
  import { Router } from "./router";
2
2
  import { Context, Handler } from "./context";
3
3
  import { Method } from "./context";
4
- import { matchTokenizePath, PathPartToken, tokenizePath } from "./tokenize-match";
4
+ import { matchTokenizePath, PathPartToken, tokenizePath } from "./tokenize-match"
5
+ import { ParseRequest } from "../middleware/parse";
6
+ import { Parser, ParseOptions, parse } from "../../util/parser";
7
+ import { SessionHandler, SessionHandlerOptions } from "../middleware/session";
8
+ import { GroupPolicyHandler } from "../middleware/group";
9
+ import { GroupPolicy } from "../../util/session";
10
+
11
+ const ResultParser = (options: ParseOptions | ParseOptions[], parser?: Parser): Handler<any> =>
12
+ async (ctx: Context): Promise<any> => {
13
+ if (!ctx.results || ctx.results.length === 0) {
14
+ ctx.logger.debug(`not parsing results`);
15
+ return undefined;
16
+ } else {
17
+ const index = ctx.results.length - 1;
18
+ const lastResult = ctx.results[index];
19
+ ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
20
+ try {
21
+ if (options instanceof Array) {
22
+ for (let i = 0; i < options.length; i++) {
23
+ const o = options[i];
24
+ try {
25
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, o.options, o.mode, o.ignoreUndefined);
26
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
27
+ return mappedResults;
28
+ } catch (e) {
29
+ if (i === options.length - 1) {
30
+ throw e;
31
+ } else {
32
+ continue;
33
+ }
34
+ }
35
+ }
36
+ } else {
37
+ const mappedResults = (parser ? parser.parse : parse)(`ctx.results[${index}]`, lastResult, options.options, options.mode, options.ignoreUndefined);
38
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
39
+ return mappedResults;
40
+ }
41
+ } catch (e) {
42
+ ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
43
+ throw e;
44
+ }
45
+ }
46
+ };
47
+
48
+
49
+ const ResponseHandler = (): Handler<void> =>
50
+ async (ctx: Context): Promise<void> => {
51
+ ctx.logger.trace("results [%o]", ctx.results);
52
+ if (!ctx.results || ctx.results.length === 0) {
53
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
54
+ } else {
55
+ const lastResult = ctx.results[ctx.results.length - 1];
56
+ ctx.logger.debug("response [%o]", lastResult);
57
+ if (lastResult !== undefined) {
58
+ await ctx.json(lastResult);
59
+ } else {
60
+ throw new Error(`no response to send. Is your handler returning a value differente than boolean 'true|false' ?`);
61
+ }
62
+ }
63
+ };
64
+
65
+
66
+
67
+
68
+ export interface HandlerWithOptions extends RouterHandlerOptions {
69
+ handler: Handler | Array<Handler>;
70
+ }
71
+
72
+ export interface RouteOptions {
73
+ name?: string;
74
+ description?: string;
75
+ policy?: GroupPolicy;
76
+ request?: {
77
+ headers?: ParseOptions | ParseOptions[];
78
+ query?: ParseOptions | false | ParseOptions[];
79
+ params?: ParseOptions | false | ParseOptions[];
80
+ body?: ParseOptions | false | ParseOptions[];
81
+ };
82
+ response?: true | ParseOptions | ParseOptions[];
83
+ }
84
+
85
+ export interface RouteJSONDoc extends RouteOptions {
86
+ identifier: string;
87
+ }
88
+
89
+ export interface RouterJSONDoc {
90
+ [path: string]: {
91
+ [method: string]: RouteJSONDoc
92
+ }
93
+ }
94
+
95
+ export interface RouterHandlerOptions extends RouteOptions {
96
+ parser?: Parser;
97
+ middleware?: Handler | Handler[];
98
+ session?: SessionHandlerOptions | Handler;
99
+ }
5
100
 
6
101
  export class RouterHandler {
7
102
 
8
- private readonly tokens: PathPartToken[];
9
- private readonly handler: Array<Handler | Handler | Router>;
10
- private readonly isRouter: boolean;
103
+ private readonly tokens: PathPartToken[];
104
+ private readonly handler: Array<Handler | Handler | Router>;
105
+ private readonly isRouter: boolean;
106
+ private readonly options?: RouterHandlerOptions;
11
107
 
12
- public constructor(handler: Array<Handler> | Handler | Router, private readonly path: string | undefined, private readonly method: Method | undefined) {
13
- this.tokens = tokenizePath(path);
14
- this.handler = handler instanceof Array ? handler : [handler];
15
- this.isRouter = handler instanceof Router;
16
- if (!this.isRouter && this.handler.length !== this.handler.filter(h => typeof h === "function").length) {
17
- throw new Error("bad arguments handler must be an array of Handler or a Router");
18
- }
108
+ public constructor(handler: Array<Handler> | HandlerWithOptions | Handler | Router, private readonly path: string | undefined, private readonly method: Method | undefined, options?: RouterHandlerOptions) {
109
+ this.tokens = tokenizePath(path);
110
+
111
+ let handlers: Array<Handler | Router> = []
112
+ this.isRouter = handler instanceof Router;
113
+
114
+ if (!this.isRouter && !(handler instanceof Array) && typeof handler === "object") {
115
+ // HandlerWithOptions
116
+ if (options) {
117
+ throw new Error("bad arguments. cannot send options with HandlerWithOptions");
118
+ }
119
+ const realHandler = (handler as HandlerWithOptions).handler;
120
+ const newOptions = {
121
+ ...(handler as HandlerWithOptions)
122
+ };
123
+ delete (newOptions as any).handler;
124
+ handler = realHandler;
125
+ this.options = newOptions;
126
+ } else {
127
+ this.options = options;
19
128
  }
129
+ const routeHandlers = handler instanceof Array ? handler : [handler] as Array<Handler | Router>;
20
130
 
21
- public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
22
- for (let i = 0; i < this.handler.length; i++) {
23
- const h = this.handler[i];
24
- if (h instanceof Router) {
25
- if (!this.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
26
- return false;
27
- }
28
- } else {
29
- if (!this.pushResults(await h(ctx), ctx)) {
30
- return false;
31
- }
32
- }
33
- }
34
- return true;
131
+ if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
132
+ throw new Error("bad arguments");
35
133
  }
36
134
 
37
- public isMatch(
38
- method: string,
39
- pathTokens: { value: string; lower: string; }[],
40
- prePathTokens: PathPartToken[]): {
41
- match: boolean;
42
- params?: { [name: string]: string | undefined }
43
- } {
44
- if ((this.method === undefined || this.method === method)) {
45
- if (this.path === undefined) {
46
- return {
47
- match: true
48
- };
49
- }
50
- return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
135
+
136
+ if (this.options && this.options.middleware) {
137
+ handlers = handlers.concat(this.options.middleware);
138
+ }
139
+ if (this.options && this.options.session) {
140
+ handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
141
+ }
142
+ if (this.options && this.options.policy) {
143
+ handlers.push(GroupPolicyHandler(this.options.policy));
144
+ }
145
+ if (this.options && this.options.request) {
146
+ handlers.push(ParseRequest(this.options.request));
147
+ }
148
+
149
+ handlers = handlers.concat(routeHandlers);
150
+
151
+ if (this.options && this.options.response) {
152
+ if (typeof this.options.response === "boolean") {
153
+ (handlers as Handler[]).push(ResponseHandler());
154
+ } else {
155
+ (handlers as Handler[]).push(ResultParser(this.options.response, this.options.parser));
156
+ (handlers as Handler[]).push(ResponseHandler());
157
+ }
158
+ }
159
+ this.handler = handlers;
160
+ }
161
+
162
+ public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
163
+ const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
164
+ const nMethod = this.method ? this.method : "";
165
+
166
+ if (this.isRouter) {
167
+ const router: Router = this.handler[0] as Router;
168
+ router.getJSONDoc(doc, `${prePath}${nPath}`);
169
+ } else if (this.options) {
170
+ if (!doc[`${prePath}${nPath}`]) {
171
+ doc[`${prePath}${nPath}`] = {};
172
+ }
173
+ if (doc[`${prePath}${nPath}`][nMethod]) {
174
+ throw new Error("cannot create doc routes override each other");
175
+ }
176
+ doc[`${prePath}${nPath}`][nMethod] = {
177
+ description: this.options.description,
178
+ name: this.options.name,
179
+ identifier: `${prePath}${nPath}${this.options.name ? this.options.name : ""}${nMethod ? `_${nMethod}` : ""}`.replace(/[^a-z0-9+]+/gi, '_').split("_").map(s => s.trim()).filter(s => s).join("_").toUpperCase(),
180
+ policy: this.options.policy,
181
+ request: this.options.request ? {
182
+ body: this.options.request.body,
183
+ headers: this.options.request.headers,
184
+ params: this.options.request.params,
185
+ query: this.options.request.query,
186
+ } : undefined,
187
+ response: this.options.response
188
+ };
189
+ }
190
+ return doc;
191
+ }
192
+
193
+ public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
194
+ for (let i = 0; i < this.handler.length; i++) {
195
+ const h = this.handler[i];
196
+ if (h instanceof Router) {
197
+ if (!this.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
198
+ return false;
51
199
  }
200
+ } else {
201
+ if (!this.pushResults(await h(ctx), ctx)) {
202
+ return false;
203
+ }
204
+ }
205
+ }
206
+ return true;
207
+ }
208
+
209
+ public isMatch(
210
+ method: string,
211
+ pathTokens: { value: string; lower: string; }[],
212
+ prePathTokens: PathPartToken[]): {
213
+ match: boolean;
214
+ params?: { [name: string]: string | undefined }
215
+ } {
216
+ if ((this.method === undefined || this.method === method)) {
217
+ if (this.path === undefined) {
52
218
  return {
53
- match: false
219
+ match: true
54
220
  };
221
+ }
222
+ return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
55
223
  }
224
+ return {
225
+ match: false
226
+ };
227
+ }
56
228
 
57
- private pushResults(shouldContinue: boolean, ctx: Context): boolean {
58
- if (shouldContinue === false) {
59
- // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
60
- return false;
61
- } else if (shouldContinue !== true && shouldContinue !== undefined) {
62
- ctx.logger.trace("pushing to results [%o]", shouldContinue);
63
- ctx.results.push(shouldContinue);
64
- }
65
- return true;
229
+ private pushResults(result: boolean, ctx: Context): boolean {
230
+ if (result === false) {
231
+ // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
232
+ return false;
233
+ } else if (result !== true && result !== undefined) {
234
+ ctx.logger.trace("pushing to results [%o]", result);
235
+ ctx.results.push(result);
66
236
  }
237
+ return true;
238
+ }
67
239
  }
@@ -1,32 +1,54 @@
1
+ import { IncomingMessage, RequestListener, ServerResponse } from "http";
2
+ import { Logger } from "../../util/logger";
1
3
  import { Method, Handler, Context, ErrorHandler } from "./context";
2
- import { RouterHandler } from "./router-utils";
4
+ import { RouterHandler, RouterJSONDoc, RouterHandlerOptions, HandlerWithOptions } from "./router-utils";
3
5
  import { normalizePath, PathPartToken, splitPath } from "./tokenize-match";
4
6
 
7
+ export interface RouterOptions {
8
+ newRequestLogger?: (req: IncomingMessage) => Logger;
9
+ newContext?: (req: IncomingMessage, res: ServerResponse) => Context;
10
+ }
11
+
5
12
  export class Router {
6
13
  protected readonly handlers: RouterHandler[] = [];
7
14
  protected readonly errorHandlers: ErrorHandler[] = [];
8
- public get(path: string, handler: Array<Handler> | Handler | Router): Router {
9
- return this.use(handler, path, "get");
15
+ public readonly listener: RequestListener;
16
+ constructor(protected config?: RouterOptions) {
17
+ this.listener = async (req, res) => {
18
+ const ctx = this.config && this.config.newContext ?
19
+ this.config.newContext(req, res) :
20
+ new Context(
21
+ req,
22
+ res,
23
+ this.config && this.config.newRequestLogger ?
24
+ this.config.newRequestLogger(req) :
25
+ undefined);
26
+ ctx.logger.trace(`request received`);
27
+ await this.run(ctx);
28
+ };
29
+ }
30
+ public get(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
31
+ return this.use(handler, path, "get", options);
10
32
  }
11
- public post(path: string, handler: Array<Handler> | Handler | Router): Router {
12
- return this.use(handler, path, "post");
33
+ public post(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
34
+ return this.use(handler, path, "post", options);
13
35
  }
14
- public patch(path: string, handler: Array<Handler> | Handler | Router): Router {
15
- return this.use(handler, path, "patch");
36
+ public patch(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
37
+ return this.use(handler, path, "patch", options);
16
38
  }
17
- public delete(path: string, handler: Array<Handler> | Handler | Router): Router {
18
- return this.use(handler, path, "delete");
39
+ public delete(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
40
+ return this.use(handler, path, "delete", options);
19
41
  }
20
- public put(path: string, handler: Array<Handler> | Handler | Router): Router {
21
- return this.use(handler, path, "put");
42
+ public put(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
43
+ return this.use(handler, path, "put", options);
22
44
  }
23
- public options(path: string, handler: Array<Handler> | Handler | Router): Router {
24
- return this.use(handler, path, "options");
45
+ public options(path: string, handler: Array<Handler> | Handler | Router | HandlerWithOptions, options?: RouterHandlerOptions): Router {
46
+ return this.use(handler, path, "options", options);
25
47
  }
26
- public use(handler: Array<Handler> | Handler | Router, path?: string, method?: Method): Router {
48
+ public use(handler: Array<Handler> | HandlerWithOptions | Handler | Router, path?: string, method?: Method, options?: RouterHandlerOptions): Router {
27
49
  const nPath = path !== undefined ? normalizePath(path) : undefined;
28
50
  const nMethod = method ? method.toUpperCase() as Method : method;
29
- this.handlers.push(new RouterHandler(handler, nPath, nMethod));
51
+ this.handlers.push(new RouterHandler(handler, nPath, nMethod, options));
30
52
  return this;
31
53
  }
32
54
  public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
@@ -67,4 +89,10 @@ export class Router {
67
89
  throw e; // pass the error along
68
90
  }
69
91
  }
92
+ public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
93
+ for (const h of this.handlers) {
94
+ doc = h.getJSONDoc(doc, prePath);
95
+ }
96
+ return doc;
97
+ }
70
98
  }
@@ -1,8 +1,5 @@
1
1
  export * from "./app";
2
- export * from "./api-handler";
3
2
  export * from "./api-router";
4
- export * from "./response";
5
3
  export * from "./common";
6
- export * from "./feature-router";
7
4
  export * from "./proxy";
8
5
  export * from "./middleware";
@@ -2,7 +2,7 @@ import { parse as queryParse } from "querystring";
2
2
  import { Context, Handler } from "../common";
3
3
  import { BadRequestError } from "../../util/error";
4
4
  import { checkEnvVariables } from "../../util/config";
5
- import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
5
+ import { ReadBuffer, DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
6
6
 
7
7
  const DEFAULT_FORM_MAX_KEYS = undefined;
8
8
 
@@ -25,9 +25,15 @@ export const URLEncodedParser = (options?: {
25
25
  type = typeS;
26
26
  maxKeys = maxKeysS !== "undefined" ? parseInt(maxKeysS, 10) : DEFAULT_FORM_MAX_KEYS;
27
27
  }
28
+ const readBuffer = ReadBuffer({
29
+ limit
30
+ });
28
31
  return async (ctx: Context): Promise<void> => {
29
32
  try {
30
33
  const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
34
+ if(isType && !ctx.buffer) {
35
+ await readBuffer(ctx);
36
+ }
31
37
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
32
38
  const string = ctx.buffer.toString();
33
39
  if (string) {
@@ -42,7 +48,7 @@ export const URLEncodedParser = (options?: {
42
48
  throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
43
49
  }
44
50
  } catch (e: any) {
45
- if (e && e.name === "ParseOptionsError") {
51
+ if (e && e.name === "BadRequestError") {
46
52
  throw e;
47
53
  } else {
48
54
  ctx.logger.error(e);
@@ -1,7 +1,49 @@
1
- import { GroupPolicy, policyCheck } from "../../util/session";
2
- import { ForbiddenError, UnAuthorizedError } from "../../util/error";
1
+ import { GroupPolicy, Session } from "../../util/session";
2
+ import { ForbiddenError, UnAuthorizedError, ParseOptionsError } from "../../util/error";
3
3
  import { Context, Handler } from "../common";
4
4
 
5
+ const policyCheck = (session: Session, options: GroupPolicy): boolean => {
6
+ switch (options.groupPolicy) {
7
+ case "at_least_one":
8
+ for (const group of options.groups) {
9
+ if (group instanceof Array) {
10
+ let ret = true;
11
+ for (const g of group) {
12
+ if (session.groups.indexOf(g) === -1) {
13
+ ret = false;
14
+ break;
15
+ }
16
+ }
17
+ if (ret) {
18
+ return true;
19
+ }
20
+ } else {
21
+ if (session.groups.indexOf(group) !== -1) {
22
+ return true;
23
+ }
24
+ }
25
+ }
26
+ return false;
27
+ case "all":
28
+ for (const group of options.groups) {
29
+ if (group instanceof Array) {
30
+ for (const g of group) {
31
+ if (session.groups.indexOf(g) === -1) {
32
+ return false;
33
+ }
34
+ }
35
+ } else {
36
+ if (session.groups.indexOf(group) === -1) {
37
+ return false;
38
+ }
39
+ }
40
+ }
41
+ return true;
42
+ default:
43
+ throw new ParseOptionsError(`policy [${options.groupPolicy}] not implemented!!`);
44
+ }
45
+ };
46
+
5
47
  export const GroupPolicyHandler = (options: GroupPolicy): Handler<void> => {
6
48
  return async (ctx: Context): Promise<void> => {
7
49
  try {
@@ -5,7 +5,6 @@ import { LoggerHandler } from "./logger";
5
5
  import { TagResponse } from "./tag";
6
6
  import { CORS } from "./cors";
7
7
  import { CookieParser } from "./cookie";
8
- import { ReadBuffer } from "./buffer";
9
8
  import { JSONParser } from "./json";
10
9
  import { TextParser } from "./text";
11
10
  import { URLEncodedParser } from "./form";
@@ -33,9 +32,6 @@ export const middleware = (): Handler[] => {
33
32
  if (isFeatureEnabled("CORS", false)) {
34
33
  ret.push(CORS());
35
34
  }
36
- if (isFeatureEnabled("READ_BUFFER", true)) {
37
- ret.push(ReadBuffer());
38
- }
39
35
  if (isFeatureEnabled("COOKIE_PARSER", true)) {
40
36
  ret.push(CookieParser());
41
37
  }
@@ -1,7 +1,7 @@
1
1
  import { Context, Handler } from "../common";
2
2
  import { BadRequestError } from "../../util/error";
3
3
  import { checkEnvVariables } from "../../util/config";
4
- import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
4
+ import { DEFAULT_READ_BUFFER_LIMIT, ReadBuffer } from "./buffer";
5
5
 
6
6
  export const JSONParser = (options?: {
7
7
  limit?: number;
@@ -22,15 +22,21 @@ export const JSONParser = (options?: {
22
22
  limit = parseInt(limitS, 10);
23
23
  type = typeS;
24
24
  }
25
+ const readBuffer = ReadBuffer({
26
+ limit
27
+ });
25
28
  return async (ctx: Context): Promise<void> => {
26
29
  try {
27
30
  const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
31
+ if(isType && !ctx.buffer) {
32
+ await readBuffer(ctx);
33
+ }
28
34
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
29
35
  const string = ctx.buffer.toString();
30
36
  if (string) {
31
37
  const parsed = JSON.parse(string);
32
38
  if (parsed instanceof Array && strict) {
33
- throw new BadRequestError(`body cannot be an array`, 'body');
39
+ throw new BadRequestError(`body cannot be an array`);
34
40
  }
35
41
  ctx.body = parsed;
36
42
  }
@@ -39,7 +45,7 @@ export const JSONParser = (options?: {
39
45
  throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
40
46
  }
41
47
  } catch (e: any) {
42
- if (e && e.name === "ParseOptionsError") {
48
+ if (e && e.name === "BadRequestError") {
43
49
  throw e;
44
50
  } else {
45
51
  ctx.logger.error(e);
@@ -2,6 +2,7 @@ import { Context, Handler } from "../common";
2
2
  import { BadRequestError } from "../../util/error";
3
3
  import { checkEnvVariables } from "../../util/config";
4
4
  import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
5
+ import { ReadBuffer } from "./buffer";
5
6
 
6
7
  export const TextParser = (options?: {
7
8
  limit?: number;
@@ -18,9 +19,15 @@ export const TextParser = (options?: {
18
19
  limit = parseInt(limitS, 10);
19
20
  type = typeS;
20
21
  }
22
+ const readBuffer = ReadBuffer({
23
+ limit
24
+ });
21
25
  return async (ctx: Context): Promise<void> => {
22
26
  try {
23
27
  const isType = ctx.body === undefined && ctx.headers["content-type"] ? ctx.headers["content-type"].toLocaleLowerCase().indexOf(type.toLocaleLowerCase()) !== -1 : false;
28
+ if(isType && !ctx.buffer) {
29
+ await readBuffer(ctx);
30
+ }
24
31
  if (isType && ctx.buffer && ctx.buffer.length <= limit) {
25
32
  const string = ctx.buffer.toString();
26
33
  ctx.body = string;
@@ -29,7 +36,7 @@ export const TextParser = (options?: {
29
36
  throw new BadRequestError(`buffer.length ${ctx.buffer.length} > ${limit}`);
30
37
  }
31
38
  } catch (e: any) {
32
- if (e && e.name === "ParseOptionsError") {
39
+ if (e && e.name === "BadRequestError") {
33
40
  throw e;
34
41
  } else {
35
42
  ctx.logger.error(e);
@@ -2,17 +2,12 @@ import { request, RequestOptions, RequestResponse } from "../util/request";
2
2
  import { Context, Handler } from "./common";
3
3
 
4
4
  export interface ProxyServiceInterface {
5
- resolveRequest(ctx: Context): Promise<RequestOptions>;
5
+ resolve(ctx: Context): Promise<RequestOptions>;
6
6
  }
7
7
 
8
- export interface ProxyOptionsInterface {
9
- proxyService: ProxyServiceInterface;
10
- }
11
-
12
- export const ProxyHandler = (options: ProxyOptionsInterface): Handler<RequestResponse> =>
8
+ export const ProxyHandler = (resolver: ProxyServiceInterface): Handler<RequestResponse> =>
13
9
  async (ctx): Promise<RequestResponse> => {
14
- const resolver = options.proxyService;
15
- const requestConfig = await resolver.resolveRequest(ctx);
10
+ const requestConfig = await resolver.resolve(ctx);
16
11
  try {
17
12
  ctx.logger.debug("proxy resolveRequest to [%o]", requestConfig);
18
13
  const response = await request(requestConfig);
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from "./handler";
2
2
  export * from "./util";
3
+ export * from "./test";
@@ -1,17 +1,18 @@
1
- import { request, RequestOptions, RequestResponse, ResponseError } from "../request";
1
+ import { request, RequestOptions, RequestResponse } from "../../util/request";
2
2
  import { App } from "../../handler/app";
3
3
  import { existsSync, unlinkSync } from "fs";
4
4
  import { createServer } from "http";
5
5
 
6
- export const TestHelper = async (app: App, options: RequestOptions, cb?: (response: RequestResponse) => void): Promise<RequestResponse | void> => {
6
+ export const TestHelper = async (app: App, options: RequestOptions, cb?: (response: RequestResponse) => void): Promise<RequestResponse> => {
7
7
  const unixSocket = `/tmp/socket.test.helper${Date.now()}`;
8
8
  if (existsSync(unixSocket)) {
9
9
  unlinkSync(unixSocket);
10
10
  }
11
11
  const server = createServer(app.listener);
12
- return new Promise<RequestResponse | void>((resolve, reject) => {
12
+ return new Promise<RequestResponse>((resolve, reject) => {
13
13
  server.listen(unixSocket, () => {
14
14
  request({
15
+ disableThrow: true,
15
16
  ...options,
16
17
  socketPath: unixSocket
17
18
  }).then((response) => {
@@ -25,7 +26,7 @@ export const TestHelper = async (app: App, options: RequestOptions, cb?: (respon
25
26
  }
26
27
  resolve(response);
27
28
  });
28
- }).catch((e: ResponseError) => {
29
+ }).catch((e: any) => {
29
30
  server.close(() => {
30
31
  if (cb) {
31
32
  try {
@@ -33,7 +34,7 @@ export const TestHelper = async (app: App, options: RequestOptions, cb?: (respon
33
34
  } catch (ee) {
34
35
  reject(ee);
35
36
  }
36
- resolve();
37
+ resolve(undefined as any);
37
38
  } else {
38
39
  reject(e);
39
40
  }
File without changes
@@ -1,2 +1,3 @@
1
1
  export * from "./common";
2
2
  export * from "./app";
3
+ export * from "./runner";