This repository was archived by the owner on Feb 10, 2023. It is now read-only.
forked from Himenon/openapi-typescript-code-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsample-axios.ts
66 lines (60 loc) · 1.58 KB
/
sample-axios.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import * as axios from "axios";
import { ApiClient, Client, HttpMethod, ObjectLike, QueryParameters } from "./client";
import { generateQueryString } from "./utils";
export interface RequestOption {
retries?: number;
timeout?: number;
deadline?: number;
}
const convertHttpMethodToAxiosMethod = (httpMethod: HttpMethod): axios.Method => {
const patterns: { [key in HttpMethod]: axios.Method } = {
GET: "GET",
PUT: "PUT",
POST: "POST",
DELETE: "DELETE",
OPTIONS: "OPTIONS",
HEAD: "HEAD",
PATCH: "PATCH",
TRACE: "POST", // ?
};
return patterns[httpMethod];
};
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 axios.default.request({
url: requestUrl,
method: convertHttpMethodToAxiosMethod(httpMethod),
headers,
data: requestBody,
timeout: options?.timeout,
});
return response.data;
},
};
const main = async () => {
const client = new Client<RequestOption>(apiClientImpl, "https://example.com");
await client.getBooks({
retries: 50,
});
await client.searchBooks({
parameter: {
filter: {
title: "hoge",
author: "fuga",
},
},
});
};
main().catch(error => {
console.error(error);
process.exit(1);
});