75 lines
1.6 KiB
JavaScript
75 lines
1.6 KiB
JavaScript
import { createCache } from '$lib/cache.server';
|
|
import { cacheUpdater, cachedMethod } from './root';
|
|
|
|
const cache = createCache();
|
|
|
|
/**
|
|
* @template T
|
|
* @typedef {import('$types/base').Result<T>} Result<T>
|
|
*/
|
|
|
|
/**
|
|
* @typedef {import('$types/base').Category} Category
|
|
*/
|
|
|
|
/**
|
|
* @param {Result<Category>} categories
|
|
* @returns {Result<Category>}
|
|
*/
|
|
const updateCategoryCache = cacheUpdater(cache);
|
|
|
|
/**
|
|
* @param {import('postgres').Sql} sql
|
|
* @param {number[]} user_ids
|
|
* @returns {Promise<Result<Category>>}
|
|
*/
|
|
export const getCategoriesCached = cachedMethod(cache, getCategories);
|
|
|
|
/**
|
|
* @param {import('postgres').Sql} sql
|
|
* @param {number[]} category_ids
|
|
* @returns {Promise<Result<Category>>}
|
|
*/
|
|
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<Category>}
|
|
*/
|
|
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<Category | import('$types/error').Error>}
|
|
*/
|
|
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];
|
|
} |