KV to D1 migration (this is totally gonna break something)

This commit is contained in:
2024-05-12 01:25:46 -04:00
parent a2b3391bda
commit e00b7e8c55
24 changed files with 1835 additions and 669 deletions

View File

@ -5,15 +5,18 @@ import { sendPushNotification } from "../../../gcloud.js";
export async function onRequestPost(context: RequestContext) {
const reportId = context.params.id as string;
const reportData: (ReportCardProps & { fcm_token?: string }) | null =
await context.env.DATA.get(`report_${reportId}`, { type: "json" });
const report: {
[k: string]: any;
} | null = await context.env.D1.prepare("SELECT * FROM reports WHERE id = ?")
.bind(reportId)
.first();
if (!reportData) return jsonError("Report does not exist", 404);
if (!report) return jsonError("Report does not exist", 404);
const actionMap = context.data.body;
const newActions: { [k: string]: { BanType: number } } = {};
const logMap: { [k: string]: number } = {};
const { user } = reportData as ReportCardProps & { user?: { email: string } };
const user = JSON.parse(report.user);
for (const [user, action] of Object.entries(actionMap)) {
if (
@ -64,35 +67,44 @@ export async function onRequestPost(context: RequestContext) {
await setBanList(context, Object.assign(banList, newActions));
}
reportData.open = false;
const pushNotificationData: Record<string, string> | null =
await context.env.D1.prepare(
"SELECT token FROM push_notifications WHERE event_id = ? AND event_type = 'report';",
)
.bind(reportId)
.first();
if (user?.email && !reportData.fcm_token)
if (user?.email)
await sendEmail(
user.email,
user?.email,
context.env.MAILGUN_API_KEY,
"Report Processed",
"report_processed",
{
username: reportData.user?.username as string,
username: report.user?.username as string,
},
);
else if (reportData.fcm_token)
else if (pushNotificationData)
await sendPushNotification(
context.env,
"Report Processed",
`Your report for ${reportData.target_usernames.toString()} has been reviewed.`,
reportData.fcm_token,
`Your report for ${JSON.parse(report.target_usernames).toString()} has been reviewed.`,
pushNotificationData.token,
);
delete reportData.fcm_token;
delete (reportData.user as { email?: string; id: string; username: string })
delete (report.user as { email?: string; id: string; username: string })
?.email;
await context.env.DATA.put(`report_${reportId}`, JSON.stringify(reportData));
await context.env.D1.prepare("UPDATE reports SET open = 0 WHERE id = ?;")
.bind(reportId)
.run();
await context.env.D1.prepare(
"DELETE FROM push_notifications WHERE event_id = ? AND event_type = 'report';",
)
.bind(reportId)
.run();
return new Response(null, {
status: 204,
});