media: refactor upload code into a separate module
This commit is contained in:
parent
55d5197136
commit
d2760bc706
|
@ -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);
|
||||
|
|
|
@ -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 };
|
Loading…
Reference in New Issue