UNPKG

@rocketmakers/api-swr

Version:

Rocketmakers front-end library for parsing a generated Typescript API client into a set of configurable React hooks for fetching and mutating data.

52 lines (51 loc) 2.46 kB
"use strict"; /** * Utility functions for caching. * -------------------------------------- * These functions are designed to facilitate param driven caching */ Object.defineProperty(exports, "__esModule", { value: true }); exports.readCacheKey = exports.cacheKeyConcat = void 0; /** * Concatenates a cache key string from an array of string arguments. * @param {...(string | undefined)} args - An array of string arguments. * @returns {string} - The concatenated cache key string. */ const cacheKeyConcat = (...args) => { return args.filter((arg) => !!arg).join('.'); }; exports.cacheKeyConcat = cacheKeyConcat; /** * Returns the final concatenated cache key for an API call by unwrapping the defined cache key. * NOTE: If any of the cache key params are falsy, this function will return undefined so that the API call is held back until all the cache key params are ready * @param {string} [endpointId] - The ID of the API endpoint. * @param {CacheKey<TArgs>} [cacheKey] - The cache key, which can be a string, an array of strings, or a function that receives the params and returns the built cache key. * @param {TArgs} [params] - The parameters for the API call. * @returns {string|undefined} - The final concatenated cache key, or undefined if the cache key params are not all present. */ const readCacheKey = (endpointId, cacheKey, params) => { var _a; switch (typeof cacheKey) { case 'function': const funcResult = cacheKey(params); if (!funcResult) { return undefined; } return (0, exports.cacheKeyConcat)(endpointId, funcResult); case 'string': const lookupResult = `${(_a = params === null || params === void 0 ? void 0 : params[cacheKey]) !== null && _a !== void 0 ? _a : ''}`; if (!lookupResult) { return undefined; } return (0, exports.cacheKeyConcat)(endpointId, lookupResult); case 'object': if (Array.isArray(cacheKey)) { const lookupResults = cacheKey.map((key) => { var _a; return `${(_a = params === null || params === void 0 ? void 0 : params[key]) !== null && _a !== void 0 ? _a : ''}`; }).filter((key) => !!key); return (0, exports.cacheKeyConcat)(endpointId, ...lookupResults); } return undefined; default: return endpointId; } }; exports.readCacheKey = readCacheKey;