@nestia/core 2.1.8 → 2.2.0-dev.20231010

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 (43) hide show
  1. package/lib/decorators/TypedQuery.d.ts +59 -0
  2. package/lib/decorators/TypedQuery.js +220 -0
  3. package/lib/decorators/TypedQuery.js.map +1 -1
  4. package/lib/decorators/internal/get_path_and_querify.d.ts +1 -0
  5. package/lib/decorators/internal/get_path_and_querify.js +164 -0
  6. package/lib/decorators/internal/get_path_and_querify.js.map +1 -0
  7. package/lib/options/IResponseBodyQuerifier.d.ts +20 -0
  8. package/lib/options/IResponseBodyQuerifier.js +3 -0
  9. package/lib/options/IResponseBodyQuerifier.js.map +1 -0
  10. package/lib/programmers/TypedQueryBodyProgrammer.d.ts +5 -0
  11. package/lib/programmers/TypedQueryBodyProgrammer.js +51 -0
  12. package/lib/programmers/TypedQueryBodyProgrammer.js.map +1 -0
  13. package/lib/programmers/TypedQueryRouteProgrammer.d.ts +5 -0
  14. package/lib/programmers/TypedQueryRouteProgrammer.js +50 -0
  15. package/lib/programmers/TypedQueryRouteProgrammer.js.map +1 -0
  16. package/lib/programmers/http/HttpAssertQuerifyProgrammer.d.ts +5 -0
  17. package/lib/programmers/http/HttpAssertQuerifyProgrammer.js +39 -0
  18. package/lib/programmers/http/HttpAssertQuerifyProgrammer.js.map +1 -0
  19. package/lib/programmers/http/HttpIsQuerifyProgrammer.d.ts +5 -0
  20. package/lib/programmers/http/HttpIsQuerifyProgrammer.js +37 -0
  21. package/lib/programmers/http/HttpIsQuerifyProgrammer.js.map +1 -0
  22. package/lib/programmers/http/HttpQuerifyProgrammer.d.ts +5 -0
  23. package/lib/programmers/http/HttpQuerifyProgrammer.js +80 -0
  24. package/lib/programmers/http/HttpQuerifyProgrammer.js.map +1 -0
  25. package/lib/programmers/http/HttpValidateQuerifyProgrammer.d.ts +5 -0
  26. package/lib/programmers/http/HttpValidateQuerifyProgrammer.js +38 -0
  27. package/lib/programmers/http/HttpValidateQuerifyProgrammer.js.map +1 -0
  28. package/lib/transformers/ParameterDecoratorTransformer.js +21 -1
  29. package/lib/transformers/ParameterDecoratorTransformer.js.map +1 -1
  30. package/lib/transformers/TypedRouteTransformer.js +13 -6
  31. package/lib/transformers/TypedRouteTransformer.js.map +1 -1
  32. package/package.json +13 -13
  33. package/src/decorators/TypedQuery.ts +197 -1
  34. package/src/decorators/internal/get_path_and_querify.ts +104 -0
  35. package/src/options/IResponseBodyQuerifier.ts +25 -0
  36. package/src/programmers/TypedQueryBodyProgrammer.ts +52 -0
  37. package/src/programmers/TypedQueryRouteProgrammer.ts +55 -0
  38. package/src/programmers/http/HttpAssertQuerifyProgrammer.ts +59 -0
  39. package/src/programmers/http/HttpIsQuerifyProgrammer.ts +63 -0
  40. package/src/programmers/http/HttpQuerifyProgrammer.ts +105 -0
  41. package/src/programmers/http/HttpValidateQuerifyProgrammer.ts +64 -0
  42. package/src/transformers/ParameterDecoratorTransformer.ts +23 -1
  43. package/src/transformers/TypedRouteTransformer.ts +15 -8
@@ -1,10 +1,28 @@
1
- import { ExecutionContext, createParamDecorator } from "@nestjs/common";
1
+ import {
2
+ BadRequestException,
3
+ CallHandler,
4
+ Delete,
5
+ ExecutionContext,
6
+ Get,
7
+ NestInterceptor,
8
+ Patch,
9
+ Post,
10
+ Put,
11
+ UseInterceptors,
12
+ applyDecorators,
13
+ createParamDecorator,
14
+ } from "@nestjs/common";
15
+ import { HttpArgumentsHost } from "@nestjs/common/interfaces";
2
16
  import type express from "express";
