@miqro/core 1.5.14 → 1.5.15

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 (38) hide show
  1. package/dist/api-router.d.ts +6 -5
  2. package/dist/api-router.js +9 -3
  3. package/dist/api-router.js.map +1 -1
  4. package/dist/common/api-router-utils.d.ts +1 -1
  5. package/dist/common/api-router-utils.js +4 -3
  6. package/dist/common/api-router-utils.js.map +1 -1
  7. package/dist/common/router-handler.d.ts +20 -0
  8. package/dist/common/router-handler.js +136 -0
  9. package/dist/common/router-handler.js.map +1 -0
  10. package/dist/common/router-utils.d.ts +7 -5
  11. package/dist/common/router-utils.js +37 -47
  12. package/dist/common/router-utils.js.map +1 -1
  13. package/dist/common/tokenize-match.d.ts +13 -20
  14. package/dist/common/tokenize-match.js +25 -57
  15. package/dist/common/tokenize-match.js.map +1 -1
  16. package/dist/middleware/group.js +2 -0
  17. package/dist/middleware/group.js.map +1 -1
  18. package/dist/middleware/index.d.ts +1 -0
  19. package/dist/middleware/index.js +1 -0
  20. package/dist/middleware/index.js.map +1 -1
  21. package/dist/middleware/result.d.ts +3 -0
  22. package/dist/middleware/result.js +51 -0
  23. package/dist/middleware/result.js.map +1 -0
  24. package/dist/router.d.ts +3 -30
  25. package/dist/router.js +2 -167
  26. package/dist/router.js.map +1 -1
  27. package/package.json +7 -5
  28. package/src/api-router.ts +16 -7
  29. package/src/api-router.unit.test.js +273 -0
  30. package/src/common/api-router-utils.ts +3 -3
  31. package/src/common/router-handler.ts +159 -0
  32. package/src/common/router-utils.ts +46 -44
  33. package/src/common/tokenize-match.ts +30 -52
  34. package/src/middleware/group.ts +2 -0
  35. package/src/middleware/index.ts +1 -0
  36. package/src/middleware/result.ts +43 -0
  37. package/src/router.ts +4 -196
  38. package/src/setup-test.js +3 -0
@@ -1,45 +1,16 @@
1
1
  import {URLSearchParams} from "url";
2
- import {newURLSearchParams} from "./helpers";
3
2
 
4
- export const parseSearchParams = (search: URLSearchParams): { [name: string]: string | string[] } => {
3
+ export function parseSearchParams(search: URLSearchParams): { [name: string]: string | string[] } {
5
4
  const query: { [name: string]: string | string[] } = {};
6
5
  search.forEach((value: string, key: string) => {
7
6
  query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
8
7
  });
9
8
  return query;
10
- };
11
-
12
- // appends query params to URLSearchParams and returns a copy
13
- export const mergeSearchParams = (search: URLSearchParams, append?: { [name: string]: string | string[] | number | boolean | number[] | boolean[] }): URLSearchParams => {
14
- const copy = newURLSearchParams(search.toString());
15
- if (!append) {
16
- return copy;
17
- }
18
- const keys = Object.keys(append);
19
- for (const k of keys) {
20
- if (append[k] instanceof Array) {
21
- for (const a of append[k] as Array<any>) {
22
- if (copy.has(k)) {
23
- copy.append(k, String(a));
24
- } else {
25
- copy.set(k, String(a));
26
- }
27
-
28
- }
29
- } else {
30
- if (copy.has(k)) {
31
- copy.append(k, String(append[k]));
32
- } else {
33
- copy.set(k, String(append[k]));
34
- }
35
- }
36
- }
37
- return copy;
38
- };
9
+ }
39
10
 
40
11
  // adds "/" to the final of path
41
12
  // cannot account for query or hash params so send only new URL().pathname
