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.
219 lines (168 loc) • 5.36 kB
Markdown
# WaitlistMailer - Practical Examples
Real-world scenarios and complete working examples.
## Table of Contents
1. [Complete Setup Examples](#complete-setup-examples)
2. [Email Workflow Examples](#email-workflow-examples)
3. [Database Management](#database-management)
4. [Event Integration](#event-integration)
5. [Production Patterns](#production-patterns)
## Complete Setup Examples
### Example 1: Simple In-Memory Waitlist for MVP
Perfect for a quick prototype or MVP (Minimum Viable Product). Uses the default memory storage.
```
// mvp-waitlist.ts
import { WaitlistManager, ConsoleMailProvider } from 'waitlist-mailer';
const manager = new WaitlistManager({
// Storage defaults to MemoryStorage automatically
mailer: new ConsoleMailProvider(true), // verbose mode for development
companyName: 'MyStartup'
});
// API endpoint: POST /waitlist/join
export async function joinWaitlist(email: string) {
const result = await manager.join(email, {
joinedAt: new Date().toISOString()
});
return result;
}
// API endpoint: GET /waitlist/stats
export async function getStats() {
const count = await manager.count();
return { waitlistSize: count };
}
```
**Benefits:**
- ✅ Zero database setup
- ✅ No email infrastructure needed
- ✅ Fast iteration
- ✅ See all emails in console
### Example 2: Production MongoDB Setup
For production with persistent database and email sending.
```
// production-setup.ts
import { WaitlistManager, MongooseStorage, NodemailerProvider } from 'waitlist-mailer';
import mongoose from 'mongoose';
// 1. Connect to MongoDB
await mongoose.connect(process.env.MONGODB_URI!);
// 2. Define schema
const waitlistSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true, lowercase: true },
metadata: {
name: String,
source: { type: String, enum: ['twitter', 'productHunt', 'referral', 'direct'] },
referralCode: String,
plan: { type: String, enum: ['free', 'pro', 'enterprise'] }
},
createdAt: { type: Date, default: Date.now }
});
const WaitlistModel = mongoose.model('Waitlist', waitlistSchema);
// 3. Create manager with email provider
const manager = new WaitlistManager({
storage: new MongooseStorage({ model: WaitlistModel }),
mailer: new NodemailerProvider({
host: process.env.SMTP_HOST!,
port: parseInt(process.env.SMTP_PORT!),
secure: process.env.SMTP_SECURE === 'true',
auth: {
user: process.env.SMTP_USER!,
pass: process.env.SMTP_PASS!
}
}),
companyName: 'MyStartup'
});
export { manager };
```
### Example 3: PostgreSQL with Sequelize
```
// postgres-setup.ts
import { WaitlistManager, SequelizeStorage, NodemailerProvider } from 'waitlist-mailer';
import { Sequelize, DataTypes } from 'sequelize';
const sequelize = new Sequelize(
process.env.DB_NAME!,
process.env.DB_USER!,
process.env.DB_PASSWORD!,
{
host: process.env.DB_HOST,
dialect: 'postgres',
logging: false
}
);
// Define model
const WaitlistModel = sequelize.define('Waitlist', {
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false,
lowercase: true
},
metadata: {
type: DataTypes.JSON,
allowNull: true
},
createdAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
}
}, {
timestamps: false,
tableName: 'waitlist'
});
// Sync database
await WaitlistModel.sync();
const manager = new WaitlistManager({
storage: new SequelizeStorage({ model: WaitlistModel }),
mailer: new NodemailerProvider({ /* config */ }),
companyName: 'MyStartup'
});
export { manager };
```
## Email Workflow Examples
### Example 1: Custom Welcome Email with Template
```
import Handlebars from 'handlebars';
import fs from 'fs/promises';
// Load template once (reuse)
const templateSource = await fs.readFile('./templates/welcome.hbs', 'utf-8');
const welcomeTemplate = Handlebars.compile(templateSource);
// When user joins
const result = await manager.join('alice@example.com', {
name: 'Alice Johnson',
source: 'twitter',
plan: 'pro'
});
if (result.success) {
// Generate custom email with their data
const html = welcomeTemplate({
name: 'Alice',
confirmUrl: `https://mystartup.com/confirm/${result.email}`,
company: 'MyStartup'
});
// Send custom email
await manager.sendEmail(result.email, {
subject: '🎉 Welcome to MyStartup, Alice!',
customHtml: html,
customUrl: '[https://mystartup.com/launch](https://mystartup.com/launch)'
});
}
```
### Example 2: Segmented Bulk Email Campaign
Send different emails based on user metadata.
```
// ... template loading code ...
// Send bulk emails with segmentation
const result = await manager.sendBulkEmails((email, metadata) => {
const plan = metadata?.plan || 'free';
const template = plan === 'pro' ? proTemplate : freeTemplate;
const html = template({
name: metadata?.name || 'friend',
launchUrl: '[https://mystartup.com/launch](https://mystartup.com/launch)'
});
return {
subject: plan === 'pro'
? '🌟 Exclusive Early Access for Pro Members'
: '🚀 We\'re Live! Join MyStartup Today',
customHtml: html,
customUrl: '[https://mystartup.com/launch](https://mystartup.com/launch)'
};
}, 5); // Send 5 emails at a time
console.log(`Campaign sent: ${result.sent}/${result.total} emails`);
```