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 🙏

© 2024 – Pkg Stats / Ryan Hefner

tickets-commonutils

v1.0.4

Published

common package

Downloads

212

Readme

Common Utilities for Express Applications

A collection of reusable utilities and middleware for Express.js applications, aimed at handling common tasks such as error handling, user authentication, and request validation.

Table of Contents

Installation

Install the package via npm:

npm install @sandeshghoti/tickets-commonutils

Usage

Error Handling Middleware

This middleware is used to handle errors thrown during request processing. It catches custom errors and responds with appropriate HTTP status codes and messages.

Example

import express from "express";
import { errorHandler } from "@sandeshghoti/tickets-commonutils";
import { CustomError } from "@sandeshghoti/tickets-commonutils/errors";

const app = express();

// Middleware to handle errors
app.use(errorHandler);

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Current User Middleware

This middleware attaches the current user to the request object if a valid JWT token is present in the session. It decodes the JWT token and attaches the user payload to req.user.

Example

import express from "express";
import { currentUser } from "@sandeshghoti/tickets-commonutils";

const app = express();

// Middleware to attach current user
app.use(currentUser);

app.get("/profile", (req, res) => {
  if (req.user) {
    res.send(`Hello, ${req.user.email}`);
  } else {
    res.send("Hello, Guest");
  }
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Request Validation Middleware

This middleware validates incoming requests based on the validation rules defined using express-validator. It throws a RequestValidationError if the validation fails.

Example

import express from "express";
import { body } from "express-validator";
import { validateRequest } from "@sandeshghoti/tickets-commonutils";

const app = express();
app.use(express.json());

app.post(
  "/signup",
  [
    body("email").isEmail().withMessage("Email must be valid"),
    body("password")
      .isLength({ min: 6 })
      .withMessage("Password must be at least 6 characters"),
    validateRequest,
  ],
  (req, res) => {
    res.send("User signed up successfully");
  }
);

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Custom Errors

CustomError

An abstract class for defining custom errors with specific HTTP status codes and error messages.

Example

import { CustomError } from "@sandeshghoti/tickets-commonutils/errors";

class NotFoundError extends CustomError {
  statusCode = 404;

  constructor() {
    super("Resource not found");
    Object.setPrototypeOf(this, NotFoundError.prototype);
  }

  serializeErrors() {
    return [{ message: "Resource not found" }];
  }
}

DatabaseConnectionError

An error thrown when there is an issue connecting to the database. Extends CustomError.

Example

import { DatabaseConnectionError } from "@sandeshghoti/tickets-commonutils/errors";

app.get("/connect", (req, res) => {
  try {
    // Simulate database connection
    throw new DatabaseConnectionError();
  } catch (err) {
    next(err);
  }
});

RequestValidationError

An error thrown when request validation fails. Extends CustomError and provides details about the validation errors.

Example

import { body } from "express-validator";
import { RequestValidationError } from "@sandeshghoti/tickets-commonutils/errors";

app.post(
  "/login",
  [
    body("email").isEmail().withMessage("Email must be valid"),
    body("password").notEmpty().withMessage("Password is required"),
    (req, res, next) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        throw new RequestValidationError(errors.array());
      }
      next();
    },
  ],
  (req, res) => {
    res.send("User logged in successfully");
  }
);

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue if you find any bugs or have suggestions for improvements.

License

This package is open source and available under the MIT License.