Spaces:
Sleeping
Sleeping
import { auth } from '@/auth'; | |
import { upload } from '@/lib/aws'; | |
import { ChatEntity, MessageBase } from '@/lib/types'; | |
import { nanoid } from '@/lib/utils'; | |
import { kv } from '@vercel/kv'; | |
/** | |
* TODO: this should be replaced with actual upload to S3 | |
* @param req | |
* @returns | |
*/ | |
export async function POST(req: Request): Promise<Response> { | |
const session = await auth(); | |
const email = session?.user?.email; | |
if (!email) { | |
return new Response('Unauthorized', { | |
status: 401, | |
}); | |
} | |
try { | |
const { url, base64, initMessages, fileType } = (await req.json()) as { | |
url?: string; | |
file?: File; | |
base64?: string; | |
fileType?: string; | |
initMessages?: MessageBase[]; | |
}; | |
if (!url && !base64) { | |
return new Response('Missing both url and base64 in payload', { | |
status: 400, | |
}); | |
} | |
const id = nanoid(); | |
let urlToSave = url; | |
if (base64) { | |
const fileName = `${email}/${id}/${Date.now()}-image.jpg`; | |
const res = await upload(base64, fileName, fileType ?? 'image/png'); | |
if (res.ok) { | |
console.log('Image uploaded successfully'); | |
urlToSave = `https://${process.env.AWS_BUCKET_NAME}.s3.${process.env.AWS_REGION}.amazonaws.com/${fileName}`; | |
} else { | |
return res; | |
} | |
} | |
const payload: ChatEntity = { | |
url: urlToSave!, // TODO can be uploaded as well | |
id, | |
user: email, | |
messages: initMessages ?? [], | |
}; | |
await kv.hmset(`chat:${id}`, payload); | |
await kv.zadd(`user:chat:${email}`, { | |
score: Date.now(), | |
member: `chat:${id}`, | |
}); | |
await kv.zadd('user:chat:all', { | |
score: Date.now(), | |
member: `chat:${id}`, | |
}); | |
return Response.json(payload); | |
} catch (error) { | |
return new Response((error as Error).message, { | |
status: 400, | |
}); | |
} | |
} | |