Files
memestream/src/memes.ts
T

74 lines
2.1 KiB
TypeScript

import type { PrismaClient, Attachment, Meme } from '@prisma/client';
import type { Meilisearch } from 'meilisearch';
import type { Logger } from 'pino';
import * as attachments from './attachments'
const STORAGE_BUCKET = process.env.STORAGE_BUCKET
function memeUrl(a: Attachment) {
const STORAGE_URL = process.env.STORAGE_URL
const u = new URL(`${STORAGE_BUCKET}/${attachments.objectName(a)}`, `https://${STORAGE_URL}`)
return u.href
}
export default async function memeService(baseLog: Logger, prisma: PrismaClient, meili: Meilisearch) {
const log = baseLog.child({ service: 'meme' })
function fromAttachment(a: Attachment) {
const text = a.vision.fullTextAnnotation?.text || ''
const tags = [
a.guild.name,
a.channel.name,
a.message.author.username,
]
const m: Meme = {
id: a.memeId,
url: memeUrl(a),
text,
tags: tags,
attachmentId: a.id,
createdAt: undefined,
updatedAt: undefined
}
return m
}
async function ensureMeiliIndex() {
const delTask = await meili.deleteIndex('memes')
const delResult = await meili.waitForTask(delTask.taskUid)
const task = await meili.createIndex('memes', { primaryKey: 'id' })
const result = await meili.waitForTask(task.taskUid)
log.debug(result);
return meili.index('memes')
}
async function updateMeili() {
await ensureMeiliIndex();
const index = meili.index('memes')
const memes = await prisma.meme.findMany();
const task = await index.updateDocuments(memes)
const res = await meili.waitForTask(task.taskUid)
log.debug(res)
}
async function addToIndex(memes: Meme[]) {
const index = meili.index('memes')
return index.updateDocuments(memes)
}
await ensureMeiliIndex();
await updateMeili();
return {
ensureMeiliIndex,
updateMeili,
fromAttachment,
addToIndex,
}
}
export type MemeService = Awaited<ReturnType<typeof memeService>>