@remcostoeten/fync
Version:
Unified TypeScript library for 9 popular APIs with consistent functional architecture
59 lines (58 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createFyncResource = createFyncResource;
exports.defineResource = defineResource;
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
};
}
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;
}
function defineResource(config) {
return config;
}