3
17
  import type { FastifyRequest } from "fastify";
18
+ import { catchError, map } from "rxjs";
4
19
 
5
20
  import typia from "typia";
6
21
 
7
22
  import { IRequestQueryValidator } from "../options/IRequestQueryValidator";
23
+ import { IResponseBodyQuerifier } from "../options/IResponseBodyQuerifier";
24
+ import { get_path_and_querify } from "./internal/get_path_and_querify";
25
+ import { route_error } from "./internal/route_error";
8
26
  import { validate_request_query } from "./internal/validate_request_query";
9
27
 
10
28
  /**
@@ -44,6 +62,111 @@ export function TypedQuery<T extends object>(
44
62
  return output;
45
63
  })();
46
64
  }
65
+ export namespace TypedQuery {
66
+ export function Body<T extends object>(
67
+ validator?: IRequestQueryValidator<T>,
68
+ ): ParameterDecorator {
69
+ const checker = validate_request_query(validator);
70
+ return createParamDecorator(function TypedQueryBody(
71
+ _unknown: any,
72
+ context: ExecutionContext,
73
+ ) {
74
+ const request: express.Request | FastifyRequest = context
75
+ .switchToHttp()
76
+ .getRequest();
77
+ if (isApplicationQuery(request.headers["content-type"]) === false)
78
+ throw new BadRequestException(
79
+ `Request body type is not "application/x-www-form-urlencoded".`,
80
+ );
81
+ const params: URLSearchParams =
82
+ request.body instanceof URLSearchParams
83
+ ? request.body
84
+ : (new FakeURLSearchParams(request.body) as any);
85
+
86
+ const output: T | Error = checker(params);
87
+ if (output instanceof Error) throw output;
88
+ return output;
89
+ })();
90
+ }
91
+ Object.assign(Body, typia.http.assertQuery);
92
+ Object.assign(Body, typia.http.isQuery);
93
+ Object.assign(Body, typia.http.validateQuery);
94
+
95
+ /**
96
+ * Router decorator function for the GET method.
97
+ *
98
+ * @param path Path of the HTTP request
99
+ * @returns Method decorator
100
+ */
101
+ export const Get = Generator("Get");
102
+
103
+ /**
104
+ * Router decorator function for the POST method.
105
+ *
106
+ * @param path Path of the HTTP request
107
+ * @returns Method decorator
108
+ */
109
+ export const Post = Generator("Post");
110
+
111
+ /**
112
+ * Router decorator function for the PATH method.
113
+ *
114
+ * @param path Path of the HTTP request
115
+ * @returns Method decorator
116
+ */
117
+ export const Patch = Generator("Patch");
118
+
119
+ /**
120
+ * Router decorator function for the PUT method.
121
+ *
122
+ * @param path Path of the HTTP request
123
+ * @returns Method decorator
124
+ */
125
+ export const Put = Generator("Put");
126
+
127
+ /**
128
+ * Router decorator function for the DELETE method.
129
+ *
130
+ * @param path Path of the HTTP request
131
+ * @returns Method decorator
132
+ */
133
+ export const Delete = Generator("Delete");
134
+
135
+ /**
136
+ * @internal
137
+ */
138
+ function Generator(method: "Get" | "Post" | "Put" | "Patch" | "Delete") {
139
+ function route(path?: string | string[]): MethodDecorator;
140
+ function route<T>(
141
+ stringify?: IResponseBodyQuerifier<T>,
142
+ ): MethodDecorator;
143
+ function route<T>(
144
+ path: string | string[],
145
+ stringify?: IResponseBodyQuerifier<T>,
146
+ ): MethodDecorator;
147
+
148
+ function route(...args: any[]): MethodDecorator {
149
+ const [path, stringify] = get_path_and_querify(
150
+ `TypedQuery.${method}`,
151
+ )(...args);
152
+ return applyDecorators(
153
+ ROUTERS[method](path),
154
+ UseInterceptors(new TypedQueryRouteInterceptor(stringify)),
155
+ );
156
+ }
157
+ return route;
158
+ }
159
+ for (const method of [typia.assert, typia.is, typia.validate])
160
+ for (const [key, value] of Object.entries(method))
161
+ for (const deco of [
162
+ TypedQuery.Get,
163
+ TypedQuery.Delete,
164
+ TypedQuery.Post,
165
+ TypedQuery.Put,
166
+ TypedQuery.Patch,
167
+ ])
168
+ (deco as any)[key] = value;
169
+ }
47
170
  Object.assign(TypedQuery, typia.http.assertQuery);
