-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathapiClient.js
More file actions
118 lines (101 loc) · 2.76 KB
/
apiClient.js
File metadata and controls
118 lines (101 loc) · 2.76 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
const fs = require("fs-extra");
const path = require("path");
const mime = require("mime");
const axios = require("axios");
const parse = require("url-parse");
const DEFAULT_SLEEP_MS = 1000;
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function getVersion(openApi) {
if ((openApi || "").includes("/v2")) return "/v2";
return "/v1";
}
function getRequestUrl(openApi, requestPath) {
const { origin } = parse(openApi || "");
return `${origin}${requestPath}`;
}
function extractMemoName(responseData) {
return responseData?.data?.name || responseData?.data?.data?.name;
}
function createApiClient(options) {
const { openApi, accessToken, sleepMs = DEFAULT_SLEEP_MS } = options;
if (!openApi) {
throw new Error("openApi is required");
}
if (!accessToken) {
throw new Error("accessToken is required");
}
const version = getVersion(openApi);
const headers = {
Authorization: `Bearer ${accessToken}`,
};
return {
async uploadFile(filePath) {
const readFile = fs.readFileSync(filePath);
const response = await axios({
method: "post",
url: getRequestUrl(openApi, `/api${version}/resources`),
data: {
content: readFile.toString("base64"),
filename: path.basename(filePath),
type: mime.getType(filePath) || undefined,
},
headers,
});
return response.data;
},
async sendMemo(memo) {
const response = await axios({
method: "post",
url: getRequestUrl(openApi, `/api${version}/memos`),
data: memo,
headers: {
...headers,
"Content-Type": "application/json; charset=UTF-8",
},
});
await sleep(sleepMs);
return response;
},
async updateMemo(memoName, createTime) {
return axios({
method: "patch",
url: getRequestUrl(openApi, `/api${version}/${memoName}`),
data: { createTime },
headers: {
...headers,
"Content-Type": "application/json; charset=UTF-8",
},
});
},
async setMemoResources(memoName, resources) {
return axios({
method: "patch",
url: getRequestUrl(openApi, `/api${version}/${memoName}/resources`),
data: {
resources,
},
headers: {
...headers,
"Content-Type": "application/json; charset=UTF-8",
},
});
},
async deleteMemo(memoName) {
return axios({
method: "delete",
url: getRequestUrl(openApi, `/api${version}/${memoName}`),
headers: {
...headers,
"Content-Type": "application/json; charset=UTF-8",
},
});
},
extractMemoName,
};
}
module.exports = {
createApiClient,
extractMemoName,
};