@nestia/sdk 1.3.3 → 1.3.5

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.
@@ -1,148 +1,156 @@
1
- import fs from "fs";
2
-
3
- import { INestiaConfig } from "../../INestiaConfig";
4
- import { IRoute } from "../../structures/IRoute";
5
- import { ImportDictionary } from "../../utils/ImportDictionary";
6
- import { SdkFunctionProgrammer } from "./SdkFunctionProgrammer";
7
- import { SdkRouteDirectory } from "./SdkRouteDirectory";
8
-
9
- export namespace SdkFileProgrammer {
10
- /* ---------------------------------------------------------
11
- CONSTRUCTOR
12
- --------------------------------------------------------- */
13
- export const generate =
14
- (config: INestiaConfig) =>
15
- async (routeList: IRoute[]): Promise<void> => {
16
- // CONSTRUCT FOLDER TREE
17
- const root: SdkRouteDirectory = new SdkRouteDirectory(
18
- null,
19
- "functional",
20
- );
21
- for (const route of routeList) emplace(root)(route);
22
-
23
- // RELOCATE FOR ONLY ONE CONTROLLER METHOD IN AN URL CASE
24
- relocate(root);
25
-
26
- // ITERATE FILES
27
- await iterate(config)(root)(config.output + "/functional");
28
- };
29
-
30
- const emplace =
31
- (directory: SdkRouteDirectory) =>
32
- (route: IRoute): void => {
33
- // SEPARATE IDENTIFIERS
34
- const identifiers: string[] = route.path
35
- .split("/")
36
- .filter((str) => str.length && str[0] !== ":")
37
- .map((str) => str.split("-").join("_").split(".").join("_"));
38
-
39
- // OPEN DIRECTORIES
40
- for (const key of identifiers) {
41
- directory = directory.directories.take(
42
- key,
43
- () => new SdkRouteDirectory(directory, key),
44
- );
45
- }
46
-
47
- // ADD ROUTE
48
- directory.routes.push(route);
49
- };
50
-
51
- const relocate = (directory: SdkRouteDirectory): void => {
52
- if (
53
- directory.parent !== null &&
54
- directory.directories.empty() &&
55
- directory.routes.length === 1 &&
56
- directory.name === directory.routes[0].name
57
- ) {
58
- directory.parent.routes.push(directory.routes[0]);
59
- directory.parent.directories.erase(directory.name);
60
- } else if (directory.directories.empty() === false)
61
- for (const it of directory.directories) relocate(it.second);
62
- };
63
-
64
- /* ---------------------------------------------------------
65
- FILE ITERATOR
66
- --------------------------------------------------------- */
67
- const iterate =
68
- (config: INestiaConfig) =>
69
- (directory: SdkRouteDirectory) =>
70
- async (outDir: string): Promise<void> => {
71
- // CREATE A NEW DIRECTORY
72
- try {
73
- await fs.promises.mkdir(outDir);
74
- } catch {}
75
-
76
- // ITERATE CHILDREN
77
- const content: string[] = [];
78
- for (const it of directory.directories) {
79
- await iterate(config)(it.second)(`${outDir}/${it.first}`);
80
- content.push(`export * as ${it.first} from "./${it.first}";`);
81
- }
82
- if (content.length && directory.routes.length) content.push("");
83
-
84
- // ITERATE ROUTES
85
- const importDict: ImportDictionary = new ImportDictionary();
86
- directory.routes.forEach((route, i) => {
87
- for (const tuple of route.imports)
88
- for (const instance of tuple[1])
89
- importDict.emplace(tuple[0], false, instance);
90
-
91
- content.push(SdkFunctionProgrammer.generate(config)(route));
92
- if (i !== directory.routes.length - 1) content.push("");
93
- });
94
-
95
- // FINALIZE THE CONTENT
96
- if (directory.routes.length !== 0) {
97
- const primitived: boolean =
98
- config.primitive !== false &&
99
- directory.routes.some(
100
- (route) =>
101
- route.output.name !== "void" ||
102
- route.parameters.some(
103
- (param) => param.category !== "param",
104
- ),
105
- );
106
- const asserted: boolean =
107
- config.assert === true &&
108
- directory.routes.some(
109
- (route) => route.parameters.length !== 0,
110
- );
111
- const json: boolean =
112
- config.json === true &&
113
- directory.routes.some(
114
- (route) =>
115
- route.method === "POST" ||
116
- route.method === "PUT" ||
117
- route.method === "PATCH",
118
- );
119
- const random: boolean =
120
- config.random === true &&
121
- directory.routes.some((s) => s.output.name !== "void");
122
-
123
- const fetcher: string[] = ["Fetcher"];
124
- if (primitived) fetcher.push("Primitive");
125
-
126
- const head: string[] = [
127
- `import { ${fetcher.join(", ")} } from "@nestia/fetcher";`,
128
- `import type { IConnection } from "@nestia/fetcher";`,
129
- ];
130
- if (asserted || json || random)
131
- head.push(`import typia from "typia";`);
132
- if (!importDict.empty())
133
- head.push("", importDict.toScript(outDir));
134
-
135
- content.push(...head, "", ...content.splice(0, content.length));
136
- }
137
-
138
- const script: string =
139
- "/**\n" +
140
- " * @packageDocumentation\n" +
141
- ` * @module ${directory.module}\n` +
142
- " * @nestia Generated by Nestia - https://github.com/samchon/nestia \n" +
143
- " */\n" +
144
- "//================================================================\n" +
145
- content.join("\n");
146
- await fs.promises.writeFile(`${outDir}/index.ts`, script, "utf8");
147
- };
148
- }
1
+ import fs from "fs";
2
+
3
+ import { INestiaConfig } from "../../INestiaConfig";
4
+ import { IRoute } from "../../structures/IRoute";
5
+ import { ImportDictionary } from "../../utils/ImportDictionary";
6
+ import { SdkFunctionProgrammer } from "./SdkFunctionProgrammer";
7
+ import { SdkRouteDirectory } from "./SdkRouteDirectory";
8
+
9
+ export namespace SdkFileProgrammer {
10
+ /* ---------------------------------------------------------
11
+ CONSTRUCTOR
12
+ --------------------------------------------------------- */
13
+ export const generate =
14
+ (config: INestiaConfig) =>
15
+ async (routeList: IRoute[]): Promise<void> => {
16
+ // CONSTRUCT FOLDER TREE
17
+ const root: SdkRouteDirectory = new SdkRouteDirectory(
18
+ null,
19
+ "functional",
20
+ );
21
+ for (const route of routeList) emplace(root)(route);
22
+
23
+ // RELOCATE FOR ONLY ONE CONTROLLER METHOD IN AN URL CASE
24
+ relocate(root);
25
+
26
+ // ITERATE FILES
27
+ await iterate(config)(root)(config.output + "/functional");
28
+ };
29
+
30
+ const emplace =
31
+ (directory: SdkRouteDirectory) =>
32
+ (route: IRoute): void => {
33
+ // SEPARATE IDENTIFIERS
34
+ const identifiers: string[] = route.path
35
+ .split("/")
36
+ .filter((str) => str.length && str[0] !== ":")
37
+ .map((str) => str.split("-").join("_").split(".").join("_"));
38
+
39
+ // OPEN DIRECTORIES
40
+ for (const key of identifiers) {
41
+ directory = directory.directories.take(
42
+ key,
43
+ () => new SdkRouteDirectory(directory, key),
44
+ );
45
+ }
46
+
47
+ // ADD ROUTE
48
+ directory.routes.push(route);
49
+ };
50
+
51
+ const relocate = (directory: SdkRouteDirectory): void => {
52
+ if (
53
+ directory.parent !== null &&
54
+ directory.directories.empty() &&
55
+ directory.routes.length === 1 &&
56
+ directory.name === directory.routes[0].name
57
+ ) {
58
+ directory.parent.routes.push(directory.routes[0]);
59
+ directory.parent.directories.erase(directory.name);
60
+ } else if (directory.directories.empty() === false)
61
+ for (const it of directory.directories) relocate(it.second);
62
+ };
63
+
64
+ /* ---------------------------------------------------------
65
+ FILE ITERATOR
66
+ --------------------------------------------------------- */
67
+ const iterate =
68
+ (config: INestiaConfig) =>
69
+ (directory: SdkRouteDirectory) =>
70
+ async (outDir: string): Promise<void> => {
71
+ // CREATE A NEW DIRECTORY
72
+ try {
73
+ await fs.promises.mkdir(outDir);
74
+ } catch {}
75
+
76
+ // ITERATE CHILDREN
77
+ const content: string[] = [];
78
+ for (const it of directory.directories) {
79
+ await iterate(config)(it.second)(`${outDir}/${it.first}`);
80
+ content.push(`export * as ${it.first} from "./${it.first}";`);
81
+ }
82
+ if (content.length && directory.routes.length) content.push("");
83
+
84
+ // ITERATE ROUTES
85
+ const importDict: ImportDictionary = new ImportDictionary();
86
+ directory.routes.forEach((route, i) => {
87
+ for (const tuple of route.imports)
88
+ for (const instance of tuple[1])
89
+ importDict.emplace(tuple[0], false, instance);
90
+
91
+ content.push(SdkFunctionProgrammer.generate(config)(route));
92
+ if (i !== directory.routes.length - 1) content.push("");
93
+ });
94
+
95
+ // FINALIZE THE CONTENT
96
+ if (directory.routes.length !== 0) {
97
+ const primitived: boolean =
98
+ config.primitive !== false &&
99
+ directory.routes.some(
100
+ (route) =>
101
+ route.output.name !== "void" ||
102
+ route.parameters.some(
103
+ (param) => param.category !== "param",
104
+ ),
105
+ );
106
+ const asserted: boolean =
107
+ config.assert === true &&
108
+ directory.routes.some(
109
+ (route) => route.parameters.length !== 0,
110
+ );
111
+ const json: boolean =
112
+ config.json === true &&
113
+ directory.routes.some(
114
+ (route) =>
115
+ route.method === "POST" ||
116
+ route.method === "PUT" ||
117
+ route.method === "PATCH",
118
+ );
119
+ const random: boolean =
120
+ config.random === true &&
121
+ directory.routes.some((s) => s.output.name !== "void");
122
+
123
+ const classes: string[] = ["Fetcher"];
124
+ const typings: string[] = ["IConnection"];
125
+ if (primitived) typings.push("Primitive");
126
+ if (
127
+ config.random &&
128
+ directory.routes.some((r) => !!r.parameters.length)
129
+ )
130
+ classes.push("HttpError");
131
+
132
+ const head: string[] = [
133
+ `import { ${classes.join(", ")} } from "@nestia/fetcher";`,
134
+ `import type { ${typings.join(
135
+ ", ",
136
+ )} } from "@nestia/fetcher";`,
137
+ ];
138
+ if (asserted || json || random || classes.length === 2)
139
+ head.push(`import typia from "typia";`);
140
+ if (!importDict.empty())
141
+ head.push("", importDict.toScript(outDir));
142
+
143
+ content.push(...head, "", ...content.splice(0, content.length));
144
+ }
145
+
146
+ const script: string =
147
+ "/**\n" +
148
+ " * @packageDocumentation\n" +
149
+ ` * @module ${directory.module}\n` +
150
+ " * @nestia Generated by Nestia - https://github.com/samchon/nestia \n" +
151
+ " */\n" +
152
+ "//================================================================\n" +
153
+ content.join("\n");
154
+ await fs.promises.writeFile(`${outDir}/index.ts`, script, "utf8");
155
+ };
156
+ }
@@ -4,6 +4,7 @@ import { Escaper } from "typia/lib/utils/Escaper";
4
4
 