48
171
  Object.assign(TypedQuery, typia.http.isQuery);
49
172
  Object.assign(TypedQuery, typia.http.validateQuery);
@@ -55,3 +178,76 @@ function tail(url: string): string {
55
178
  const index: number = url.indexOf("?");
56
179
  return index === -1 ? "" : url.substring(index + 1);
57
180
  }
181
+
182
+ /**
183
+ * @internal
184
+ */
185
+ function isApplicationQuery(text?: string): boolean {
186
+ return (
187
+ text !== undefined &&
188
+ text
189
+ .split(";")
190
+ .map((str) => str.trim())
191
+ .some((str) => str === "application/x-www-form-urlencoded")
192
+ );
193
+ }
194
+
195
+ /**
196
+ * @internal
197
+ */
198
+ class FakeURLSearchParams {
199
+ public constructor(private readonly target: Record<string, string[]>) {}
200
+
201
+ public has(key: string): boolean {
202
+ return this.target[key] !== undefined;
203
+ }
204
+
205
+ public get(key: string): string | null {
206
+ const value = this.target[key];
207
+ return value === undefined
208
+ ? null
209
+ : Array.isArray(value)
210
+ ? value[0] ?? null
211
+ : value;
212
+ }
213
+
214
+ public getAll(key: string): string[] {
215
+ const value = this.target[key];
216
+ return value === undefined
217
+ ? []
218
+ : Array.isArray(value)
219
+ ? value
220
+ : [value];
221
+ }
222
+ }
223
+
224
+ /**
225
+ * @internal
226
+ */
227
+ class TypedQueryRouteInterceptor implements NestInterceptor {
228
+ public constructor(
229
+ private readonly toSearchParams: (input: any) => URLSearchParams,
230
+ ) {}
231
+
232
+ public intercept(context: ExecutionContext, next: CallHandler) {
233
+ const http: HttpArgumentsHost = context.switchToHttp();
234
+ const response: express.Response = http.getResponse();
235
+ response.header("Content-Type", "application/x-www-form-urlencoded");
236
+
237
+ return next.handle().pipe(
238
+ map((value) => this.toSearchParams(value).toString()),
239
+ catchError((err) => route_error(http.getRequest(), err)),
240
+ );
241
+ }
242
+ }
243
+
244
+ /**
245
+ * @internal
246
+ */
247
+ const ROUTERS = {
248
+ Get,
249
+ Post,
250
+ Patch,
251
+ Put,
252
+ Delete,
253
+ };
@@ -0,0 +1,104 @@
1
+ import { InternalServerErrorException } from "@nestjs/common";
2
+
3
+ import typia, { IValidation, TypeGuardError } from "typia";
4
+
5
+ import { IResponseBodyQuerifier } from "../../options/IResponseBodyQuerifier";
6
+ import { NoTransformConfigureError } from "./NoTransformConfigureError";
7
+
8
+ /**
9
+ * @internal
10
+ */
11
+ export const get_path_and_querify =
12
+ (method: string) =>
13
+ (
14
+ ...args: any[]
15
+ ): [string | string[] | undefined, (input: any) => URLSearchParams] => {
16
+ const path: string | string[] | null | undefined =
17
+ args[0] === undefined ||
18
+ typeof args[0] === "string" ||
19
+ Array.isArray(args[0])
20
+ ? args[0]
21
+ : null;
22
+ const functor: IResponseBodyQuerifier<any> | undefined =
23
+ path === null ? args[0] : args[1];
24
+ return [path ?? undefined, take(method)(functor)];
25
+ };
26
+
27
+ /**
28
+ * @internal
29
+ */
30
+ const take =
31
+ (method: string) =>
32
+ <T>(functor?: IResponseBodyQuerifier<T> | null) => {
33
+ if (functor === undefined) throw NoTransformConfigureError(method);
34
+ else if (functor === null) return querify;
35
+ else if (functor.type === "stringify") return functor.stringify;
36
+ else if (functor.type === "assert") return assert(functor.assert);
37
+ else if (functor.type === "is") return is(functor.is);
38
+ else if (functor.type === "validate") return validate(functor.validate);
39
+ throw new Error(
40
+ `Error on nestia.core.${method}(): invalid typed stringify function.`,
41
+ );
42
+ };
43
+
44
+ const querify = (input: Record<string, any>): URLSearchParams => {
45
+ const output: URLSearchParams = new URLSearchParams();
46
+ for (const [key, value] of Object.entries(input))
47
+ if (key === undefined) continue;
48
+ else if (Array.isArray(value))
49
+ for (const elem of value) output.append(key, String(elem));
50
+ else output.append(key, String(value));
51
+ return output;
52
+ };
53
+
54
+ /**
55
+ * @internal
56
+ */
57
+ const assert =
58
+ <T>(closure: (data: T) => URLSearchParams) =>
59
+ (data: T) => {
60
+ try {
61
+ return closure(data);
62
+ } catch (exp) {
63
+ if (typia.is<TypeGuardError>(exp))
64
+ throw new InternalServerErrorException({
65
+ path: exp.path,
66
+ reason: exp.message,
67
+ expected: exp.expected,
68
+ value: exp.value,
69
+ message: MESSAGE,
70
+ });
71
+ throw exp;
72
+ }
73
+ };
74
+
75
+ /**
76
+ * @internal
77
+ */
78
+ const is =
79
+ <T>(closure: (data: T) => URLSearchParams | null) =>
80
+ (data: T) => {
81
+ const result: URLSearchParams | null = closure(data);
82
+ if (result === null) throw new InternalServerErrorException(MESSAGE);
83
+ return result;
84
+ };
85
+
86
+ /**
87
+ * @internal
88
+ */
89
+ const validate =
90
+ <T>(closure: (data: T) => IValidation<URLSearchParams>) =>
91
+ (data: T) => {
92
+ const result: IValidation<URLSearchParams> = closure(data);
93
+ if (result.success === false)
94
+ throw new InternalServerErrorException({
95
+ errors: result.errors,
96
+ message: MESSAGE,
97
+ });
98
+ return result.data;
99
+ };
100
+
101
+ /**
102
+ * @internal
103
+ */
104
+ const MESSAGE = "Response body data is not following the promised type.";
@@ -0,0 +1,25 @@
1
+ import { IValidation } from "typia";
2
+
3
+ export type IResponseBodyQuerifier<T> =
4
+ | IResponseBodyquerifier.IStringify<T>
5
+ | IResponseBodyquerifier.IIs<T>
6
+ | IResponseBodyquerifier.IAssert<T>
7
+ | IResponseBodyquerifier.IValidate<T>;
8
+ export namespace IResponseBodyquerifier {
9
+ export interface IStringify<T> {
10
+ type: "stringify";
11
+ stringify: (input: T) => URLSearchParams;
12
+ }
13
+ export interface IIs<T> {
14
+ type: "is";
15
+ is: (input: T) => URLSearchParams | null;
16
+ }
17
+ export interface IAssert<T> {
18
+ type: "assert";
19
+ assert: (input: T) => URLSearchParams;
20
+ }
21
+ export interface IValidate<T> {
22
+ type: "validate";
23
+ validate: (input: T) => IValidation<URLSearchParams>;
24
+ }
25
+ }
@@ -0,0 +1,52 @@
1
+ import ts from "typescript";
2
+
3
+ import { HttpAssertQueryProgrammer } from "typia/lib/programmers/http/HttpAssertQueryProgrammer";
4
+ import { HttpIsQueryProgrammer } from "typia/lib/programmers/http/HttpIsQueryProgrammer";
5
+ import { HttpValidateQueryProgrammer } from "typia/lib/programmers/http/HttpValidateQueryProgrammer";
6
+ import { IProject } from "typia/lib/transformers/IProject";
7
+
8
+ import { INestiaTransformProject } from "../options/INestiaTransformProject";
9
+ import { IRequestQueryValidator } from "../options/IRequestQueryValidator";
10
+
11
+ export namespace TypedQueryBodyProgrammer {
12
+ export const generate =
13
+ (project: INestiaTransformProject) =>
14
+ (modulo: ts.LeftHandSideExpression) =>
15
+ (type: ts.Type): ts.ObjectLiteralExpression => {
16
+ // GENERATE VALIDATION PLAN
17
+ const parameter =
18
+ (key: IRequestQueryValidator<any>["type"]) =>
19
+ (
20
+ programmer: (
21
+ project: IProject,
22
+ ) => (
23
+ modulo: ts.LeftHandSideExpression,
24
+ ) => (type: ts.Type) => ts.ArrowFunction,
25
+ ) =>
26
+ ts.factory.createObjectLiteralExpression([
27
+ ts.factory.createPropertyAssignment(
28
+ ts.factory.createIdentifier("type"),
29
+ ts.factory.createStringLiteral(key),
30
+ ),
31
+ ts.factory.createPropertyAssignment(
32
+ ts.factory.createIdentifier(key),
33
+ programmer({
34
+ ...project,
35
+ options: {
36
+ numeric: false,
37
+ finite: false,
38
+ functional: false,
39
+ },
40
+ })(modulo)(type),
41
+ ),
42
+ ]);
43
+
44
+ // RETURNS
45
+ const category = project.options.validate;
46
+ if (category === "is" || category === "equals")
47
+ return parameter("is")(HttpIsQueryProgrammer.write);
48
+ else if (category === "validate" || category === "validateEquals")
49
+ return parameter("validate")(HttpValidateQueryProgrammer.write);
50
+ return parameter("assert")(HttpAssertQueryProgrammer.write);
51
+ };
52
+ }
@@ -0,0 +1,55 @@
1
+ import ts from "typescript";
2
+
3
+ import { IProject } from "typia/lib/transformers/IProject";
4
+
5
+ import { INestiaTransformProject } from "../options/INestiaTransformProject";
6
+ import { HttpAssertQuerifyProgrammer } from "./http/HttpAssertQuerifyProgrammer";
7
+ import { HttpIsQuerifyProgrammer } from "./http/HttpIsQuerifyProgrammer";
8
+ import { HttpQuerifyProgrammer } from "./http/HttpQuerifyProgrammer";
9
+ import { HttpValidateQuerifyProgrammer } from "./http/HttpValidateQuerifyProgrammer";
10
+
11
+ export namespace TypedQueryRouteProgrammer {
12
+ export const generate =
13
+ (project: INestiaTransformProject) =>
14
+ (modulo: ts.LeftHandSideExpression) =>
15
+ (type: ts.Type): ts.Expression => {
16
+ // GENERATE STRINGIFY PLAN
17
+ const parameter = (
18
+ key: string,
19
+ programmer: (
20
+ project: IProject,
21
+ ) => (
22
+ modulo: ts.LeftHandSideExpression,
23
+ ) => (type: ts.Type) => ts.ArrowFunction,
24
+ ) =>
25
+ ts.factory.createObjectLiteralExpression([
26
+ ts.factory.createPropertyAssignment(
27
+ ts.factory.createIdentifier("type"),
28
+ ts.factory.createStringLiteral(key),
29
+ ),
30
+ ts.factory.createPropertyAssignment(
31
+ ts.factory.createIdentifier(key),
32
+ programmer({
33
+ ...project,
34
+ options: {}, // use default option
35
+ })(modulo)(type),
36
+ ),
37
+ ]);
38
+
39
+ // RETURNS
40
+ if (project.options.stringify === "is")
41
+ return parameter("is", HttpIsQuerifyProgrammer.write);
42
+ else if (project.options.stringify === "validate")
43
+ return parameter(
44
+ "validate",
45
+ HttpValidateQuerifyProgrammer.write,
46
+ );
47
+ else if (project.options.stringify === "stringify")
48
+ return parameter("stringify", HttpQuerifyProgrammer.write);
49
+ else if (project.options.stringify === null)
50
+ return ts.factory.createNull();
51
+
52
+ // ASSERT IS DEFAULT
53
+ return parameter("assert", HttpAssertQuerifyProgrammer.write);
54
+ };
55
+ }
@@ -0,0 +1,59 @@
1
+ import ts from "typescript";
2
+
3
+ import { IdentifierFactory } from "typia/lib/factories/IdentifierFactory";
4
+ import { StatementFactory } from "typia/lib/factories/StatementFactory";
5
+ import { AssertProgrammer } from "typia/lib/programmers/AssertProgrammer";
6
+ import { IProject } from "typia/lib/transformers/IProject";
7
+
8
+ import { HttpQuerifyProgrammer } from "./HttpQuerifyProgrammer";
9
+
10
+ export namespace HttpAssertQuerifyProgrammer {
11
+ export const write =
12
+ (project: IProject) =>
13
+ (modulo: ts.LeftHandSideExpression) =>
14
+ (type: ts.Type, name?: string): ts.ArrowFunction =>
15
+ ts.factory.createArrowFunction(
16
+ undefined,
17
+ undefined,
18
+ [IdentifierFactory.parameter("input")],
19
+ undefined,
20
+ undefined,
21
+ ts.factory.createBlock([
22
+ StatementFactory.constant(
23
+ "assert",
24
+ AssertProgrammer.write({
25
+ ...project,
26
+ options: {
27
+ ...project.options,
28
+ functional: false,
29
+ numeric: false,
30
+ },
31
+ })(modulo)(false)(type, name),
32
+ ),
33
+ StatementFactory.constant(
34
+ "stringify",
35
+ HttpQuerifyProgrammer.write({
36
+ ...project,
37
+ options: {
38
+ ...project.options,
39
+ functional: false,
40
+ numeric: false,
41
+ },
42
+ })(modulo)(type),
43
+ ),
44
+ ts.factory.createReturnStatement(
45
+ ts.factory.createCallExpression(
46
+ ts.factory.createIdentifier("stringify"),
47
+ undefined,
48
+ [
49
+ ts.factory.createCallExpression(
50
+ ts.factory.createIdentifier("assert"),
51
+ undefined,
52
+ [ts.factory.createIdentifier("input")],
53
+ ),
54
+ ],
55
+ ),
56
+ ),
57
+ ]),
58
+ );
59
+ }
@@ -0,0 +1,63 @@
1
+ import ts from "typescript";
2
+
3
+ import { IdentifierFactory } from "typia/lib/factories/IdentifierFactory";
4
+ import { StatementFactory } from "typia/lib/factories/StatementFactory";
5
+ import { IsProgrammer } from "typia/lib/programmers/IsProgrammer";
6
+ import { IProject } from "typia/lib/transformers/IProject";
7
+
8
+ import { HttpQuerifyProgrammer } from "./HttpQuerifyProgrammer";
9
+
10
+ export namespace HttpIsQuerifyProgrammer {
11
+ export const write =
12
+ (project: IProject) =>
13
+ (modulo: ts.LeftHandSideExpression) =>
14
+ (type: ts.Type): ts.ArrowFunction =>
15
+ ts.factory.createArrowFunction(
16
+ undefined,
17
+ undefined,
18
+ [IdentifierFactory.parameter("input")],
19
+ undefined,
20
+ undefined,
21
+ ts.factory.createBlock([
22
+ StatementFactory.constant(
23
+ "is",
24
+ IsProgrammer.write({
25
+ ...project,
26
+ options: {
27
+ ...project.options,
28
+ functional: false,
29
+ numeric: false,
30
+ },
31
+ })(modulo)(false)(type),
32
+ ),
33
+ StatementFactory.constant(
34
+ "stringify",
35
+ HttpQuerifyProgrammer.write({
36
+ ...project,
37
+ options: {
38
+ ...project.options,
39
+ functional: false,
40
+ numeric: false,
41
+ },
42
+ })(modulo)(type),
43
+ ),
44
+ ts.factory.createReturnStatement(
45
+ ts.factory.createConditionalExpression(
46
+ ts.factory.createCallExpression(
47
+ ts.factory.createIdentifier("is"),
48
+ undefined,
49
+ [ts.factory.createIdentifier("input")],
50
+ ),
51
+ undefined,
52
+ ts.factory.createCallExpression(
53
+ ts.factory.createIdentifier("stringify"),
54
+ undefined,
55
+ [ts.factory.createIdentifier("input")],
56
+ ),
57
+ undefined,
58
+ ts.factory.createNull(),
59
+ ),
60
+ ),
61
+ ]),
62
+ );
63
+ }
@@ -0,0 +1,105 @@
1
+ import ts from "typescript";
2
+
3
+ import { IdentifierFactory } from "typia/lib/factories/IdentifierFactory";
4
+ import { MetadataCollection } from "typia/lib/factories/MetadataCollection";
5
+ import { MetadataFactory } from "typia/lib/factories/MetadataFactory";
6
+ import { StatementFactory } from "typia/lib/factories/StatementFactory";
7
+ import { FunctionImporter } from "typia/lib/programmers/helpers/FunctionImporeter";
8
+ import { HttpQueryProgrammer } from "typia/lib/programmers/http/HttpQueryProgrammer";
9
+ import { Metadata } from "typia/lib/schemas/metadata/Metadata";
10
+ import { MetadataObject } from "typia/lib/schemas/metadata/MetadataObject";
11
+ import { IProject } from "typia/lib/transformers/IProject";
12
+ import { TransformerError } from "typia/lib/transformers/TransformerError";
13
+
14
+ export namespace HttpQuerifyProgrammer {
15
+ export const write =
16
+ (project: IProject) =>
17
+ (modulo: ts.LeftHandSideExpression) =>
18
+ (type: ts.Type): ts.ArrowFunction => {
19
+ // GET OBJECT TYPE
20
+ const importer: FunctionImporter = new FunctionImporter(
21
+ modulo.getText(),
22
+ );
23
+ const collection: MetadataCollection = new MetadataCollection();
24
+ const result = MetadataFactory.analyze(project.checker)({
25
+ escape: false,
26
+ constant: true,
27
+ absorb: true,
28
+ validate: HttpQueryProgrammer.validate,
29
+ })(collection)(type);
30
+ if (result.success === false)
31
+ throw TransformerError.from(
32
+ `@nestia.core.TypedQuery.${importer.method}`,
33
+ )(result.errors);
34
+
35
+ const object: MetadataObject = result.data.objects[0]!;
36
+ return ts.factory.createArrowFunction(
37
+ undefined,
38
+ undefined,
39
+ [IdentifierFactory.parameter("input")],
40
+ undefined,
41
+ undefined,
42
+ ts.factory.createBlock(
43
+ [
44
+ ...importer.declare(modulo),
45
+ StatementFactory.constant(
46
+ "output",
47
+ ts.factory.createNewExpression(
48
+ ts.factory.createIdentifier("URLSearchParams"),
49
+ undefined,
50
+ [],
51
+ ),
52
+ ),
53
+ ...object.properties.map((p) =>
54
+ ts.factory.createExpressionStatement(
55
+ decode(p.key.constants[0]!.values[0] as string)(
56
+ p.value,
57
+ ),
58
+ ),
59
+ ),
60
+ ts.factory.createReturnStatement(
61
+ ts.factory.createIdentifier("output"),
62
+ ),
63
+ ],
64
+ true,
65
+ ),
66
+ );
67
+ };
68
+
69
+ const decode =
70
+ (key: string) =>
71
+ (value: Metadata): ts.CallExpression =>
72
+ !!value.arrays.length
73
+ ? ts.factory.createCallExpression(
74
+ IdentifierFactory.access(
75
+ IdentifierFactory.access(
76
+ ts.factory.createIdentifier("input"),
77
+ )(key),
78
+ )("forEach"),
79
+ undefined,
80
+ [
81
+ ts.factory.createArrowFunction(
82
+ undefined,
83
+ undefined,
84
+ [IdentifierFactory.parameter("elem")],
85
+ undefined,
86
+ undefined,
87
+ append(key)(ts.factory.createIdentifier("elem")),
88
+ ),
89
+ ],
90
+ )
91
+ : append(key)(
92
+ IdentifierFactory.access(
93
+ ts.factory.createIdentifier("input"),
94
+ )(key),
95
+ );
96
+
97
+ const append = (key: string) => (elem: ts.Expression) =>
98
+ ts.factory.createCallExpression(
99
+ IdentifierFactory.access(ts.factory.createIdentifier("output"))(
100
+ "append",
101
+ ),
102
+ undefined,
103
+ [ts.factory.createStringLiteral(key), elem],
104
+ );
105
+ }