Skip to content

Commit 04ddc66

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

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
@@ -4,3 +4,4 @@ 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");
66
export const REQUEST_FORM_METADATA = Symbol("REQUEST_BODY_METADATA");
7+
export const REQUEST_HEADER_METADATA = Symbol("REQUEST_HEADER_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_HEADER_METADATA } from "./constants";
3+
import {
4+
RequestHeader,
5+
type RequestHeaderMetadata,
6+
} from "./request-header.decorator";
7+
8+
describe("RequestHeader", () => {
9+
test("should set request header metadata with empty key", () => {
10+
// given
11+
class TestService {
12+
request(@RequestHeader() query: { foo: string }): string {
13+
return query.foo;
14+
}
15+
}
16+
17+
// when
18+
const result: RequestHeaderMetadata = Reflect.getMetadata(
19+
REQUEST_HEADER_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 header metadata with key", () => {
30+
// given
31+
class TestService {
32+
request(@RequestHeader("foo") bar: string): string {
33+
return bar;
34+
}
35+
}
36+
37+
// when
38+
const result: RequestHeaderMetadata = Reflect.getMetadata(
39+
REQUEST_HEADER_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_HEADER_METADATA } from "./constants";
2+
3+
export type RequestHeaderMetadata = Map<number, string>;
4+
5+
export function RequestHeader(key?: string): ParameterDecorator {
6+
return (target, propertyKey, parameterIndex) => {
7+
if (typeof propertyKey === "undefined") {
8+
return;
9+
}
10+
11+
const metadata =
12+
Reflect.getMetadata(REQUEST_HEADER_METADATA, target, propertyKey) ??
13+
new Map();
14+
15+
metadata.set(parameterIndex, key);
16+
17+
Reflect.defineMetadata(
18+
REQUEST_HEADER_METADATA,
19+
metadata,
20+
target,
21+
propertyKey
22+
);
23+
};
24+
}

0 commit comments

Comments
 (0)