MingruiZhang's picture
Minor things: revalidate cache, table css, card title (#16)
973f0d8 unverified
raw
history blame
1.76 kB
import { auth } from '@/auth';
import { upload } from '@/lib/aws';
import { createKVChat } from '@/lib/kv/chat';
import { ChatEntity, MessageBase } from '@/lib/types';
import { nanoid } from '@/lib/utils';
import { revalidatePath } from 'next/cache';
/**
* 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 user = session?.user?.email ?? 'anonymous';
// 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 = `${user}/${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,
messages: initMessages ?? [],
};
await createKVChat(payload);
revalidatePath('/chat', 'layout');
return Response.json(payload);
} catch (error) {
return new Response((error as Error).message, {
status: 400,
});
}
}