Spaces:
Sleeping
Sleeping
File size: 1,853 Bytes
c3e8f3d 26c4b30 d0a1b70 c3e8f3d d0a1b70 f80b091 c3e8f3d 26c4b30 5b99fc6 26c4b30 c3e8f3d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
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,
});
}
}
|