UNPKG

waitlist-mailer

Version:

Modern, modular TypeScript library for managing waitlists with pluggable storage and mail providers. Supports MongoDB, SQL databases, and custom adapters with zero required dependencies for basic usage.

105 lines (103 loc) 3.06 kB
// lib/adapters/storage/MongooseStorage.ts var MongooseStorage = class { /** * Create a new MongooseStorage instance. * @param config - Configuration object with mongoose model * @throws {Error} If mongoose is not installed or model is invalid */ constructor(config) { try { if (!config.model) { throw new Error("Mongoose model is required. Please provide a valid Mongoose model instance."); } if (!config.model.collection) { throw new Error("Invalid Mongoose model. Make sure you're passing a compiled Mongoose model."); } } catch (error) { if (error.message.includes("Mongoose") || error.message.includes("model")) { throw error; } throw new Error( "MongooseStorage requires mongoose to be installed. Install it with: npm install mongoose" ); } this.model = config.model; this.normalizeEmail = config.normalizeEmail ?? true; } normalizeEmailAddress(email) { return this.normalizeEmail ? email.toLowerCase() : email; } /** * Add an email to MongoDB. * @param email - The email to add * @param data - Optional metadata * @throws {Error} If the email already exists or database operation fails */ async add(email, data) { const normalized = this.normalizeEmailAddress(email); const existingDoc = await this.model.findOne({ email: normalized }).exec(); if (existingDoc) { throw new Error(`Email already exists: ${email}`); } try { await this.model.create({ email: normalized, metadata: data, createdAt: /* @__PURE__ */ new Date() }); } catch (error) { if (error.code === 11e3) { throw new Error(`Email already exists: ${email}`); } throw error; } } /** * Remove an email from MongoDB. * @param email - The email to remove * @returns true if the email was found and removed */ async remove(email) { const normalized = this.normalizeEmailAddress(email); const result = await this.model.deleteOne({ email: normalized }).exec(); return result.deletedCount > 0; } /** * Check if an email exists in MongoDB. * @param email - The email to check * @returns true if the email exists */ async exists(email) { const normalized = this.normalizeEmailAddress(email); const count = await this.model.countDocuments({ email: normalized }).exec(); return count > 0; } /** * Retrieve all entries from MongoDB. * @returns Array of all WaitlistEntry objects */ async getAll() { const docs = await this.model.find().lean().exec(); return docs.map((doc) => ({ email: doc.email, metadata: doc.metadata, createdAt: doc.createdAt })); } /** * Count total entries in MongoDB. * @returns Number of entries */ async count() { return this.model.countDocuments().exec(); } /** * Clear all entries from MongoDB. */ async clear() { await this.model.deleteMany({}).exec(); } }; export { MongooseStorage };