From d2760bc706b9b4d3eda1c518f362a3e64b8ea281 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 11 Sep 2023 17:49:38 -0500 Subject: [PATCH] media: refactor upload code into a separate module --- src/controllers/api/media.ts | 28 ++++------------------------ src/upload.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 24 deletions(-) create mode 100644 src/upload.ts diff --git a/src/controllers/api/media.ts b/src/controllers/api/media.ts index 1e310e1..a7edef1 100644 --- a/src/controllers/api/media.ts +++ b/src/controllers/api/media.ts @@ -1,19 +1,13 @@ import { AppController } from '@/app.ts'; -import { Conf } from '@/config.ts'; -import { insertUnattachedMedia } from '@/db/unattached-media.ts'; import { z } from '@/deps.ts'; import { fileSchema } from '@/schema.ts'; -import { configUploader as uploader } from '@/uploaders/config.ts'; import { parseBody } from '@/utils/web.ts'; import { renderAttachment } from '@/views/attachment.ts'; - -const uploadSchema = fileSchema - .refine((file) => !!file.type, 'File type is required.') - .refine((file) => file.size <= Conf.maxUploadSize, 'File size is too large.'); +import { uploadFile } from '@/upload.ts'; const mediaBodySchema = z.object({ - file: uploadSchema, - thumbnail: uploadSchema.optional(), + file: fileSchema, + thumbnail: fileSchema.optional(), description: z.string().optional(), focus: z.string().optional(), }); @@ -27,21 +21,7 @@ const mediaController: AppController = async (c) => { try { const { file, description } = result.data; - const { cid } = await uploader.upload(file); - - const url = new URL(`/ipfs/${cid}`, Conf.mediaDomain).toString(); - - const media = await insertUnattachedMedia({ - pubkey: c.get('pubkey')!, - url, - data: { - name: file.name, - mime: file.type, - size: file.size, - description, - }, - }); - + const media = await uploadFile(file, { pubkey: c.get('pubkey')!, description }); return c.json(renderAttachment(media)); } catch (e) { console.error(e); diff --git a/src/upload.ts b/src/upload.ts new file mode 100644 index 0000000..d8ea969 --- /dev/null +++ b/src/upload.ts @@ -0,0 +1,34 @@ +import { Conf } from '@/config.ts'; +import { insertUnattachedMedia } from '@/db/unattached-media.ts'; +import { configUploader as uploader } from '@/uploaders/config.ts'; + +interface FileMeta { + pubkey: string; + description?: string; +} + +/** Upload a file, track it in the database, and return the resulting media object. */ +async function uploadFile(file: File, meta: FileMeta) { + const { name, type, size } = file; + const { pubkey, description } = meta; + + if (file.size > Conf.maxUploadSize) { + throw new Error('File size is too large.'); + } + + const { cid } = await uploader.upload(file); + const url = new URL(`/ipfs/${cid}`, Conf.mediaDomain).toString(); + + return insertUnattachedMedia({ + pubkey, + url, + data: { + name, + size, + description, + mime: type, + }, + }); +} + +export { uploadFile };