endpoint-fetcher 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +427 -0
- package/dist/index.d.mts +21 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +75 -0
- package/dist/index.mjs +51 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lorenzo Giovanni Vecchio
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
# endpoint-fetcher
|
|
2
|
+
|
|
3
|
+
A type-safe API client builder using the Fetch API with full TypeScript support.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install fetcher
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- 🔒 **Fully type-safe** - Input and output types are enforced at compile time
|
|
14
|
+
- 🎯 **Dynamic paths** - Use functions to build paths from input parameters
|
|
15
|
+
- 🔧 **Custom handlers** - Override default behavior for specific endpoints
|
|
16
|
+
- 🌐 **Configurable fetch** - Pass your own fetch instance with interceptors, retries, etc.
|
|
17
|
+
- 📝 **Auto JSON handling** - Automatic serialization and deserialization
|
|
18
|
+
- 🔑 **Default headers** - Set common headers like authorization tokens
|
|
19
|
+
|
|
20
|
+
## Basic Usage
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { createApiClient, EndpointConfig } from 'fetcher';
|
|
24
|
+
|
|
25
|
+
type User = { id: string; name: string; email: string };
|
|
26
|
+
|
|
27
|
+
const api = createApiClient(
|
|
28
|
+
{
|
|
29
|
+
getUser: {
|
|
30
|
+
method: 'GET',
|
|
31
|
+
path: (input: { id: string }) => `/users/${input.id}`,
|
|
32
|
+
} as EndpointConfig<{ id: string }, User>,
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
baseUrl: 'https://api.example.com',
|
|
36
|
+
}
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
// Fully type-safe!
|
|
40
|
+
const user = await api.getUser({ id: '123' });
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Examples
|
|
44
|
+
|
|
45
|
+
### 1. Static Path (Simple GET)
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
const api = createApiClient(
|
|
49
|
+
{
|
|
50
|
+
listUsers: {
|
|
51
|
+
method: 'GET',
|
|
52
|
+
path: '/users',
|
|
53
|
+
} as EndpointConfig<void, User[]>,
|
|
54
|
+
},
|
|
55
|
+
{ baseUrl: 'https://api.example.com' }
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
// No input required
|
|
59
|
+
const users = await api.listUsers();
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### 2. Dynamic Path with Function
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
const api = createApiClient(
|
|
66
|
+
{
|
|
67
|
+
getUser: {
|
|
68
|
+
method: 'GET',
|
|
69
|
+
path: (input: { id: string }) => `/users/${input.id}`,
|
|
70
|
+
} as EndpointConfig<{ id: string }, User>,
|
|
71
|
+
|
|
72
|
+
getUserPosts: {
|
|
73
|
+
method: 'GET',
|
|
74
|
+
path: (input: { userId: string; page?: number }) =>
|
|
75
|
+
`/users/${input.userId}/posts${input.page ? `?page=${input.page}` : ''}`,
|
|
76
|
+
} as EndpointConfig<{ userId: string; page?: number }, Post[]>,
|
|
77
|
+
},
|
|
78
|
+
{ baseUrl: 'https://api.example.com' }
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
const user = await api.getUser({ id: '123' });
|
|
82
|
+
const posts = await api.getUserPosts({ userId: '123', page: 2 });
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### 3. POST with Request Body
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
type CreateUserInput = { name: string; email: string };
|
|
89
|
+
|
|
90
|
+
const api = createApiClient(
|
|
91
|
+
{
|
|
92
|
+
createUser: {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
path: '/users',
|
|
95
|
+
} as EndpointConfig<CreateUserInput, User>,
|
|
96
|
+
},
|
|
97
|
+
{ baseUrl: 'https://api.example.com' }
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
const newUser = await api.createUser({
|
|
101
|
+
name: 'John Doe',
|
|
102
|
+
email: 'john@example.com'
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### 4. PUT/PATCH with Dynamic Path
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
type UpdateUserInput = {
|
|
110
|
+
id: string;
|
|
111
|
+
name?: string;
|
|
112
|
+
email?: string
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const api = createApiClient(
|
|
116
|
+
{
|
|
117
|
+
updateUser: {
|
|
118
|
+
method: 'PATCH',
|
|
119
|
+
path: (input: UpdateUserInput) => `/users/${input.id}`,
|
|
120
|
+
} as EndpointConfig<UpdateUserInput, User>,
|
|
121
|
+
},
|
|
122
|
+
{ baseUrl: 'https://api.example.com' }
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
const updated = await api.updateUser({
|
|
126
|
+
id: '123',
|
|
127
|
+
name: 'Jane Doe'
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### 5. DELETE
|
|
132
|
+
|
|
133
|
+
```typescript
|
|
134
|
+
const api = createApiClient(
|
|
135
|
+
{
|
|
136
|
+
deleteUser: {
|
|
137
|
+
method: 'DELETE',
|
|
138
|
+
path: (input: { id: string }) => `/users/${input.id}`,
|
|
139
|
+
} as EndpointConfig<{ id: string }, void>,
|
|
140
|
+
},
|
|
141
|
+
{ baseUrl: 'https://api.example.com' }
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
await api.deleteUser({ id: '123' });
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
### 6. Custom Handler for Special Cases
|
|
148
|
+
|
|
149
|
+
Use custom handlers when you need full control over the request (e.g., file uploads, custom headers, non-JSON responses).
|
|
150
|
+
|
|
151
|
+
```typescript
|
|
152
|
+
const api = createApiClient(
|
|
153
|
+
{
|
|
154
|
+
uploadFile: {
|
|
155
|
+
method: 'POST',
|
|
156
|
+
path: '/upload',
|
|
157
|
+
handler: async ({ input, fetch }) => {
|
|
158
|
+
const formData = new FormData();
|
|
159
|
+
formData.append('file', input.file);
|
|
160
|
+
formData.append('category', input.category);
|
|
161
|
+
|
|
162
|
+
const response = await fetch('https://api.example.com/upload', {
|
|
163
|
+
method: 'POST',
|
|
164
|
+
body: formData,
|
|
165
|
+
// Note: Don't set Content-Type for FormData
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
if (!response.ok) {
|
|
169
|
+
throw new Error('Upload failed');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return response.json();
|
|
173
|
+
},
|
|
174
|
+
} as EndpointConfig
|
|
175
|
+
{ file: File; category: string },
|
|
176
|
+
{ url: string; id: string }
|
|
177
|
+
>,
|
|
178
|
+
|
|
179
|
+
downloadFile: {
|
|
180
|
+
method: 'GET',
|
|
181
|
+
path: '/download',
|
|
182
|
+
handler: async ({ input, fetch }) => {
|
|
183
|
+
const response = await fetch(
|
|
184
|
+
`https://api.example.com/files/${input.id}`,
|
|
185
|
+
{ method: 'GET' }
|
|
186
|
+
);
|
|
187
|
+
|
|
188
|
+
if (!response.ok) {
|
|
189
|
+
throw new Error('Download failed');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return response.blob();
|
|
193
|
+
},
|
|
194
|
+
} as EndpointConfig<{ id: string }, Blob>,
|
|
195
|
+
},
|
|
196
|
+
{ baseUrl: 'https://api.example.com' }
|
|
197
|
+
);
|
|
198
|
+
|
|
199
|
+
// Usage
|
|
200
|
+
const file = new File(['content'], 'test.txt');
|
|
201
|
+
const result = await api.uploadFile({ file, category: 'documents' });
|
|
202
|
+
|
|
203
|
+
const blob = await api.downloadFile({ id: 'file-123' });
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### 7. Using Custom Fetch Instance
|
|
207
|
+
|
|
208
|
+
Pass a configured fetch instance for authentication, retries, logging, etc.
|
|
209
|
+
|
|
210
|
+
```typescript
|
|
211
|
+
// Custom fetch with interceptors
|
|
212
|
+
const customFetch: typeof fetch = async (input, init) => {
|
|
213
|
+
console.log('Request:', input);
|
|
214
|
+
|
|
215
|
+
// Add auth token
|
|
216
|
+
const headers = new Headers(init?.headers);
|
|
217
|
+
headers.set('Authorization', `Bearer ${getToken()}`);
|
|
218
|
+
|
|
219
|
+
const response = await fetch(input, {
|
|
220
|
+
...init,
|
|
221
|
+
headers,
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
console.log('Response:', response.status);
|
|
225
|
+
|
|
226
|
+
// Handle 401
|
|
227
|
+
if (response.status === 401) {
|
|
228
|
+
await refreshToken();
|
|
229
|
+
// Retry request
|
|
230
|
+
return fetch(input, init);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return response;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const api = createApiClient(
|
|
237
|
+
{
|
|
238
|
+
getUser: {
|
|
239
|
+
method: 'GET',
|
|
240
|
+
path: (input: { id: string }) => `/users/${input.id}`,
|
|
241
|
+
} as EndpointConfig<{ id: string }, User>,
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
baseUrl: 'https://api.example.com',
|
|
245
|
+
fetch: customFetch, // Use custom fetch
|
|
246
|
+
}
|
|
247
|
+
);
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### 8. With Default Headers
|
|
251
|
+
|
|
252
|
+
```typescript
|
|
253
|
+
const api = createApiClient(
|
|
254
|
+
{
|
|
255
|
+
getUser: {
|
|
256
|
+
method: 'GET',
|
|
257
|
+
path: (input: { id: string }) => `/users/${input.id}`,
|
|
258
|
+
} as EndpointConfig<{ id: string }, User>,
|
|
259
|
+
},
|
|
260
|
+
{
|
|
261
|
+
baseUrl: 'https://api.example.com',
|
|
262
|
+
defaultHeaders: {
|
|
263
|
+
'Authorization': 'Bearer your-token-here',
|
|
264
|
+
'X-API-Key': 'your-api-key',
|
|
265
|
+
'X-Custom-Header': 'custom-value',
|
|
266
|
+
},
|
|
267
|
+
}
|
|
268
|
+
);
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### 9. With Error Types
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
type ApiError = {
|
|
275
|
+
message: string;
|
|
276
|
+
code: string;
|
|
277
|
+
details?: Record<string, any>
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
const api = createApiClient(
|
|
281
|
+
{
|
|
282
|
+
createUser: {
|
|
283
|
+
method: 'POST',
|
|
284
|
+
path: '/users',
|
|
285
|
+
} as EndpointConfig<CreateUserInput, User, ApiError>,
|
|
286
|
+
},
|
|
287
|
+
{ baseUrl: 'https://api.example.com' }
|
|
288
|
+
);
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
const user = await api.createUser({
|
|
292
|
+
name: 'John',
|
|
293
|
+
email: 'invalid-email'
|
|
294
|
+
});
|
|
295
|
+
} catch (error) {
|
|
296
|
+
// Error will have shape: { status, statusText, error: ApiError }
|
|
297
|
+
console.error(error);
|
|
298
|
+
}
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
### 10. Complex Example - Full API Client
|
|
302
|
+
|
|
303
|
+
```typescript
|
|
304
|
+
import { createApiClient, EndpointConfig } from 'fetcher';
|
|
305
|
+
|
|
306
|
+
// Types
|
|
307
|
+
type User = { id: string; name: string; email: string };
|
|
308
|
+
type Post = { id: string; title: string; content: string; userId: string };
|
|
309
|
+
type Comment = { id: string; content: string; postId: string };
|
|
310
|
+
type ApiError = { message: string; code: string };
|
|
311
|
+
|
|
312
|
+
// Create client
|
|
313
|
+
const api = createApiClient(
|
|
314
|
+
{
|
|
315
|
+
// Users
|
|
316
|
+
listUsers: {
|
|
317
|
+
method: 'GET',
|
|
318
|
+
path: '/users',
|
|
319
|
+
} as EndpointConfig<void, User[], ApiError>,
|
|
320
|
+
|
|
321
|
+
getUser: {
|
|
322
|
+
method: 'GET',
|
|
323
|
+
path: (input: { id: string }) => `/users/${input.id}`,
|
|
324
|
+
} as EndpointConfig<{ id: string }, User, ApiError>,
|
|
325
|
+
|
|
326
|
+
createUser: {
|
|
327
|
+
method: 'POST',
|
|
328
|
+
path: '/users',
|
|
329
|
+
} as EndpointConfig<Omit<User, 'id'>, User, ApiError>,
|
|
330
|
+
|
|
331
|
+
updateUser: {
|
|
332
|
+
method: 'PATCH',
|
|
333
|
+
path: (input: Partial<User> & { id: string }) => `/users/${input.id}`,
|
|
334
|
+
} as EndpointConfig<Partial<User> & { id: string }, User, ApiError>,
|
|
335
|
+
|
|
336
|
+
deleteUser: {
|
|
337
|
+
method: 'DELETE',
|
|
338
|
+
path: (input: { id: string }) => `/users/${input.id}`,
|
|
339
|
+
} as EndpointConfig<{ id: string }, void, ApiError>,
|
|
340
|
+
|
|
341
|
+
// Posts
|
|
342
|
+
getUserPosts: {
|
|
343
|
+
method: 'GET',
|
|
344
|
+
path: (input: { userId: string }) => `/users/${input.userId}/posts`,
|
|
345
|
+
} as EndpointConfig<{ userId: string }, Post[], ApiError>,
|
|
346
|
+
|
|
347
|
+
createPost: {
|
|
348
|
+
method: 'POST',
|
|
349
|
+
path: '/posts',
|
|
350
|
+
} as EndpointConfig<Omit<Post, 'id'>, Post, ApiError>,
|
|
351
|
+
|
|
352
|
+
// Custom handler for search with query params
|
|
353
|
+
searchPosts: {
|
|
354
|
+
method: 'GET',
|
|
355
|
+
path: '/posts/search',
|
|
356
|
+
handler: async ({ input, fetch, path }) => {
|
|
357
|
+
const params = new URLSearchParams({
|
|
358
|
+
q: input.query,
|
|
359
|
+
...(input.limit && { limit: input.limit.toString() }),
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
const response = await fetch(
|
|
363
|
+
`https://api.example.com${path}?${params}`,
|
|
364
|
+
{ method: 'GET' }
|
|
365
|
+
);
|
|
366
|
+
|
|
367
|
+
if (!response.ok) throw new Error('Search failed');
|
|
368
|
+
return response.json();
|
|
369
|
+
},
|
|
370
|
+
} as EndpointConfig
|
|
371
|
+
{ query: string; limit?: number },
|
|
372
|
+
Post[],
|
|
373
|
+
ApiError
|
|
374
|
+
>,
|
|
375
|
+
},
|
|
376
|
+
{
|
|
377
|
+
baseUrl: 'https://api.example.com',
|
|
378
|
+
defaultHeaders: {
|
|
379
|
+
'Authorization': 'Bearer token123',
|
|
380
|
+
},
|
|
381
|
+
}
|
|
382
|
+
);
|
|
383
|
+
|
|
384
|
+
// Usage - all type-safe!
|
|
385
|
+
const users = await api.listUsers();
|
|
386
|
+
const user = await api.getUser({ id: '1' });
|
|
387
|
+
const newUser = await api.createUser({ name: 'John', email: 'john@example.com' });
|
|
388
|
+
const posts = await api.getUserPosts({ userId: '1' });
|
|
389
|
+
const searchResults = await api.searchPosts({ query: 'typescript', limit: 10 });
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
## API Reference
|
|
393
|
+
|
|
394
|
+
### `createApiClient(endpoints, config)`
|
|
395
|
+
|
|
396
|
+
Creates a type-safe API client.
|
|
397
|
+
|
|
398
|
+
**Parameters:**
|
|
399
|
+
|
|
400
|
+
- `endpoints`: Object mapping endpoint names to configurations
|
|
401
|
+
|
|
402
|
+
- `method`: HTTP method ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE')
|
|
403
|
+
- `path`: Static string or function `(input) => string`
|
|
404
|
+
- `handler`: Optional custom handler function (receives `{ input, fetch, method, path }`)
|
|
405
|
+
- `config`: Client configuration
|
|
406
|
+
|
|
407
|
+
- `baseUrl`: Base URL for all requests
|
|
408
|
+
- `fetch`: Optional custom fetch instance
|
|
409
|
+
- `defaultHeaders`: Optional headers applied to all requests
|
|
410
|
+
|
|
411
|
+
**Returns:** Type-safe client object with methods for each endpoint
|
|
412
|
+
|
|
413
|
+
## TypeScript Support
|
|
414
|
+
|
|
415
|
+
Full TypeScript support with generic types:
|
|
416
|
+
|
|
417
|
+
```typescript
|
|
418
|
+
EndpointConfig<TInput, TOutput, TError>
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
- `TInput`: Input parameter type
|
|
422
|
+
- `TOutput`: Response type
|
|
423
|
+
- `TError`: Error type (optional)
|
|
424
|
+
|
|
425
|
+
## License
|
|
426
|
+
|
|
427
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
2
|
+
type EndpointConfig<TInput = any, TOutput = any, TError = any> = {
|
|
3
|
+
method: HttpMethod;
|
|
4
|
+
path: string | ((input: TInput) => string);
|
|
5
|
+
handler?: (params: {
|
|
6
|
+
input: TInput;
|
|
7
|
+
fetch: typeof fetch;
|
|
8
|
+
method: HttpMethod;
|
|
9
|
+
path: string;
|
|
10
|
+
}) => Promise<TOutput>;
|
|
11
|
+
};
|
|
12
|
+
type ApiConfig = {
|
|
13
|
+
baseUrl: string;
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
defaultHeaders?: HeadersInit;
|
|
16
|
+
};
|
|
17
|
+
type EndpointDefinitions = Record<string, EndpointConfig>;
|
|
18
|
+
|
|
19
|
+
declare function createApiClient<TEndpoints extends EndpointDefinitions>(endpoints: TEndpoints, config: ApiConfig): { [K in keyof TEndpoints]: TEndpoints[K] extends infer T ? T extends TEndpoints[K] ? T extends EndpointConfig<infer TInput, infer TOutput, any> ? (input: TInput) => Promise<TOutput> : never : never : never; };
|
|
20
|
+
|
|
21
|
+
export { type ApiConfig, type EndpointConfig, type EndpointDefinitions, type HttpMethod, createApiClient };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
2
|
+
type EndpointConfig<TInput = any, TOutput = any, TError = any> = {
|
|
3
|
+
method: HttpMethod;
|
|
4
|
+
path: string | ((input: TInput) => string);
|
|
5
|
+
handler?: (params: {
|
|
6
|
+
input: TInput;
|
|
7
|
+
fetch: typeof fetch;
|
|
8
|
+
method: HttpMethod;
|
|
9
|
+
path: string;
|
|
10
|
+
}) => Promise<TOutput>;
|
|
11
|
+
};
|
|
12
|
+
type ApiConfig = {
|
|
13
|
+
baseUrl: string;
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
defaultHeaders?: HeadersInit;
|
|
16
|
+
};
|
|
17
|
+
type EndpointDefinitions = Record<string, EndpointConfig>;
|
|
18
|
+
|
|
19
|
+
declare function createApiClient<TEndpoints extends EndpointDefinitions>(endpoints: TEndpoints, config: ApiConfig): { [K in keyof TEndpoints]: TEndpoints[K] extends infer T ? T extends TEndpoints[K] ? T extends EndpointConfig<infer TInput, infer TOutput, any> ? (input: TInput) => Promise<TOutput> : never : never : never; };
|
|
20
|
+
|
|
21
|
+
export { type ApiConfig, type EndpointConfig, type EndpointDefinitions, type HttpMethod, createApiClient };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
|
|
19
|
+
// src/index.ts
|
|
20
|
+
var index_exports = {};
|
|
21
|
+
__export(index_exports, {
|
|
22
|
+
createApiClient: () => createApiClient
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(index_exports);
|
|
25
|
+
function createApiClient(endpoints, config) {
|
|
26
|
+
const fetchInstance = config.fetch ?? globalThis.fetch;
|
|
27
|
+
const buildUrl = (path, baseUrl) => {
|
|
28
|
+
const normalizedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
|
|
29
|
+
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
30
|
+
return `${normalizedBase}${normalizedPath}`;
|
|
31
|
+
};
|
|
32
|
+
const defaultHandler = async (method, path, input) => {
|
|
33
|
+
const url = buildUrl(path, config.baseUrl);
|
|
34
|
+
const options = {
|
|
35
|
+
method,
|
|
36
|
+
headers: {
|
|
37
|
+
"Content-Type": "application/json",
|
|
38
|
+
...config.defaultHeaders
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
if (method !== "GET" && method !== "DELETE" && input !== void 0) {
|
|
42
|
+
options.body = JSON.stringify(input);
|
|
43
|
+
}
|
|
44
|
+
const response = await fetchInstance(url, options);
|
|
45
|
+
if (!response.ok) {
|
|
46
|
+
const error = await response.json().catch(() => ({}));
|
|
47
|
+
throw {
|
|
48
|
+
status: response.status,
|
|
49
|
+
statusText: response.statusText,
|
|
50
|
+
error
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
return response.json();
|
|
54
|
+
};
|
|
55
|
+
const client = {};
|
|
56
|
+
for (const [name, endpoint] of Object.entries(endpoints)) {
|
|
57
|
+
client[name] = (async (input) => {
|
|
58
|
+
const path = typeof endpoint.path === "function" ? endpoint.path(input) : endpoint.path;
|
|
59
|
+
if (endpoint.handler) {
|
|
60
|
+
return endpoint.handler({
|
|
61
|
+
input,
|
|
62
|
+
fetch: fetchInstance,
|
|
63
|
+
method: endpoint.method,
|
|
64
|
+
path
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return defaultHandler(endpoint.method, path, input);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return client;
|
|
71
|
+
}
|
|
72
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
73
|
+
0 && (module.exports = {
|
|
74
|
+
createApiClient
|
|
75
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
function createApiClient(endpoints, config) {
|
|
3
|
+
const fetchInstance = config.fetch ?? globalThis.fetch;
|
|
4
|
+
const buildUrl = (path, baseUrl) => {
|
|
5
|
+
const normalizedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
|
|
6
|
+
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
7
|
+
return `${normalizedBase}${normalizedPath}`;
|
|
8
|
+
};
|
|
9
|
+
const defaultHandler = async (method, path, input) => {
|
|
10
|
+
const url = buildUrl(path, config.baseUrl);
|
|
11
|
+
const options = {
|
|
12
|
+
method,
|
|
13
|
+
headers: {
|
|
14
|
+
"Content-Type": "application/json",
|
|
15
|
+
...config.defaultHeaders
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
if (method !== "GET" && method !== "DELETE" && input !== void 0) {
|
|
19
|
+
options.body = JSON.stringify(input);
|
|
20
|
+
}
|
|
21
|
+
const response = await fetchInstance(url, options);
|
|
22
|
+
if (!response.ok) {
|
|
23
|
+
const error = await response.json().catch(() => ({}));
|
|
24
|
+
throw {
|
|
25
|
+
status: response.status,
|
|
26
|
+
statusText: response.statusText,
|
|
27
|
+
error
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
return response.json();
|
|
31
|
+
};
|
|
32
|
+
const client = {};
|
|
33
|
+
for (const [name, endpoint] of Object.entries(endpoints)) {
|
|
34
|
+
client[name] = (async (input) => {
|
|
35
|
+
const path = typeof endpoint.path === "function" ? endpoint.path(input) : endpoint.path;
|
|
36
|
+
if (endpoint.handler) {
|
|
37
|
+
return endpoint.handler({
|
|
38
|
+
input,
|
|
39
|
+
fetch: fetchInstance,
|
|
40
|
+
method: endpoint.method,
|
|
41
|
+
path
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return defaultHandler(endpoint.method, path, input);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return client;
|
|
48
|
+
}
|
|
49
|
+
export {
|
|
50
|
+
createApiClient
|
|
51
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "endpoint-fetcher",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Type-safe API client builder using fetch",
|
|
5
|
+
"main": "./dist/index.cjs",
|
|
6
|
+
"module": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"import": "./dist/index.js",
|
|
11
|
+
"require": "./dist/index.cjs",
|
|
12
|
+
"types": "./dist/index.d.ts"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
|
|
22
|
+
"watch": "tsup src/index.ts --format cjs,esm --dts --watch",
|
|
23
|
+
"prepublishOnly": "npm run build"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"api",
|
|
27
|
+
"client",
|
|
28
|
+
"fetch",
|
|
29
|
+
"typescript",
|
|
30
|
+
"type-safe",
|
|
31
|
+
"http",
|
|
32
|
+
"rest",
|
|
33
|
+
"api-client",
|
|
34
|
+
"typed",
|
|
35
|
+
"fetcher"
|
|
36
|
+
],
|
|
37
|
+
"author": "Lorenzo Vecchio",
|
|
38
|
+
"license": "MIT",
|
|
39
|
+
"repository": {
|
|
40
|
+
"type": "git",
|
|
41
|
+
"url": "git+https://github.com/lorenzo-vecchio/endpoint-fetcher.git"
|
|
42
|
+
},
|
|
43
|
+
"bugs": {
|
|
44
|
+
"url": "https://github.com/lorenzo-vecchio/endpoint-fetcher/issues"
|
|
45
|
+
},
|
|
46
|
+
"homepage": "https://github.com/lorenzo-vecchio/endpoint-fetcher#readme",
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=16.0.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/node": "^20.0.0",
|
|
52
|
+
"tsup": "^8.5.1",
|
|
53
|
+
"typescript": "^5.0.0"
|
|
54
|
+
}
|
|
55
|
+
}
|