UNPKG

@remcostoeten/fync

Version:

Unified TypeScript library for 9 popular APIs with consistent functional architecture

47 lines 1.96 kB
function interpolatePath(template, params) { let path = template; const queryParams = {}; Object.entries(params).forEach(function ([key, value]) { const placeholder = `{${key}}`; if (path.includes(placeholder)) { path = path.replace(placeholder, encodeURIComponent(String(value))); } else { queryParams[key] = value; } }); return { path, queryParams }; } export function createFyncResource(config, apiClient) { const resource = {}; Object.entries(config.methods).forEach(function ([methodName, definition]) { const fullPath = config.basePath ? `${config.basePath}${definition.path}` : definition.path; function createMethod() { if (definition.method === "POST" || definition.method === "PUT" || definition.method === "PATCH") { return async function (data, options) { const { path, queryParams } = interpolatePath(fullPath, options || {}); const response = await apiClient[(definition.method || "GET").toLowerCase()](path, data, { params: queryParams }); return definition.transform ? definition.transform(response) : response; }; } return async function (options) { const { path, queryParams } = interpolatePath(fullPath, options || {}); const method = definition.method || "GET"; const response = await apiClient[method.toLowerCase()](path, { params: queryParams }); return definition.transform ? definition.transform(response) : response; }; } resource[methodName] = createMethod(); }); return resource; } export function defineResource(config) { return config; } //# sourceMappingURL=resource-factory.js.map