5
5
  import { INestiaConfig } from "../../INestiaConfig";
6
6
  import { IRoute } from "../../structures/IRoute";
7
+ import { SdkSimulationProgrammer } from "./SdkSimulationProgrammer";
7
8
 
8
9
  export namespace SdkFunctionProgrammer {
9
10
  export const generate =
@@ -62,22 +63,29 @@ export namespace SdkFunctionProgrammer {
62
63
  // FUNCTION CALL STATEMENT
63
64
  const caller = (awa: boolean) => {
64
65
  const random = () =>
65
- route.output.name === "void"
66
- ? "undefined"
67
- : `typia.random<${route.name}.Output>()`;
66
+ [
67
+ `${route.name}.simulate(`,
68
+ ` connection,`,
69
+ ...route.parameters.map((p) => ` ${p.name},`),
70
+ `)`,
71
+ ]
72
+ .map((line, i) =>
73
+ i === 0 ? line : `${space(10)}${line}`,
74
+ )
75
+ .join("\n");
68
76
  const fetch = (tab: string) =>
69
77
  [
70
- `${awa ? "await " : ""} Fetcher.fetch(`,
78
+ `${awa ? "await " : ""}Fetcher.fetch(`,
71
79
  fetchArguments
72
- .map((param) => `${tab} ${param}`)
73
- .join(",\n"),
80
+ .map((param) => `${tab} ${param},`)
81
+ .join("\n"),
74
82
  `${tab})`,
75
83
  ].join("\n");
76
- if (!config.random) return fetch(" ".repeat(8));
84
+ if (!config.random) return fetch(space(4));
77
85
  return (
78
- `connection.random\n` +
86
+ `!!connection.random\n` +
79
87
  ` ? ${random()}\n` +
80
- ` : ${fetch(" ".repeat(10))}`
88
+ ` : ${fetch(space(10))}`
81
89
  );
82
90
  };
83
91
  if (route.setHeaders.length === 0)
@@ -185,9 +193,9 @@ export namespace SdkFunctionProgrammer {
185
193
  comments.map((str) => ` * ${str}`).join("\n") +
186
194
  "\n" +
187
195
  " */\n" +
188
- `export async function ${route.name} (\n` +
189
- `${parameters.map((str) => ` ${str}`).join(",\n")}\n` +
190
- ` ): Promise<${output}>`
196
+ `export async function ${route.name}(\n` +
197
+ parameters.map((str) => ` ${str},\n`).join("") +
198
+ `): Promise<${output}>`
191
199
  );
192
200
  };
193
201
 
@@ -244,11 +252,18 @@ export namespace SdkFunctionProgrammer {
244
252
  : "") +
245
253
  ` };\n` +
246
254
  "\n" +
247
- ` export function path(${parameters
255
+ ` export const path = (${parameters
248
256
  .map((param) => `${param.name}: ${param.type.name}`)
249
- .join(", ")}): string {\n` +
257
+ .join(", ")}): string => {\n` +
250
258
  `${path};\n` +
251
259
  ` }\n` +
260
+ (config.random && route.output.name !== "void"
261
+ ? ` export const random = (g?: Partial<typia.IRandomGenerator>): Output =>\n` +
262
+ ` typia.random<Output>(g);\n`
263
+ : "") +
264
+ (config.random
265
+ ? SdkSimulationProgrammer.generate(route) + "\n"
266
+ : "") +
252
267
  (config.json === true &&
253
268
  route.parameters.find((param) => param.category === "body") !==
254
269
  undefined
@@ -275,7 +290,7 @@ export namespace SdkFunctionProgrammer {
275
290
  (param) => param.category === "query" && param.field !== undefined,
276
291
  );
277
292
  if (props.query === undefined && queryParams.length === 0)
278
- return `${" ".repeat(8)}return \`${props.path}\``;
293
+ return `${space(8)}return \`${props.path}\``;
279
294
 
280
295
  const computeName = (str: string): string =>
281
296
  props.parameters.find((p) => p.name === str) !== undefined
@@ -298,7 +313,7 @@ export namespace SdkFunctionProgrammer {
298
313
  `const ${encoded}: string = ${search}.toString();`,
299
314
  `return \`${props.path}\${${encoded}.length ? \`?\${${encoded}}\` : ""}\`;`,
300
315
  ]
301
- .map((str) => `${" ".repeat(8)}${str}`)
316
+ .map((str) => `${space(8)}${str}`)
302
317
  .join("\n");
303
318
 
304
319
  if (props.query !== undefined && queryParams.length === 0)
@@ -327,5 +342,7 @@ export namespace SdkFunctionProgrammer {
327
342
  : JSON.stringify(param.field)
328
343
  }: ${param.name}`,
329
344
  )
330
- .join(`,\n${" ".repeat(12)}`);
345
+ .join(`,\n${space(12)}`);
331
346
  }
347
+
348
+ const space = (count: number) => " ".repeat(count);
@@ -0,0 +1,83 @@
1
+ import { IRoute } from "../../structures/IRoute";
2
+
3
+ export namespace SdkSimulationProgrammer {
4
+ export const generate = (route: IRoute): string => {
5
+ const output: boolean = route.output.name !== "void";
6
+ const returns = () => [
7
+ `return typia.random<Output>(`,
8
+ ` typeof connection.random === 'object'`,
9
+ ` && connection.random !== null`,
10
+ ` ? connection.random`,
11
+ ` : undefined`,
12
+ `);`,
13
+ ];
14
+ const body: string[] = [
15
+ ...(route.parameters.length !== 0 ? assert(route.parameters) : []),
16
+ ...route.parameters
17
+ .map((p) => [
18
+ `assert(`,
19
+ ` ${message(p)}`,
20
+ `)(() => typia.assert(${p.name}));`,
21
+ ])
22
+ .flat(),
23
+ ...(output ? returns() : []),
24
+ ];
25
+
26
+ return [
27
+ `export const simulate = async (`,
28
+ ` ${
29
+ route.parameters.length === 0 && route.output.name === "void"
30
+ ? "_connection"
31
+ : "connection"
32
+ }: IConnection,`,
33
+ ...route.parameters.map((p) => ` ${p.name}: ${p.type.name},`),
34
+ `): Promise<${output ? "Output" : "void"}> => {`,
35
+ ...body.map((l) => ` ${l}`),
36
+ `}`,
37
+ ]
38
+ .map((line) => ` ${line}`)
39
+ .join("\n");
40
+ };
41
+
42
+ const message = (p: IRoute.IParameter): string => {
43
+ if (p.category === "param")
44
+ return `() => "URL parameter \\"${p.name}\\" is not \${exp.expected} type."`;
45
+ else
46
+ return `() => "Request ${
47
+ p.category === "query" ? "query parameters are" : "body is"
48
+ } not following the promised type."`;
49
+ };
50
+
51
+ const assert = (parameters: IRoute.IParameter[]): string[] => {
52
+ return [
53
+ `const assert =`,
54
+ ` (message: (exp: typia.TypeGuardError) => string) =>`,
55
+ ` <T>(task: () => T): void => {`,
56
+ ` try {`,
57
+ ` task()`,
58
+ ` }`,
59
+ ` catch (exp) {`,
60
+ ` if (typia.is<typia.TypeGuardError>(exp))`,
61
+ ` throw new HttpError(`,
62
+ ` METHOD,`,
63
+ " `${connection.host}${path(" +
64
+ parameters
65
+ .filter((p) => p.category !== "body")
66
+ .map((p) => p.name)
67
+ .join(", ") +
68
+ ")}`,",
69
+ ` 400,`,
70
+ ` JSON.stringify({`,
71
+ ` method: exp.method,`,
72
+ ` path: exp.path,`,
73
+ ` expected: exp.expected,`,
74
+ ` value: exp.value,`,
75
+ ` message: message(exp),`,
76
+ ` })`,
77
+ ` );`,
78
+ ` throw exp`,
79
+ ` }`,
80
+ ` };`,
81
+ ];
82
+ };
83
+ }