UNPKG

replicate-api

Version:

A typed client library for the replicate.com API

35 lines (34 loc) 1.4 kB
// webpackIgnore: true const nodeFetch = "node-fetch"; const defaultFetch = typeof fetch !== "undefined" ? fetch : typeof self === "undefined" ? // eslint-disable-next-line import/no-unresolved import(/* webpackIgnore: true */ nodeFetch).then(module => module.default).catch(() => undefined) : undefined; export async function makeApiRequest({ fetch: passedFetchFunction, token, apiUrl = "https://api.replicate.com/v1/" }, method, endpoint, content) { const url = `${apiUrl}${endpoint}`; const body = method === "POST" && content ? JSON.stringify(content) : null; const fetchFunctionOrPromise = passedFetchFunction || defaultFetch; const fetchFunction = await fetchFunctionOrPromise; if (!fetchFunction) { throw new Error("fetch is not available. Use node >= 18 or install node-fetch"); } const response = await fetchFunction(url, { method, body, headers: { "Authorization": `Token ${token}`, "Content-Type": "application/json", }, }); const responseJson = await response.json(); if (!response.ok) { const detail = responseJson.detail; if (typeof detail === "string") { throw new Error(detail); } throw new Error(`Request failed (${response.status}): ${JSON.stringify(responseJson)}`); } return responseJson; }