npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@apyrn/utils

v0.0.13

Published

Utility package for Google OAuth integration, email notifications, and ZeptoMail integration with template engine

Readme

apyrn-utils

A utility package for common features like Google OAuth integration, email notifications (including ZeptoMail), and more.

Features

  • Google OAuth 2.0 authentication with Passport.js
  • Email notification system using Nodemailer
  • ZeptoMail integration for reliable email delivery
  • Email template engine with pre-built business templates
  • Rate limiting protection
  • PostgreSQL integration
  • Express.js middleware support
  • Winston logging integration
  • Feature toggles
  • Monitoring utilities
  • Environment-based configuration

Installation

npm install apyrn-utils

Usage

Google OAuth Authentication

The package provides a complete solution for Google OAuth 2.0 authentication using Passport.js with database integration for user management.

Setup

  1. Configure your Google OAuth credentials:
// Create a GoogleAuthConfig object
const config = {
  oauthConfig: {
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL: process.env.GOOGLE_CALLBACK_URL,
    scope: ['profile', 'email']
  },
  pgConfig: {
    host: process.env.POSTGRES_HOST,
    port: parseInt(process.env.POSTGRES_PORT || '5432'),
    user: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DB,
    max: 20,
    idleTimeoutMillis: 30000,
    connectionTimeoutMillis: 2000
  },
  onAuthSuccess: (userData) => {
    // Optional callback when authentication succeeds
    console.log('User authenticated:', userData);
  },
  onAuthFailure: (error) => {
    // Optional callback when authentication fails
    console.error('Authentication failed:', error);
  }
};

// Register Google OAuth
const auth = await registerGoogleAuth(config);

// Initialize Express app with authentication middleware
app.use(auth.initialize());
app.use(auth.session());

// Create authentication routes
app.get('/auth/google', auth.authenticate());
app.get('/auth/google/callback', auth.callback());

Authentication Flow

  1. User clicks on the Google login button, triggering /auth/google
  2. User is redirected to Google's OAuth consent screen
  3. After authentication, Google redirects back to /auth/google/callback
  4. The package handles the OAuth callback, user creation/lookup, and session management
  5. On success, the user is authenticated and their data is stored in the database
  6. On failure, the user is redirected to /auth/failure app.get('/auth/google/callback', auth.callback());

#### Database Integration

The package automatically creates and manages a PostgreSQL table for storing user information:

```sql
CREATE TABLE users_gmail_info (
    id SERIAL PRIMARY KEY,
    google_id TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)

User Management Functions

// Find a user by Google ID
const user = await auth.findUserByGoogleId(googleId);

// Create a new user from Google profile
const newUser = await auth.createUser(userInfo);

// Find or create a user
const user = await auth.findOrCreateUser(userInfo);

// User data structure
interface UserData {
    id: number;
    google_id: string;
    name: string;
    email: string;
    created_at: Date;
}

Error Handling

The package includes comprehensive error handling with specific error types:

try {
    const user = await auth.findOrCreateUser(userInfo);
} catch (error) {
    if (error instanceof DatabaseError) {
        switch (error.type) {
            case 'DUPLICATE_KEY':
                // Handle duplicate user
                break;
            case 'NOT_FOUND':
                // Handle user not found
                break;
            // ... other error types
        }
    }
}

// Database error types:
// - CONNECTION_ERROR
// - QUERY_ERROR
// - DUPLICATE_KEY
// - NOT_FOUND
// - VALIDATION_ERROR

#### Rate Limiting Protection

The authentication service includes built-in rate limiting to prevent abuse:

```typescript
// Configure rate limiting
await auth.configureRateLimit({
    points: 100,
    duration: 60, // seconds
    keyPrefix: 'google_auth_rate_limit'
});

// Check rate limit before authentication
const isLimited = await auth.checkRateLimit(userId);
if (isLimited) {
    throw new RateLimitError('Too many authentication attempts');
}

Email Notifications

Traditional SMTP (Nodemailer)

import { sendEmail } from 'apyrn-utils';

// Send an email using SMTP
const result = await sendEmail({
  transport: {
    host: 'smtp.example.com',
    port: 587,
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS
    }
  },
  email: {
    to: '[email protected]',
    subject: 'Welcome!',
    text: 'Hello! Welcome to our service.',
    html: '<h1>Welcome!</h1><p>Hello! Welcome to our service.</p>'
  }
});

if (result.success) {
  console.log('Email sent successfully:', result.messageId);
} else {
  console.error('Failed to send email:', result.error);
}

ZeptoMail Integration

ZeptoMail is Zoho's reliable email delivery service. This package provides full integration with ZeptoMail for enhanced email delivery.

import { 
  sendZeptoEmail, 
  createZeptoEmailConfig,
  createZeptoEmailSender 
} from 'apyrn-utils';

