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 => { 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 => { 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; };