generated from Himenon/template-js
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsample-fetch.ts
49 lines (44 loc) · 1.18 KB
/
sample-fetch.ts
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
import fetch from "node-fetch";
import { ApiClient, Client, HttpMethod, ObjectLike, QueryParameters } from "./client";
import { generateQueryString } from "./utils";
export interface RequestOption {
timeout?: number;
}
const apiClientImpl: ApiClient<RequestOption> = {
request: async (
httpMethod: HttpMethod,
url: string,
headers: ObjectLike | any,
requestBody: ObjectLike | any,
queryParameters: QueryParameters | undefined,
options?: RequestOption,
): Promise<any> => {
const query = generateQueryString(queryParameters);
const requestUrl = query ? url + "?" + encodeURI(query) : url;
const response = await fetch(requestUrl, {
body: JSON.stringify(requestBody),
headers,
method: httpMethod,
timeout: options?.timeout,
});
return await response.json();
},
};
const main = async () => {
const client = new Client<RequestOption>(apiClientImpl, "https://example.com");
await client.getBooks({
timeout: 1000,
});
await client.searchBooks({
parameter: {
filter: {
title: "hoge",
author: "fuga",
},
},
});
};
main().catch(error => {
console.error(error);
process.exit(1);
});