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 🙏

© 2026 – Pkg Stats / Ryan Hefner

dwinsoft-api-functions

v1.3.0

Published

A collection of API functions for common backend services

Readme

DwinSoft API Functions

A collection of common backend API functions for Node.js applications.

Installation

npm install dwinsoft-api-functions

Features

  • JWT Authentication
  • Email Service
  • Database Connections (MongoDB & PostgreSQL)
  • OAuth Authentication
  • Express Middleware
  • Advanced Error Handling
  • Logging System
  • Request Validation
  • File Upload Utilities
  • Rate Limiting
  • Controller Functions (Login, Register, CRUD)

Usage

JWT Authentication

import { generateToken, verifyToken } from 'dwinsoft-api-functions';

// Generate a JWT token
const token = generateToken({ userId: '123' });

// Verify a JWT token
const payload = verifyToken(token);

Email Service

import { sendMail } from 'dwinsoft-api-functions';

// Send an email
await sendMail('[email protected]', 'Subject', 'Email body text');

Database Connections

// MongoDB Connection
import { connectMongo } from 'dwinsoft-api-functions';
await connectMongo();

// PostgreSQL Connection
import { connectPostgres, query } from 'dwinsoft-api-functions';
const pool = await connectPostgres();
const result = await query('SELECT * FROM users WHERE id = $1', [userId]);

// Using config/db.js approach (supports both databases)
import { connectDatabases, pgQuery } from 'dwinsoft-api-functions';
const connections = await connectDatabases();
const pgResult = await pgQuery('SELECT * FROM users');

Express Middleware

import express from 'express';
import { applyMiddleware, errorHandler } from 'dwinsoft-api-functions';

const app = express();

// Apply common middleware (CORS, Helmet, Morgan, etc.)
applyMiddleware(app, {
  enableCors: true,
  enableHelmet: true,
  enableMorgan: true,
  enableRateLimit: true
});

// Add your routes here
app.get('/', (req, res) => {
  res.send('Hello World');
});

// Apply error handling middleware
errorHandler(app);

OAuth Authentication

import { verifyGoogleToken } from 'dwinsoft-api-functions';

// Verify a Google OAuth token
const userData = await verifyGoogleToken(token);

Advanced Error Handling

import { ApiError, asyncHandler, errorMiddleware } from 'dwinsoft-api-functions';
import express from 'express';

const app = express();

// Use async handler to catch errors in async route handlers
app.get('/users/:id', asyncHandler(async (req, res) => {
  const user = await findUser(req.params.id);
  if (!user) {
    throw ApiError.notFound('User not found');
  }
  res.json(user);
}));

// Apply error middleware
const { notFoundHandler, errorHandler } = errorMiddleware({
  logErrors: true,
  includeStackInResponse: process.env.NODE_ENV === 'development'
});

// Apply error handlers at the end of your middleware chain
app.use(notFoundHandler);
app.use(errorHandler);

Logging System

import { createLogger } from 'dwinsoft-api-functions';

const logger = createLogger({
  logDirectory: 'logs',
  logToConsole: true,
  logToFile: true
});

// Use as middleware
app.use(logger.middleware);

// Use as logger
logger.info('Server started', { port: 3000 });
logger.error('Database connection failed', { error: err.message });

Request Validation

import { validate, commonSchemas } from 'dwinsoft-api-functions';
import express from 'express';
import Joi from 'joi';

const app = express();

// Define validation schema
const userSchema = {
  body: Joi.object({
    name: Joi.string().required(),
    email: commonSchemas.email,
    password: commonSchemas.password
  })
};

// Apply validation middleware
app.post('/users', validate(userSchema), (req, res) => {
  // Request body is validated and sanitized
  res.json({ success: true });
});

File Upload

import { createFileUpload, fileTypes, uploadErrorHandler } from 'dwinsoft-api-functions';
import express from 'express';

const app = express();

// Create file upload middleware
const fileUpload = createFileUpload({
  destination: 'uploads/',
  allowedMimeTypes: fileTypes.images,
  limits: { fileSize: 5 * 1024 * 1024 } // 5MB
});

// Handle file upload errors
app.use(uploadErrorHandler());

// Single file upload
app.post('/upload', fileUpload.single('image'), (req, res) => {
  res.json({
    success: true,
    file: req.file,
    url: fileUpload.getFileUrl(req.file.filename)
  });
});

Rate Limiting

import { createRateLimiter, rateLimiters } from 'dwinsoft-api-functions';
import express from 'express';

const app = express();

// Use predefined rate limiters
app.use('/api', rateLimiters.api());
app.use('/auth', rateLimiters.auth());

// Create custom rate limiter
const customLimiter = createRateLimiter({
  windowMs: 5 * 60 * 1000, // 5 minutes
  max: 50, // 50 requests per 5 minutes
  message: 'Custom rate limit exceeded'
});

app.use('/custom', customLimiter);

Controller Functions

import { createController } from 'dwinsoft-api-functions';
import User from '../models/User';
import { generateToken } from 'dwinsoft-api-functions';
import bcrypt from 'bcrypt';
import Joi from 'joi';

// Create validation schemas
const validationSchemas = {
  register: Joi.object({
    name: Joi.string().required(),
    email: Joi.string().email().required(),
    password: Joi.string().min(6).required()
  }),
  login: Joi.object({
    email: Joi.string().email().required(),
    password: Joi.string().required()
  })
};

// Create controller with authentication and CRUD operations
const userController = createController({
  model: User,
  validationSchemas,
  hashPassword: async (password) => await bcrypt.hash(password, 10),
  comparePassword: async (password, hash) => await bcrypt.compare(password, hash),
  generateToken,
  uniqueField: 'email'
});

// Use controller methods in routes
app.post('/register', userController.register);
app.post('/login', userController.login);
app.get('/users', userController.getAll);
app.get('/users/:id', userController.getOne);
app.post('/users', userController.create);
app.put('/users/:id', userController.update);
app.delete('/users/:id', userController.remove);

Environment Variables

The following environment variables are required:

  • JWT_SECRET: Secret key for JWT signing and verification
  • MAIL_USER: Email address for sending emails
  • MAIL_PASS: Password for the email account
  • MONGO_URI: MongoDB connection string
  • POSTGRES_HOST: PostgreSQL host address
  • POSTGRES_USER: PostgreSQL username
  • POSTGRES_PASSWORD: PostgreSQL password
  • POSTGRES_DB: PostgreSQL database name
  • POSTGRES_PORT: PostgreSQL port (default: 5432)
  • GOOGLE_CLIENT_ID: Google OAuth client ID

CLI Usage

You can also use the CLI tool to add API features to your project:

# Add individual services
npx dwinsoft-api add jwt
npx dwinsoft-api add mailservice
npx dwinsoft-api add mongo
npx dwinsoft-api add postgres
npx dwinsoft-api add oauth
npx dwinsoft-api add middleware
npx dwinsoft-api add error-handler
npx dwinsoft-api add logger
npx dwinsoft-api add validation
npx dwinsoft-api add file-upload
npx dwinsoft-api add rate-limiter
npx dwinsoft-api add controller

# Add database configuration file
npx dwinsoft-api add db

# Add services with options
npx dwinsoft-api add jwt -middleware  # Adds JWT service and middleware
npx dwinsoft-api add auth -db         # Adds auth service and database config
npx dwinsoft-api add api -validation  # Adds API with validation
npx dwinsoft-api add upload -error    # Adds file upload with error handling

License

MIT