Skip to content

Commit

Permalink
feat: Add email subscription check before saving
Browse files Browse the repository at this point in the history
This commit adds a check to ensure that the email being subscribed is not already present in the database. If the email is already subscribed, an error is thrown. This enhancement improves the data integrity and prevents duplicate email subscriptions.
  • Loading branch information
taciturnaxolotl committed May 7, 2024
1 parent 081f7cb commit d0ece74
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/pages/api/subscribe.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { APIRoute } from 'astro';
import { db, Subscribers } from 'astro:db';
import { db, like, Subscribers } from 'astro:db';

import arcjet, { validateEmail } from "@arcjet/node";
import type { ArcjetNodeRequest } from "@arcjet/node";
Expand Down Expand Up @@ -40,8 +40,6 @@ export const POST: APIRoute = async ({ params, request }) => {
email: json.email,
});

console.log("Arcjet decision", decision);

if (decision.isDenied()) {
return new Response(JSON.stringify({ ok: false, reason: decision.reason }), {
status: 400,
Expand All @@ -50,6 +48,13 @@ export const POST: APIRoute = async ({ params, request }) => {
}
});
} else {
// check if the email is already subscribed
const existing = await db.select().from(Subscribers).where(like(Subscribers.email, json.email));

if (existing.length > 0) {
throw new Error("Email already subscribed");
}

// Save the email to the database
await db.insert(Subscribers).values({
name: json.name,
Expand Down

0 comments on commit d0ece74

Please sign in to comment.