mirror of
https://github.com/jdalrymple/gitbeaker.git
synced 2026-01-25 16:04:01 +00:00
decamelizeKeys is defined to return Object, but Typescript 3.5.1 is a bit stricter about Object and indexing properties. The correct fix would need to be done in the type definition of humps.
79 lines
2.0 KiB
TypeScript
79 lines
2.0 KiB
TypeScript
import Ky from 'ky-universal';
|
|
import { decamelizeKeys } from 'humps';
|
|
import { stringify } from 'query-string';
|
|
import { skipAllCaps } from './Utils';
|
|
import { Requester } from '.';
|
|
|
|
const methods = ['get', 'post', 'put', 'delete', 'stream'];
|
|
const KyRequester = {} as Requester;
|
|
|
|
function responseHeadersAsObject(response) {
|
|
const headers = {};
|
|
const keyVals = [...response.headers.entries()];
|
|
|
|
keyVals.forEach(([key, val]) => {
|
|
headers[key] = val;
|
|
});
|
|
|
|
return headers;
|
|
}
|
|
|
|
function defaultRequest(service: any, { body, query, sudo, method }) {
|
|
const headers = new Headers(service.headers);
|
|
|
|
if (sudo) headers.append('sudo', `${sudo}`);
|
|
|
|
return {
|
|
timeout: service.requestTimeout,
|
|
headers,
|
|
method: (method === 'stream') ? 'get' : method,
|
|
onProgress: (method === 'stream') ? () => {} : undefined,
|
|
searchParams: stringify(decamelizeKeys(query || {}) as any, { arrayFormat: 'bracket' }),
|
|
prefixUrl: service.url,
|
|
json: typeof body === 'object' ? decamelizeKeys(body, skipAllCaps) : body,
|
|
rejectUnauthorized: service.rejectUnauthorized,
|
|
}
|
|
}
|
|
|
|
async function processBody(response) {
|
|
const contentType = response.headers.get('content-type') || '';
|
|
const content = await response.text();
|
|
|
|
if(contentType.includes('json')) {
|
|
try {
|
|
return JSON.parse(content || "{}");
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
return content;
|
|
}
|
|
|
|
methods.forEach(m => {
|
|
KyRequester[m] = async function(service, endpoint, options) {
|
|
const requestOptions = defaultRequest(service, { ...options, method: m });
|
|
let response;
|
|
|
|
try {
|
|
response = await Ky(endpoint, requestOptions);
|
|
} catch (e) {
|
|
if (e.response) {
|
|
const output = await e.response.json();
|
|
|
|
e.description = output.error || output.message;
|
|
}
|
|
|
|
throw e;
|
|
}
|
|
|
|
const { status } = response;
|
|
const headers = responseHeadersAsObject(response);
|
|
const body = await processBody(response);
|
|
|
|
return { body, headers, status };
|
|
};
|
|
});
|
|
|
|
export { KyRequester };
|