Skip to content

Commit c0a3f56

Browse files
jbl428imdudu1
andcommitted
feat: add path variable decorator
Co-authored-by: imdudu1 <[email protected]>
1 parent 4c1d4a9 commit c0a3f56

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

lib/decorators/constants.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export const HTTP_INTERFACE_METADATA = Symbol("HTTP_INTERFACE_METADATA");
22
export const HTTP_EXCHANGE_METADATA = Symbol("HTTP_EXCHANGE_METADATA");
3+
export const PATH_VARIABLE_METADATA = Symbol("PATH_VARIABLE_METADATA");
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { describe, test, expect } from "vitest";
2+
import { PATH_VARIABLE_METADATA } from "./constants";
3+
import {
4+
PathVariable,
5+
type PathVariableMetadata,
6+
} from "./path-variable.decorator";
7+
8+
describe("PathVariable", () => {
9+
test("should set path variable metadata", () => {
10+
// given
11+
class TestService {
12+
request(
13+
@PathVariable("foo") foo: string,
14+
@PathVariable("bar") bar: string
15+
): string {
16+
return foo + bar;
17+
}
18+
}
19+
20+
// when
21+
const result: PathVariableMetadata = Reflect.getMetadata(
22+
PATH_VARIABLE_METADATA,
23+
TestService.prototype,
24+
"request"
25+
);
26+
27+
// then
28+
expect(result).toHaveLength(2);
29+
expect(result.get(0)).toBe("foo");
30+
expect(result.get(1)).toBe("bar");
31+
});
32+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { PATH_VARIABLE_METADATA } from "./constants";
2+
3+
export type PathVariableMetadata = Map<number, string>;
4+
5+
export function PathVariable(name: string): ParameterDecorator {
6+
return (target, propertyKey, parameterIndex) => {
7+
if (typeof propertyKey === "undefined") {
8+
return;
9+
}
10+
11+
const metadata: PathVariableMetadata =
12+
Reflect.getMetadata(PATH_VARIABLE_METADATA, target, propertyKey) ??
13+
new Map();
14+
15+
metadata.set(parameterIndex, name);
16+
17+
Reflect.defineMetadata(
18+
PATH_VARIABLE_METADATA,
19+
metadata,
20+
target,
21+
propertyKey
22+
);
23+
};
24+
}

0 commit comments

Comments
 (0)