diff --git a/src/database.ts b/src/database.ts index ebe9031..7e0a9e6 100644 --- a/src/database.ts +++ b/src/database.ts @@ -2,7 +2,7 @@ import mongoose, { Schema } from "mongoose"; import { RoleValidator, RoleSchema } from "./services/auth/auth-schema"; import { EventSchema, EventValidator } from "./services/events/events-schema"; import { - SubscriptionValidator, + SubscriptionSchemaValidator, SubscriptionSchema, } from "./services/subscription/subscription-schema"; @@ -38,9 +38,9 @@ function initializeModel( export const Database = { ROLES: initializeModel("roles", RoleSchema, RoleValidator), EVENTS: initializeModel("events", EventSchema, EventValidator), - SUBSCRIPTION: initializeModel( - "subscription", + SUBSCRIPTIONS: initializeModel( + "subscriptions", SubscriptionSchema, - SubscriptionValidator + SubscriptionSchemaValidator ), }; diff --git a/src/services/subscription/subscription-router.ts b/src/services/subscription/subscription-router.ts index b503fbe..e8b7a5f 100644 --- a/src/services/subscription/subscription-router.ts +++ b/src/services/subscription/subscription-router.ts @@ -8,8 +8,11 @@ const subscriptionRouter = Router(); // Create a new subscription subscriptionRouter.post("/", async (req, res, next) => { try { + // Validate the incoming user subscription const subscriptionData = SubscriptionValidator.parse(req.body); - await Database.SUBSCRIPTION.findOneAndUpdate( + + // Upsert the user info into the corresponding Subscription collection + await Database.SUBSCRIPTIONS.findOneAndUpdate( { mailingList: subscriptionData.mailingList }, { $push: { subscriptions: subscriptionData.email } }, { upsert: true, new: true } diff --git a/src/services/subscription/subscription-schema.ts b/src/services/subscription/subscription-schema.ts index 32579bf..63a2fcf 100644 --- a/src/services/subscription/subscription-schema.ts +++ b/src/services/subscription/subscription-schema.ts @@ -2,16 +2,26 @@ import mongoose from "mongoose"; import { z } from "zod"; import { MailingListName } from "../../config"; -// Zod schema for subscription +// Zod schema for incoming user subscriptions const SubscriptionValidator = z.object({ email: z.string().email(), mailingList: MailingListName, }); +// Zod schema for validating subscription lists +const SubscriptionSchemaValidator = z.object({ + mailingList: MailingListName, + subscriptions: z.array(z.string().email()), +}); + // Mongoose schema for subscription const SubscriptionSchema = new mongoose.Schema({ - email: { type: String, required: true }, mailingList: { type: String, required: true }, + subscriptions: [{ type: String, required: true }], }); -export { SubscriptionValidator, SubscriptionSchema }; +export { + SubscriptionValidator, + SubscriptionSchemaValidator, + SubscriptionSchema, +};