UNPKG

@platform/http

Version:
77 lines (76 loc) 2.36 kB
import { id, time, util, value } from '../common'; export const fetcher = async (args) => { const timer = time.timer(); const uid = `req:${id.shortid()}`; const { url, method, data, fire, mode, headers } = args; const modifications = { headers: args.headers || {}, data: undefined, respond: undefined, }; const modify = { header(key, value) { before.isModified = true; const headers = modifications.headers || {}; if (value) { headers[key] = value; } else { delete headers[key]; } modifications.headers = headers; }, headers: { merge(input) { before.isModified = true; modifications.headers = value.deleteEmpty(Object.assign(Object.assign({}, modifications.headers), input)); }, replace(input) { before.isModified = true; modifications.headers = value.deleteEmpty(input); }, }, }; const before = { uid, method, url, data, headers, isModified: false, modify, respond(input) { modifications.respond = input; }, }; fire({ type: 'HTTP/before', payload: before }); if (modifications.respond) { const respond = modifications.respond; const payload = typeof respond === 'function' ? await respond() : respond; const response = await util.response.fromPayload(payload, modifications); const elapsed = timer.elapsed; const { ok, status } = response; fire({ type: 'HTTP/after', payload: { uid, method, url, ok, status, response, elapsed }, }); return response; } else { const fetched = await args.fetch({ url, mode, method, headers: modifications.headers || headers, data, }); const response = await util.response.fromFetch(fetched); const elapsed = timer.elapsed; const { ok, status } = response; fire({ type: 'HTTP/after', payload: { uid, method, url, ok, status, response, elapsed }, }); return response; } };