Aggregating channels, filter inoperable.

This commit is contained in:
2024-01-09 02:26:32 +01:00
parent 58f7ca0d89
commit d242eb3b73
17 changed files with 381 additions and 68 deletions

63
src/entities.js Normal file
View File

@@ -0,0 +1,63 @@
import knex from './knex.js';
import redis from './redis.js';
import initLogger from './logger.js';
const logger = initLogger();
function curateEntity(entity, context) {
if (!entity) {
return null;
}
return {
id: entity.id,
name: entity.name,
slug: entity.slug,
type: entity.type,
isIndependent: entity.independent,
hasLogo: entity.has_logo,
parent: curateEntity(entity.parent, context),
...context?.append?.[entity.id],
};
}
export async function fetchEntitiesById(entityIds, options = {}) {
const [entities] = await Promise.all([
knex('entities')
.select('entities.*', knex.raw('row_to_json(parents) as parent'))
.whereIn('entities.id', entityIds)
.leftJoin('entities as parents', 'parents.id', 'entities.parent_id')
.modify((builder) => {
if (options.order) {
builder.orderBy(...options.order);
}
})
.groupBy('entities.id', 'parents.id'),
]);
if (options.order) {
return entities.map((entityEntry) => curateEntity(entityEntry, { append: options.append }));
}
const curatedEntities = entityIds.map((entityId) => {
const entity = entities.find((entityEntry) => entityEntry.id === entityId);
if (!entity) {
console.warn(`Can't match entity ${entityId}`);
return null;
}
return curateEntity(entity, { append: options.append });
}).filter(Boolean);
return curatedEntities;
}
export async function cacheEntityIds() {
const entities = await knex('entities').select('id', 'slug', 'type');
await redis.del('traxxx:entities:id_by_slug');
await redis.hSet('traxxx:entities:id_by_slug', entities.map((entity) => [entity.type === 'network' ? `_${entity.slug}` : entity.slug, entity.id]));
logger.info('Cached entity IDs by slug');
}