// Basic ZeptoMail configuration
const zeptoConfig = {
  apiKey: process.env.ZEPTOMAIL_API_KEY,
  domain: process.env.ZEPTOMAIL_DOMAIN // Optional
};

// Method 1: Using helper function
const emailConfig = createZeptoEmailConfig(
  { address: '[email protected]', name: 'Your Name' }, // from
  ['[email protected]'], // to
  'Test Email Subject', // subject
  'This is a plain text message.', // textBody
  '<h1>This is an HTML message</h1>', // htmlBody
  {
    cc: ['[email protected]'],
    trackClicks: true,
    trackOpens: true
  }
);

const result = await sendZeptoEmail({
  transport: zeptoConfig,
  email: emailConfig
});

// Method 2: Create reusable sender
const zeptoSender = createZeptoEmailSender(zeptoConfig);
const result2 = await zeptoSender(emailConfig);

// Method 3: Advanced configuration
const advancedResult = await sendZeptoEmail({
  transport: zeptoConfig,
  email: {
    from: { address: '[email protected]', name: 'Your Name' },
    to: [
      { email_address: { address: '[email protected]', name: 'Recipient 1' } },
      { email_address: { address: '[email protected]', name: 'Recipient 2' } }
    ],
    subject: 'Advanced ZeptoMail Example',
    htmlbody: '<h1>Hello from ZeptoMail!</h1>',
    textbody: 'Hello from ZeptoMail!',
    track_clicks: true,
    track_opens: true,
    attachments: [
      {
        name: 'document.pdf',
        content: 'base64-encoded-content-here',
        mime_type: 'application/pdf'
      }
    ]
  }
});

// Bulk email with throttling
import { sendZeptoEmailWithThrottling } from 'apyrn-utils';

const throttledResult = await sendZeptoEmailWithThrottling(
  { transport: zeptoConfig, email: emailConfig },
  { maxRetries: 3, retryDelayMs: 1000 }
);

ZeptoMail Features:

  • Reliable email delivery with high deliverability rates
  • Built-in tracking for opens and clicks
  • Support for attachments
  • Advanced recipient management
  • Rate limiting and retry logic
  • Full TypeScript support

Email Templates

The package includes a comprehensive email template system with pre-built templates for common business scenarios:

import { TemplateEngine, EMAIL_TEMPLATES, createZeptoEmailSender } from 'apyrn-utils';

const templateEngine = new TemplateEngine();
const sender = createZeptoEmailSender({
  apiKey: 'your-zepto-api-key',
  domain: 'yourdomain.com'
});

// Send signup confirmation email
const signupTemplate = EMAIL_TEMPLATES.SIGNUP_CONFIRMATION;
const params = {
  companyName: 'Acme Corp',
  name: 'John Doe',
  confirmationUrl: 'https://yourdomain.com/confirm?token=abc123',
  contactEmail: '[email protected]'
};

const rendered = await templateEngine.renderTemplate(signupTemplate, params);

await sender({
  to: ['[email protected]'],
  from: { address: '[email protected]', name: 'Acme Corp' },
  subject: rendered.subject,
  htmlbody: rendered.html,
  textbody: rendered.text
});

Available Templates:

  • SIGNUP_CONFIRMATION - Account signup confirmation
  • LOGIN_OTP - One-time password for login
  • PASSWORD_RESET - Password reset links
  • ORDER_CONFIRMATION - Order confirmation with items
  • CART_ABANDONMENT - Cart abandonment reminders
  • PAYMENT_RECEIVED - Payment confirmation
  • SUBSCRIPTION_ACTIVATED - Subscription welcome emails

Template Features:

  • Variable substitution with {{variable}} syntax
  • Conditional content with {{#if condition}}...{{/if}}
  • Loops with {{#each items}}...{{/each}}
  • Both HTML and plain text versions
  • Full TypeScript support
  • Parameter validation

For detailed documentation, see EMAIL_TEMPLATES.md

Rate Limiting

import { RateLimiter } from 'apyrn-utils';

const rateLimiter = new RateLimiter({
  points: 100, // Number of points
  duration: 1, // Duration in seconds
  keyPrefix: 'api_rate_limit'
});

// Check rate limit
const isLimited = await rateLimiter.consume('user123');

Logging

import { Logger } from 'apyrn-utils';

const logger = new Logger();

logger.info('This is an info message');
logger.error('This is an error message');

Configuration

The package requires several environment variables:

# Google OAuth
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret

# Traditional Email (SMTP)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your_username
SMTP_PASS=your_password

# ZeptoMail Configuration
ZEPTOMAIL_API_KEY=your_zeptomail_api_key
ZEPTOMAIL_DOMAIN=your_custom_domain  # Optional

# Database
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_DB=your_database

Development

To run the tests:

npm test

To build the package:

npm run build

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.