Skip to content

Commit 433ee66

Browse files
committed
refactor: use brackets [] to define path params instead of :
1 parent 51f9c84 commit 433ee66

File tree

3 files changed

+25
-10
lines changed

3 files changed

+25
-10
lines changed

packages/api/src/client/middleware/replacePathParams.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,15 @@ export function replacePathParams(
2929
};
3030
const { excludePathParams = true } = options;
3131
// replace url params with input
32-
const params = req.url.match(/:\w+/g);
32+
const params = req.url.match(/\[\w+\]/g);
3333

3434
if (params) {
3535
req.rawUrl = req.url;
3636

3737
let nextUrl = req.url;
3838
for (const param of params) {
39-
const key = param.slice(1);
39+
// remove brackets
40+
const key = param.slice(1, -1);
4041
if (isObject(req.input)) {
4142
const value = req.input[key];
4243
if (typeof value === 'number' || typeof value === 'string') {

packages/api/src/types.ts

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,17 +45,33 @@ export type AnyObject = Record<string, any>;
4545
export type AnyAsyncFn<R = any> = (...args: any[]) => Promise<R>;
4646

4747
export type ApiRequest = {
48+
/**
49+
* input of the api
50+
*/
4851
input: unknown;
52+
53+
/**
54+
* parsed input, should be set after validation
55+
*/
4956
parsedInput: unknown;
5057
};
5158

5259
export type ApiResponse = {
60+
/**
61+
* output of the api, can be anything except `undefined`.
62+
*/
5363
output: unknown;
54-
ok: boolean;
5564
};
5665

5766
export type HttpRequest = {
67+
/**
68+
* http method, e.g. 'GET', 'POST', 'PUT', 'DELETE'
69+
*/
5870
method: string;
71+
72+
/**
73+
* http url
74+
*/
5975
url: string;
6076
};
6177

@@ -78,12 +94,10 @@ export type Options = {
7894
};
7995

8096
/**
81-
* convert 'users/:id' to { id: string }
97+
* convert 'users/[id]' to { id: string }
8298
*/
8399
export type ExtractPathParams<U extends string> =
84-
U extends `${string}:${infer P}/${infer R}`
100+
U extends `${string}[${infer P}]${infer R}`
85101
? { [K in P | keyof ExtractPathParams<R>]: string | number }
86-
: U extends `${string}:${infer P}`
87-
? { [K in P]: string | number }
88-
: // biome-ignore lint/suspicious/noConfusingVoidType: <explanation>
89-
void;
102+
: // biome-ignore lint/suspicious/noConfusingVoidType: <explanation>
103+
void;

readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ const api = new ApiClient({
3737
},
3838
middlewares: [
3939
logger(),
40-
// replace path params from input. e.g. /users/:id to /users/1
40+
// replace path params from input. e.g. /users/[id] to /users/1
4141
replacePathParams(),
4242
],
4343
});

0 commit comments

Comments
 (0)