57 lines
1.2 KiB
JavaScript
57 lines
1.2 KiB
JavaScript
|
import knex from './knex.js';
|
||
|
import redis from './redis.js';
|
||
|
import initLogger from './logger.js';
|
||
|
|
||
|
const logger = initLogger();
|
||
|
|
||
|
function curateTag(tag, context) {
|
||
|
return {
|
||
|
id: tag.id,
|
||
|
name: tag.name,
|
||
|
slug: tag.slug,
|
||
|
priority: tag.priority,
|
||
|
...context.append?.[tag.id],
|
||
|
};
|
||
|
}
|
||
|
|
||
|
export async function fetchTagsById(tagIds, options = {}) {
|
||
|
const [tags] = await Promise.all([
|
||
|
knex('tags')
|
||
|
.whereIn('tags.id', tagIds)
|
||
|
.modify((builder) => {
|
||
|
if (options.order) {
|
||
|
builder.orderBy(...options.order);
|
||
|
}
|
||
|
}),
|
||
|
]);
|
||
|
|
||
|
if (options.order) {
|
||
|
return tags.map((tagEntry) => curateTag(tagEntry, { append: options.append }));
|
||
|
}
|
||
|
|
||
|
const curatedTags = tagIds.map((tagId) => {
|
||
|
const tag = tags.find((tagEntry) => tagEntry.id === tagId);
|
||
|
|
||
|
if (!tag) {
|
||
|
console.warn(`Can't match tag ${tagId}`);
|
||
|
return null;
|
||
|
}
|
||
|
|
||
|
return curateTag(tag, { append: options.append });
|
||
|
}).filter(Boolean);
|
||
|
|
||
|
return curatedTags;
|
||
|
}
|
||
|
|
||
|
export async function cacheTagIds() {
|
||
|
const tags = await knex('tags')
|
||
|
.select('id', 'slug')
|
||
|
.whereNull('alias_for')
|
||
|
.whereNotNull('slug');
|
||
|
|
||
|
await redis.del('traxxx:tags:id_by_slug');
|
||
|
await redis.hSet('traxxx:tags:id_by_slug', tags.map((tag) => [tag.slug, tag.id]));
|
||
|
|
||
|
logger.info('Cached tags IDs by slug');
|
||
|
}
|