import { createCache } from '$lib/cache.server'; import { cacheUpdater, cachedMethod } from './root'; const cache = createCache(); /** * @template T * @typedef {import('$types/base').Result} Result */ /** * @typedef {import('$types/base').Category} Category */ /** * @param {Result} categories * @returns {Result} */ const updateCategoryCache = cacheUpdater(cache); /** * @param {import('postgres').Sql} sql * @param {number[]} user_ids * @returns {Promise>} */ export const getCategoriesCached = cachedMethod(cache, getCategories); /** * @param {import('postgres').Sql} sql * @param {number[]} category_ids * @returns {Promise>} */ export async function getCategories(sql, category_ids) { if (category_ids.length == 0) return {}; const query = sql` SELECT id, name FROM doki8902.post_category WHERE id IN ${ sql(category_ids) };`; let categories = await query; /** * @type {Result} */ let result = {}; categories.forEach(row => { result[row['id']] = { id: row['id'], name: row['name'] } }) return updateCategoryCache(result); } /** * * @param {import('postgres').Sql} sql * @param {number} category_id * @returns {Promise} */ export async function getCategoryCached(sql, category_id) { const categories = await getCategoriesCached(sql, [category_id]); if (Object.keys(categories).length == 0) { return { error: true, msg: `Could not find Category of ID ${category_id}` }; } return categories[category_id]; }