backend/lib/seed/helpers/FetchHelper.ts
2025-05-14 21:45:16 +02:00

65 lines
1.6 KiB
TypeScript

import fetch from 'node-fetch';
import querystring from 'querystring';
// convert object to a query string
export const apiCall = async (url: string, method: 'POST' | 'PUT' | 'PATCH' | 'GET' | 'DELETE', headers?: any, body?: any): Promise<any> => {
const q: any = {
method: method,
headers: {
'Content-Type': 'application/json',
},
};
if (headers) q.headers = headers;
if (body) {
if (typeof body === 'string') q.body = body;
else q.body = JSON.stringify(body);
}
const response = await fetch(url, q);
const rs = await response.json();
if (!response.ok) throw { error: rs };
return rs;
};
export const fetchCall = async (init: {
url: string;
method: 'POST' | 'PUT' | 'PATCH' | 'GET' | 'DELETE';
query?: any;
headers?: any;
body?: any;
raw?: boolean;
}): Promise<any> => {
let { url } = init;
const { method, query, headers, body, raw } = init;
const q: any = {
method: method,
headers: {
'Content-Type': 'application/json',
},
};
if (query) url = url + '?' + querystring.stringify(query, undefined, undefined, { encodeURIComponent: encodeURIComponent });
if (headers) q.headers = headers;
if (body) {
if (typeof body === 'string') q.body = body;
else q.body = JSON.stringify(body);
}
console.log('fetchCall', url);
const response = await fetch(url, q);
let rs;
try {
rs = await response.json();
} catch (error) {
rs = await response.text();
}
if (!response.ok) throw { error: rs };
return rs;
};