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

types-formattor

v1.0.1

Published

utilities packages for request response next handler, middleware parser, payment token format, courier response format, notification response format

Readme

Project: API Response and Middleware Formats

This project defines standardized response formats and middleware utilities for handling authentication, notifications, payments, courier tracking, and HTTP requests/responses.

Installation

Ensure you have NestJS and Express installed in your project before using these interfaces and middleware.

npm install @nestjs/common @nestjs/core @nestjs/jwt @nestjs/config express

or using yarn

yarn add @nestjs/common @nestjs/core @nestjs/jwt @nestjs/config express

Response Formats

1. Courier Response Format

This defines the structure for tracking shipments via courier services such as DHL.

export interface CourierResponse {
    trackingId: string;
    status: string;
    estimatedDelivery: string;
    currentLocation: string;
    origin: string;
    destination: string;
    history: Array<{
        status: string;
        location: string;
        timestamp: string;
    }>;
}

2. Notification Response Format

Defines the structure of notification events for server-side events.

export interface NotificationResponse<T> {
    event: string; // "order_update" | "payment_status" | "shipment_tracking" | etc.
    message: string;
    timestamp: string;
    data?: T;
}

3. Payment Response Format

Defines the structure for payment processing responses using Trust Payments.

export interface PaymentResponse {
    status: string; // "success" | "failed" | "pending"
    transactionId: string;
    amount: number;
    currency: string;
    message: string;
    paymentMethod: string; // "credit_card", "paypal", etc.
    createdAt: string;
}

4. HTTP Response Format

A generic HTTP response wrapper to standardize API responses.

export class HttpResponse<T> {
    public data: T;
    public error: boolean;
    public message?: string;
  
    constructor(data: T, error: boolean = false, message?: string) {
      this.data = data;
      this.error = error;
      if (message) {
        this.message = message;
      }
    }
}

Middleware

1. Authentication Middleware

A NestJS AuthGuard for protecting routes using JWT authentication.

import {
    CanActivate,
    ExecutionContext,
    Injectable,
    UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(
        private jwtService: JwtService,
        private reflector: Reflector,
        private configService: ConfigService,
    ) { }

    async canActivate(context: ExecutionContext): Promise<boolean> {
        const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
            context.getHandler(),
            context.getClass(),
        ]);
        if (isPublic) {
            return true;
        }

        const request = context.switchToHttp().getRequest();
        const token = this.extractTokenFromHeader(request);
        if (!token) {
            throw new UnauthorizedException();
        }
        try {
            const payload = await this.jwtService.verifyAsync(token, {
                secret: this.configService.get<string>('JWT_SECRET'),
            });
            request.body = payload;
        } catch {
            throw new UnauthorizedException();
        }
        return true;
    }

    private extractTokenFromHeader(request: Request): string | undefined {
        const [type, token] = request.headers.authorization?.split(' ') ?? [];
        return type === 'Bearer' ? token : undefined;
    }
}

2. Request Interface for Express

Defines a custom request interface that includes a body property for authenticated requests.

import { Request } from 'express';

export interface RequestWithUser extends Request {
    body: any;
}

Usage

Using the AuthGuard in NestJS

import { Controller, Get, UseGuards, Req } from '@nestjs/common';
import { AuthGuard } from './middleware/auth.guard';
import { RequestWithUser } from './req/index';

@Controller('/secure')
export class SecureController {
  @UseGuards(AuthGuard)
  @Get('/')
  getSecureData() {
    return { message: 'Secure data accessed' };
  }

  @UseGuards(AuthGuard)
  @Get('/secure_user')
  getSecureDataByUser(@Req() req: RequestWithUser) {
    return { message: 'Secure data accessed' };
  }
}

Example API Response

{
  "data": {
    "trackingId": "123456789",
    "status": "In Transit",
    "estimatedDelivery": "2025-02-20T10:00:00Z",
    "currentLocation": "New York, USA"
  },
  "error": false,
  "message": "Tracking details fetched successfully"
}

License

MIT License