UNPKG

types-formattor

Version:

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

204 lines (166 loc) 4.97 kB
# 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. ```sh npm install @nestjs/common @nestjs/core @nestjs/jwt @nestjs/config express ``` or using yarn ```sh 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. ```typescript 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. ```typescript 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. ```typescript 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. ```typescript 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. ```typescript 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. ```typescript import { Request } from 'express'; export interface RequestWithUser extends Request { body: any; } ``` --- ## Usage ### **Using the AuthGuard in NestJS** ```typescript 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** ```json { "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