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.
171 lines (169 loc) • 5.52 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// lib/adapters/storage/MongooseStorage.ts
var MongooseStorage_exports = {};
__export(MongooseStorage_exports, {
MongooseStorage: () => MongooseStorage
});
module.exports = __toCommonJS(MongooseStorage_exports);
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();
}
/**
* Search entries by email pattern using MongoDB $regex.
* Delegates filtering to MongoDB for optimal performance.
* @param pattern - The pattern to search for
* @param options - Optional search options
* @returns Matching entries
*/
async search(pattern, options = {}) {
const { limit, offset = 0, caseInsensitive = true } = options;
const escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regexOptions = caseInsensitive ? "i" : "";
let query = this.model.find({
email: { $regex: escapedPattern, $options: regexOptions }
});
if (offset > 0) {
query = query.skip(offset);
}
if (limit !== void 0 && limit > 0) {
query = query.limit(limit);
}
const docs = await query.lean().exec();
return docs.map((doc) => ({
email: doc.email,
metadata: doc.metadata,
createdAt: doc.createdAt
}));
}
/**
* Iterate over entries using MongoDB cursor for memory-efficient streaming.
* Uses Mongoose cursor to avoid loading all documents into memory.
* @param batchSize - Number of entries per batch (default: 100)
*/
async *iterate(batchSize = 100) {
const cursor = this.model.find().lean().batchSize(batchSize).cursor();
for await (const doc of cursor) {
yield {
email: doc.email,
metadata: doc.metadata,
createdAt: doc.createdAt
};
}
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MongooseStorage
});