-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexample-typescript.ts
More file actions
51 lines (44 loc) · 1.26 KB
/
example-typescript.ts
File metadata and controls
51 lines (44 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { createApiFetcher } from 'fetchff';
import type { Endpoint } from 'fetchff';
// Example endpoint interfaces
type Book = { id: number; title: string; rating: number };
type Books = { books: Book[]; totalResults: number };
type BookQueryParams = { newBook?: boolean; category?: string };
type BookPathParams = { bookId: number };
const endpoints = {
fetchBooks: {
url: '/books',
method: 'GET' as const,
},
fetchBook: {
url: '/books/:bookId',
method: 'GET' as const,
},
} as const;
interface EndpointsList {
fetchBook: Endpoint<{
response: Book;
params: BookQueryParams;
urlPathParams: BookPathParams;
}>;
fetchBooks: Endpoint<{ response: Books; params: BookQueryParams }>;
}
const api = createApiFetcher<EndpointsList>({
baseURL: 'https://example.com/api',
endpoints,
strategy: 'softFail',
});
async function main() {
// Properly typed request with URL params
const { data: book } = await api.fetchBook({
params: { newBook: true },
urlPathParams: { bookId: 1 },
});
console.log('Book:', book);
// Generic type can be passed directly for additional type safety
const { data: books } = await api.fetchBooks<{ response: Books }>({
params: { category: 'fiction' },
});
console.log('Books:', books);
}
main();