-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathload-api-json.js
More file actions
40 lines (31 loc) · 963 Bytes
/
load-api-json.js
File metadata and controls
40 lines (31 loc) · 963 Bytes
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
const path = require("path");
const getIsUrl = require("is-url");
const fetch = require("node-fetch");
const { readFileSync } = require("fs");
const { contentToJson } = require("../lib/content-to-json");
async function loadApiJson(config) {
if (config.apiJson) {
return config.apiJson;
}
const isUrl = getIsUrl(config.file);
// By url
if (isUrl) {
return fetchApi(config);
}
// By local file
const apiPath = path.resolve(process.cwd(), config.file);
return contentToJson(apiPath, () => readFileSync(apiPath, "utf8"));
}
function fetchApi(config) {
return fetch(config.file, {
headers: { authorization: config.authorization },
})
.then((response) => {
if (response.status === 401) {
throw new Error("Unable to get file. Specify authorization settings.");
}
return response.text();
})
.then((content) => contentToJson(config.file, () => content));
}
module.exports = { loadApiJson };