42
- export const normalizePath = (path: string): string => {
13
+ export function normalizePath(path: string): string {
43
14
  if (typeof path !== "string") {
44
15
  throw new Error("path not string");
45
16
  }
@@ -59,33 +30,40 @@ export const normalizePath = (path: string): string => {
59
30
  }
60
31
  }
61
32
 
62
- export interface PathPartToken {
33
+ export interface PathParams {
34
+ [name: string]: string | undefined
35
+ }
36
+
37
+ export interface PathPartToken extends PathPart {
63
38
  optional: boolean;
64
39
  wild?: string;
65
- token: string;
40
+ }
41
+
42
+ export interface PathPart {
43
+ value: string;
66
44
  lower: string;
67
45
  }
68
46
 
69
- export const pathPartTokenize = (token: { value: string; lower: string; }): PathPartToken => {
47
+ function pathPartTokenize(token: PathPart): PathPartToken {
70
48
  const isWild = token.value[0] === ":";
71
49
  const optional = token.value[token.value.length - 1] === "?";
72
50
  const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
73
51
  return {
74
52
  optional,
75
53
  wild,
76
- token: token.value,
54
+ value: token.value,
77
55
  lower: token.lower
78
56
  }
79
57
  }
80
58
 
81
- export const splitPath = (path?: string): { value: string; lower: string; }[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
59
+ export const splitPath = (path?: string): PathPart[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
82
60
  return {
83
61
  value: p,
84
62
  lower: p.toLocaleLowerCase()
85
63
  };
86
64
  });
87
65
 
88
- export const tokenizePath = (path?: string): PathPartToken[] => {
66
+ export function tokenizePath(path?: string): PathPartToken[] {
89
67
  if (path === undefined) {
90
68
  return [];
91
69
  }
@@ -98,36 +76,36 @@ export const tokenizePath = (path?: string): PathPartToken[] => {
98
76
  return tokens;
99
77
  }
100
78
 
101
- export const matchTokenizePath = (checkAsRouter: boolean, tokens: PathPartToken[], ctxTokens: { value: string; lower: string; }[]): {
79
+ export function matchTokenizePath(checkAsRouter: boolean, pathTokens: PathPartToken[], requestParts: PathPart[]): {
102
80
  match: boolean;
103
81
  params?: { [name: string]: string | undefined }
104
- } => {
105
- for (let i = 0; i < tokens.length; i++) {
106
- if (tokens[i].optional && i != tokens.length - 1) {
82
+ } {
83
+ for (let i = 0; i < pathTokens.length; i++) {
84
+ if (pathTokens[i].optional && i != pathTokens.length - 1) {
107
85
  throw new Error("cannot set a path token as optional that's not the last one");
108
86
  }
109
87
  }
110
- const lastTokenIsOptional = tokens.length > 0 ? tokens[tokens.length - 1].optional : false;
88
+ const lastTokenIsOptional = pathTokens.length > 0 ? pathTokens[pathTokens.length - 1].optional : false;
111
89
  const couldBeUsingOptional = (lastTokenIsOptional &&
112
90
  (
113
- (!checkAsRouter && tokens.length - 1 === ctxTokens.length) ||
114
- (checkAsRouter && tokens.length - 1 <= ctxTokens.length)
91
+ (!checkAsRouter && pathTokens.length - 1 === requestParts.length) ||
92
+ (checkAsRouter && pathTokens.length - 1 <= requestParts.length)
115
93
  )
116
94
  );
117
95
 
118
96
  const params: { [name: string]: string | undefined } = {};
119
97
 
120
- if ((!checkAsRouter && tokens.length === ctxTokens.length) || couldBeUsingOptional || (checkAsRouter && tokens.length <= ctxTokens.length)) {
121
- // similiar count of tokens
122
- for (let i = 0; i < ctxTokens.length; i++) {
123
- const ctxToken = ctxTokens[i];
124
- if (checkAsRouter && i >= tokens.length) {
98
+ if ((!checkAsRouter && pathTokens.length === requestParts.length) || couldBeUsingOptional || (checkAsRouter && pathTokens.length <= requestParts.length)) {
99
+ // similar count of tokens
100
+ for (let i = 0; i < requestParts.length; i++) {
101
+ const ctxToken = requestParts[i];
102
+ if (checkAsRouter && i >= pathTokens.length) {
125
103
  break;
126
104
  }
127
105
 
128
- if (tokens[i].wild || ctxToken.lower === tokens[i].lower) {
106
+ if (pathTokens[i].wild || ctxToken.lower === pathTokens[i].lower) {
129
107
  // check pass
130
- const wild = tokens[i].wild;
108
+ const wild = pathTokens[i].wild;
131
109
  if (wild) {
132
110
  params[wild] = ctxToken.value;
133
111
  }
@@ -1,4 +1,5 @@
1
1
  import {BadRequestError, Context, ForbiddenError, GroupPolicy, Handler, Session, UnAuthorizedError} from "../common";
2
+ import {parse} from "@miqro/parser";
2
3
 
3
4
  const policyCheck = (session: Session, options: GroupPolicy): boolean => {
4
5
  switch (options.groupPolicy) {
@@ -43,6 +44,7 @@ const policyCheck = (session: Session, options: GroupPolicy): boolean => {
43
44
  };
44
45
 
45
46
  export const GroupPolicyHandler = (options: GroupPolicy): Handler<void> => {
47
+ options = parse(options, "GroupPolicy", undefined, "options");
46
48
  return function GroupPolicyHandler(ctx: Context): void {
47
49
  try {
48
50
  if (!ctx.session) {
@@ -13,6 +13,7 @@ export * from "./json";
13
13
  export * from "./text";
14
14
  export * from "./form";
15
15
  export * from "./cors";
16
+ export * from "./result";
16
17
  export * from "./session";
17
18
  export * from "./group";
18
19
  export * from "./parse";
@@ -0,0 +1,43 @@
1
+ import {parse, ParseOptions, ParserInterface} from "@miqro/parser";
2
+ import {Context, Handler} from "../common/context";
3
+
4
+ export const ResultParser = (options: ParseOptions | ParseOptions[] | string, parser?: ParserInterface): Handler => {
5
+ options = parse(options, "ParseOptions[]!|string", undefined, "options");
6
+ return async function ResultParser(ctx: Context): Promise<any> {
7
+ if (!ctx.results || ctx.results.length === 0) {
8
+ ctx.logger.debug(`not parsing results`);
9
+ return undefined;
10
+ } else {
11
+ const index = ctx.results.length - 1;
12
+ const lastResult = ctx.results[index];
13
+ ctx.logger.trace(`parsing lastResult[%o]`, lastResult);
14
+ try {
15
+ if (options instanceof Array) {
16
+ for (let i = 0; i < options.length; i++) {
17
+ const o = options[i];
18
+ try {
19
+ const mappedResults = (parser ? parser : {parse}).parse(lastResult, o.options, o.mode, `ctx.results[${index}]`);
20
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
21
+ return mappedResults;
22
+ } catch (e) {
23
+ if (i === options.length - 1) {
24
+ throw e;
25
+ }
26
+ }
27
+ }
28
+ } else if (typeof options !== "string") {
29
+ const mappedResults = (parser ? parser : {parse}).parse(lastResult, options.options, options.mode, `ctx.results[${index}]`);
30
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
31
+ return mappedResults;
32
+ } else {
33
+ const mappedResults = (parser ? parser : {parse}).parse(lastResult, options, "no_extra", `ctx.results[${index}]`);
34
+ ctx.logger.trace(`ctx.results[%s] mapped to %o`, index, mappedResults);
35
+ return mappedResults;
36
+ }
37
+ } catch (e) {
38
+ ctx.logger.error(`error parsing lastResult[%o]`, lastResult);
39
+ throw e;
40
+ }
41
+ }
42
+ }
43
+ }
package/src/router.ts CHANGED
@@ -2,203 +2,11 @@ import {IncomingMessage, RequestListener} from "http";
2
2
  import {v4} from "uuid";
3
3
  import {Logger} from "./common/logger";
4
4
  import {Context, ErrorHandler, Handler, Method} from "./common/context";
5
- import {
6
- HandlerWithOptions,
7
- ResponseHandler,
8
- ResultParser,
9
- RouterHandlerOptions,
10
- RouterJSONDoc
11
- } from "./common/router-utils";
12
- import {matchTokenizePath, normalizePath, PathPartToken, splitPath, tokenizePath} from "./common/tokenize-match";
5
+ import {HandlerWithOptions, RouterHandlerOptions, RouterJSONDoc} from "./common/router-utils";
6
+ import {normalizePath, PathPart, PathPartToken, splitPath} from "./common/tokenize-match";
13
7
  import {defaultLoggerFactory} from "./common/router-helpers";
14
- import {GroupPolicyHandler, ParseRequest, SessionHandler} from "./middleware";
15
- import {parse, ParseOptionMap} from "@miqro/parser";
8
+ import {RouterHandler} from "./common/router-handler";
16
9
 
17
- const ROUTE_OPTIONS: ParseOptionMap = {
18
- name: "string?",
19
- description: "string?",
20
- policy: "GroupPolicy?",
21
- response: {
22
- type: "nested?",
23
- nestedOptions: {
24
- options: {
25
- body: "boolean?|ParseOptions[]!?|string?"
26
- },
27
- mode: "no_extra"
28
- }
29
- },
30
- request: {
31
- type: "nested?",
32
- nestedOptions: {
33
- options: {
34
- headers: "ParseOptions[]!?",
35
- query: "boolean?|ParseOptions[]!?|string?",
36
- params: "boolean?|ParseOptions[]!?|string?",
37
- body: "boolean?|ParseOptions[]!?|string?"
38
- },
39
- mode: "no_extra"
40
- }
41
- }
42
- };
43
-
44
- class RouterHandler {
45
-
46
- private readonly tokens: PathPartToken[];
47
- private readonly handler: Array<Handler | Router>;
48
- private readonly isRouter: boolean;
49
- private readonly options?: RouterHandlerOptions;
50
-
51
- public constructor(
52
- handler: Array<Handler> | HandlerWithOptions | Handler | Router,
53
- private readonly path: string | undefined,
54
- private readonly method: Method | undefined,
55
- options?: RouterHandlerOptions) {
56
- this.tokens = tokenizePath(path);
57
-
58
- if (options) {
59
- options = parse(options, {
60
- parser: "ParserInterface?",
61
- middleware: "function[]!?",
62
- session: "SessionHandlerOptions?|function?",
63
- ...ROUTE_OPTIONS
64
- }, "no_extra", "options");
65
- }
66
-
67
- let handlers: Array<Handler | Router> = []
68
- this.isRouter = handler instanceof Router;
69
-
70
- if (!this.isRouter && !(handler instanceof Array) && typeof handler === "object") {
71
- // HandlerWithOptions
72
- if (options) {
73
- throw new Error("bad arguments. cannot send options with HandlerWithOptions");
74
- }
75
- handler = parse(handler, {
76
- handler: "function[]!",
77
- parser: "ParserInterface?",
78
- middleware: "function[]!?",
79
- session: "SessionHandlerOptions?|function?",
80
- ...ROUTE_OPTIONS
81
- }, "no_extra", "handler");
82
- const realHandler = (handler as HandlerWithOptions).handler;
83
- const newOptions = {
84
- ...(handler as HandlerWithOptions)
85
- };
86
- delete (newOptions as any).handler;
87
- handler = realHandler;
88
- this.options = newOptions;
89
- } else {
90
- this.options = options;
91
- }
92
- const routeHandlers = handler instanceof Array ? handler : [handler] as Array<Handler | Router>;
93
-
94
- if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && this.options)) {
95
- throw new Error("bad arguments");
96
- }
97
-
98
- if (this.options && this.options.middleware) {
99
- handlers = handlers.concat(this.options.middleware);
100
- }
101
- if (this.options && this.options.session) {
102
- handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
103
- }
104
- if (this.options && this.options.policy) {
105
- handlers.push(GroupPolicyHandler(this.options.policy));
106
- }
107
- if (this.options && this.options.request) {
108
- handlers.push(ParseRequest(this.options.request, this.options.parser));
109
- }
110
-
111
- handlers = handlers.concat(routeHandlers);
112
-
113
- if (this.options && this.options.response) {
114
- if (typeof this.options.response.body === "boolean" && this.options.response.body) {
115
- (handlers as Handler[]).push(ResponseHandler());
116
- } else if (this.options.response.body) {
117
- (handlers as Handler[]).push(ResultParser(this.options.response.body, this.options.parser));
118
- (handlers as Handler[]).push(ResponseHandler());
119
- }
120
- }
121
- this.handler = handlers;
122
- }
123
-
124
- public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
125
- const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
126
- const nMethod = this.method ? this.method : "";
127
-
128
- if (this.isRouter) {
129
- const router: Router = this.handler[0] as Router;
130
- router.getJSONDoc(doc, `${prePath}${nPath}`);
131
- } else if (this.options) {
132
- if (!doc[`${prePath}${nPath}`]) {
133
- doc[`${prePath}${nPath}`] = {};
134
- }
135
- if (doc[`${prePath}${nPath}`][nMethod]) {
136
- throw new Error("cannot create doc routes override each other");
137
- }
138
- doc[`${prePath}${nPath}`][nMethod] = {
139
- description: this.options.description,
140
- name: this.options.name,
141
- 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(),
142
- policy: this.options.policy,
143
- request: this.options.request ? {
144
- body: this.options.request.body,
145
- headers: this.options.request.headers,
146
- params: this.options.request.params,
147
- query: this.options.request.query,
148
- } : undefined,
149
- response: this.options.response
150
- };
151
- }
152
- return doc;
153
- }
154
-
155
- public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
156
- for (let i = 0; i < this.handler.length; i++) {
157
- const h = this.handler[i];
158
- if (h instanceof Router) {
159
- if (!RouterHandler.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
160
- return false;
161
- }
162
- } else {
163
- if (!RouterHandler.pushResults(await h(ctx), ctx)) {
164
- return false;
165
- }
166
- }
167
- }
168
- return true;
169
- }
170
-
171
- public isMatch(
172
- method: string,
173
- pathTokens: { value: string; lower: string; }[],
174
- prePathTokens: PathPartToken[]): {
175
- match: boolean;
176
- params?: { [name: string]: string | undefined }
177
- } {
178
- if ((this.method === undefined || this.method === method)) {
179
- if (this.path === undefined) {
180
- return {
181
- match: true
182
- };
183
- }
184
- return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
185
- }
186
- return {
187
- match: false
188
- };
189
- }
190
-
191
- private static pushResults(result: any, ctx: Context): boolean {
192
- if (result === false) {
193
- // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
194
- return false;
195
- } else if (result !== true && result !== undefined) {
196
- ctx.logger.trace("pushing to results [%o]", result);
197
- ctx.results.push(result);
198
- }
199
- return true;
200
- }
201
- }
202
10
 
203
11
  export interface RouterOptions {
204
12
  loggerFactory?: (uuid: string, req: IncomingMessage) => Logger;
@@ -259,7 +67,7 @@ export class Router {
259
67
  return this;
260
68
  }
261
69
 
262
- public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
70
+ public async run(ctx: Context, pathTokens?: PathPart[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
263
71
  pathTokens = pathTokens ? pathTokens : splitPath(ctx.path);
264
72
  try {
265
73
  for (const h of this.handlers) {
@@ -0,0 +1,3 @@
1
+ const {resolve} = require("path");
2
+
3
+ module.exports.distPath = resolve(__dirname, "..", "dist");