From dff64b31a481adc59a6eddfe50b54d5e993bdcf1 Mon Sep 17 00:00:00 2001 From: Andreas Date: Sun, 23 Jun 2024 20:00:08 +0200 Subject: [PATCH] did some reformatting --- src/app/api/attachment/route.ts | 117 ++++++++++++++++++-------------- 1 file changed, 67 insertions(+), 50 deletions(-) diff --git a/src/app/api/attachment/route.ts b/src/app/api/attachment/route.ts index 1dc217e..18507e7 100644 --- a/src/app/api/attachment/route.ts +++ b/src/app/api/attachment/route.ts @@ -8,37 +8,52 @@ import { UUID, randomUUID } from "crypto"; import { mkdir, mkdirSync, writeFile } from "fs"; import { where } from "@sequelize/core"; -async function writeFilesToBucket(uuid: UUID, files:any[]) { - const fileArray:{name:string, content:Promise>|ReadableStreamReadResult}[] = await Promise.all( files.map((file:File) => { - return {'name':( ()=>file.name)(), 'content':file.stream().getReader().read()}; + +async function writeFilesToBucket(uuid: UUID, files: any[]) { + + type FileArrayEntry = { + name:string; + content: Promise> | ReadableStreamReadResult + } + + const fileArray:FileArrayEntry[] = await Promise.all(files.map((file: File) => { + return { 'name': (() => file.name)(), 'content': file.stream().getReader().read() }; })); - let finalFileArray:{name:string,content:ReadableStreamReadResult}[] = await (async () => { - for(let file in fileArray){ + let finalFileArray: { name: string, content: ReadableStreamReadResult }[] = await (async () => { + for (let file in fileArray) { fileArray[file].content = await fileArray[file].content } - return [...fileArray as {name:string,content:ReadableStreamReadResult}[]] - })() ; - + return [...fileArray as { name: string, content: ReadableStreamReadResult }[]] + })(); + mkdirSync(`./bucket/${uuid}/`) - for(let file in finalFileArray){ - writeFile(`./bucket/${uuid}/${finalFileArray[file].name}`,Buffer.from(finalFileArray[file].content.value as Uint8Array),(e)=>{console.log(e)}) - const attachment = await Attachment.create({bucket_id:uuid, filename:finalFileArray[file].name}, {include: Attachment.associations.bucket}); + for (let file in finalFileArray) { + writeFile( + `./bucket/${uuid}/${finalFileArray[file].name}`, + Buffer.from(finalFileArray[file].content.value as Uint8Array), + (e) => { console.log(e) } + ); + const attachment = await Attachment.create( + { bucket_id: uuid, filename: finalFileArray[file].name }, + { include: Attachment.associations.bucket } + ); console.log(attachment); } } -async function addToPost(postid:number):Promise -{ +async function addToPost(postid: number): Promise { Post.sync(); - const post = await Post.findOne({where: {id:postid}}); - + const post = await Post.findOne({ where: { id: postid } }); + if (!post) throw new APIError({ status: 500, responseText: "invalid postid" }); - const bucket = await post.createBucket({id:randomUUID()}); + const bucket = await post.createBucket({ id: randomUUID() }); return bucket; } -async function addToBucket(bucketid:number):Promise { - const bucket = await Bucket.findOne({where: {id: bucketid}, include: {association: Bucket.associations.posts}}); +async function addToBucket(bucketid: number): Promise { + const bucket = await Bucket.findOne({ + where: { id: bucketid }, include: { association: Bucket.associations.posts } + }); if (!bucket) throw new APIError({ status: 500, responseText: "invalid bucketid" }); return bucket; } @@ -48,76 +63,77 @@ async function tryCreateAttachment(request: Request) { // Make sure the DB is ready await dbSync; - + // Prepare data const formData = await request.formData(); - const requestData:string | Object | undefined = formData.get('data')?.valueOf(); - const files:FormDataEntryValue[] = formData.getAll('files') + const requestData: string | Object | undefined = formData.get('data')?.valueOf(); + const files: FormDataEntryValue[] = formData.getAll('files') const authCkie = await cookies().get("auth"); - + // Sanity check auth cookie - if ( !authCkie || !authCkie.value) throw new APIError({ status: 500, responseText: "missing auth cookie" }); - + if (!authCkie || !authCkie.value) throw new APIError({ status: 500, responseText: "missing auth cookie" }); + // Get JSON from the Cookie const cookieJSON = authCkie.value; const authObject = JSON.parse(cookieJSON); - + // Fetch User Auth from the database - const auth = await Auth.findOne({ + const auth = await Auth.findOne({ include: [ - { + { model: User.withScope(['withPerms']), attributes: { exclude: ['username', 'password', 'updatedAt', 'createdAt'] } } ], - where: { token: authObject.token } + where: { token: authObject.token } }); - + // Sanity check the auth and associated user for authorization - if (!auth || !auth.user) throw new APIError({ status: 401, responseText: "Authentication Error" }); - if (!auth.user.id) throw new APIError({ status: 500, responseText: "Missing user id" }); - if (!auth.user.perms || !auth.user.perms.isAdmin) throw new APIError({ status: 401, responseText: `Unauthorized ${JSON.stringify(auth.user)}` }); + if (!auth || !auth.user) throw new APIError({ status: 401, responseText: "Authentication Error" }); + if (!auth.user.id) throw new APIError({ status: 500, responseText: "Missing user id" }); + if (!auth.user.perms || !auth.user.perms.isAdmin) + throw new APIError({ status: 401, responseText: `Unauthorized ${JSON.stringify(auth.user)}` }); // Handle incomplete data or other problems - if (!files) throw new APIError({ status: 500, responseText: "Missing file" }); - if (!formData) throw new APIError({ status: 500, responseText: "Empty request body" }); - if (!requestData) throw new APIError({ status: 500, responseText: "Missing request data" }); - if (!(typeof requestData == "string")) throw new APIError({ status: 500, responseText: "Malformed request data" }); - + if (!files) throw new APIError({ status: 500, responseText: "Missing file" }); + if (!formData) throw new APIError({ status: 500, responseText: "Empty request body" }); + if (!requestData) throw new APIError({ status: 500, responseText: "Missing request data" }); + if (!(typeof requestData == "string")) throw new APIError({ status: 500, responseText: "Malformed request data" }); + const data = JSON.parse(requestData); - let bucket:Bucket = (data.postid && !data.bucketid)? await addToPost(data.postid) : await addToBucket(data.bucketid) + let bucket:Bucket = (data.postid && !data.bucketid) ? await addToPost(data.postid) : await addToBucket(data.bucketid) writeFilesToBucket(bucket.id, files); - const bucket2 = await Bucket.findOne({where: {id: bucket.id}, include: [Bucket.associations.posts, Bucket.associations.attachments]}) + const bucket2 = await Bucket.findOne({ + where: { id: bucket.id }, + include: [Bucket.associations.posts, Bucket.associations.attachments] + }); return new Response(JSON.stringify({ bucket: bucket2 }), { status: 200 }); - } - - export async function tryFetchAttachments(request: Request) { await Post.sync(); const foundPosts = await Post.findAll({ include: [ - { - association: Post.associations.user, - attributes: { exclude: ['password', 'createdAt', 'updatedAt'] } - },{ - association: Post.associations.postTags - }] + { + association: Post.associations.user, + attributes: { exclude: ['password', 'createdAt', 'updatedAt'] } + }, { + association: Post.associations.postTags + }] }); return new Response(JSON.stringify(foundPosts), { status: 200 }); @@ -125,8 +141,9 @@ export async function tryFetchAttachments(request: Request) { } export async function GET(request: Request) { - return await attemptAPIAction(tryFetchAttachments,request); + return await attemptAPIAction(tryFetchAttachments, request); } + export async function POST(request: Request) { - return await attemptAPIAction(tryCreateAttachment,request); + return await attemptAPIAction(tryCreateAttachment, request); }