@hokuto/jam-node
Version:
JAM Node TS, guardians and utils
100 lines (99 loc) • 3.26 kB
JavaScript
import fetch from "node-fetch";
import { ApiMethod } from "../types.js";
import { BlobContentType, FetchContentType } from "@hokuto/jam-core";
export function apiFetch(input, init = {}) {
return new Promise((resolve, reject) => {
return fetch(input, init)
.then((res) => {
return res.ok ? resolve(res) : Promise.reject(res);
}, (rej) => {
return Promise.reject(rej);
})
.catch((rej) => {
if (rej instanceof Error)
return reject(rej);
return rej.text().then((text) => {
const cause = {
status: rej.status,
text,
};
return reject(new Error(`could not request data from ${input}`, { cause }));
});
});
});
}
export function apiProps(url, options = {}) {
const { method = ApiMethod.Get, params, headers = {} } = options;
let { body } = options;
let qs;
switch (method) {
case ApiMethod.Get:
qs =
params &&
new URLSearchParams(Object.keys(params).reduce((prev, curr) => {
return { ...prev, [curr]: String(params[curr]) };
}, {}));
break;
default:
if (params)
body = JSON.stringify(params);
}
url = `${url}${qs ? "?" + qs.toString() : ""}`;
return { url, headers, method, body };
}
export function jsonFetch(baseurl, options = {}) {
const { headers, url, method, body } = apiProps(baseurl, options);
return apiFetch(url, {
method,
body,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
...headers,
},
})
.then((res) => {
if (res.ok)
return res.json();
return res.text().then((err) => Promise.reject(new Error(err)));
})
.then((data) => {
return Promise.resolve(data);
}, (err) => {
return Promise.reject(err);
});
}
export function uploadFetch(baseurl, options = {}, contentType = FetchContentType.Json) {
const { headers, url, method, body } = apiProps(baseurl, options);
return apiFetch(url, {
method,
body,
headers,
})
.then((res) => {
if (res.ok)
return contentType === FetchContentType.Json ? res.json() : res.text();
return res.text().then((err) => Promise.reject(new Error(err)));
})
.then((data) => {
return Promise.resolve(data);
}, (err) => Promise.reject(err));
}
export function blobFetch(baseurl, options = {}, contentType = BlobContentType.Json) {
const { headers, url, method, body } = apiProps(baseurl, options);
return apiFetch(url, {
method,
body,
headers: {
"Content-Type": contentType,
Accept: BlobContentType.Json,
...headers,
},
}).then((res) => res.blob());
}
export function pngFetch(baseurl, options = {}) {
return blobFetch(baseurl, options, BlobContentType.Image);
}
export function svgFetch(baseurl, options = {}) {
return blobFetch(baseurl, options, BlobContentType.Svg);
}