Skip to content

Commit 8d2274b

Browse files
jbl428imdudu1
andcommitted
feat: add request form decorator
Co-authored-by: imdudu1 <[email protected]>
1 parent 3bb21b3 commit 8d2274b

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

lib/decorators/constants.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ export const HTTP_EXCHANGE_METADATA = Symbol("HTTP_EXCHANGE_METADATA");
33
export const PATH_VARIABLE_METADATA = Symbol("PATH_VARIABLE_METADATA");
44
export const REQUEST_PARAM_METADATA = Symbol("REQUEST_PARAM_METADATA");
55
export const REQUEST_BODY_METADATA = Symbol("REQUEST_BODY_METADATA");
6+
export const REQUEST_FORM_METADATA = Symbol("REQUEST_BODY_METADATA");
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { describe, test, expect } from "vitest";
2+
import { REQUEST_FORM_METADATA } from "./constants";
3+
import {
4+
RequestForm,
5+
type RequestFromMetadata,
6+
} from "./request-form.decorator";
7+
8+
describe("RequestForm", () => {
9+
test("should set request form metadata with empty key", () => {
10+
// given
11+
class TestService {
12+
request(@RequestForm() query: { foo: string }): string {
13+
return query.foo;
14+
}
15+
}
16+
17+
// when
18+
const result: RequestFromMetadata = Reflect.getMetadata(
19+
REQUEST_FORM_METADATA,
20+
TestService.prototype,
21+
"request"
22+
);
23+
24+
// then
25+
expect(result).toHaveLength(1);
26+
expect(result.get(0)).toBeUndefined();
27+
});
28+
29+
test("should set request form metadata with key", () => {
30+
// given
31+
class TestService {
32+
request(@RequestForm("foo") bar: string): string {
33+
return bar;
34+
}
35+
}
36+
37+
// when
38+
const result: RequestFromMetadata = Reflect.getMetadata(
39+
REQUEST_FORM_METADATA,
40+
TestService.prototype,
41+
"request"
42+
);
43+
44+
// then
45+
expect(result).toHaveLength(1);
46+
expect(result.get(0)).toBe("foo");
47+
});
48+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { REQUEST_FORM_METADATA } from "./constants";
2+
3+
export type RequestFromMetadata = Map<number, string | undefined>;
4+
5+
export function RequestForm(key?: string): ParameterDecorator {
6+
return (target, propertyKey, parameterIndex) => {
7+
if (typeof propertyKey === "undefined") {
8+
return;
9+
}
10+
11+
const metadata =
12+
Reflect.getMetadata(REQUEST_FORM_METADATA, target, propertyKey) ??
13+
new Map();
14+
15+
metadata.set(parameterIndex, key);
16+
17+
Reflect.defineMetadata(
18+
REQUEST_FORM_METADATA,
19+
metadata,
20+
target,
21+
propertyKey
22+
);
23+
};
24+
}

0 commit comments

Comments
 (0)