Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Feathers.js Request Id Middleware
Bervianto Leo Pratama
Bervianto Leo Pratama

Posted on

     

Feathers.js Request Id Middleware

Prepare your project

  1. Generate the app (if you don't have existing app), please seehere. Basically you need to install the generator with:npm install @feathersjs/cli -g

  2. You can follow the step-by-step in the generate app page. Some notes: I use Typescript for the codebase.

Generate and write the Middleware

  • Usefeathers generate middleware. You can see how I generate the middleware here.

Generate Middleware

  • I want to useuuidv4 as my request id. So please install the uuid use:npm install uuid @types/uuid oryarn install uuid @types/uuid (if you use yarn).

  • Write the middleware. We put the requestId at feathers object. You can found the file atsrc/middleware/request-id.ts.

import{v4asuuidv4}from'uuid';import{Request,Response,NextFunction}from'express';exportdefault()=>{// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/explicit-module-boundary-typesreturn(req:Request,res:Response,next:NextFunction)=>{constrequestId=uuidv4();if(!req.feathers){req.feathers={};}req.feathers.requestId=requestId;next();};};
Enter fullscreen modeExit fullscreen mode
  • Update log hooks for capture ourrequestId. I update thesrc/hooks/log.ts.
// A hook that logs service method before, after and error// See https://github.com/winstonjs/winston for documentation// about the logger.importloggerfrom'../logger';importutilfrom'util';import{HookContext,Hook}from'@feathersjs/feathers';// To see more detailed messages, uncomment the following line:logger.level='debug';exportdefaultfunction():Hook{return(context:HookContext)=>{const{params}=context;constrequestId=params.requestId;logger.debug(`Request Id:${requestId}`);// This debugs the service call and a stringified version of the hook context// You can customize the message (and logger) to your needslogger.debug(`${context.type} app.service('${context.path}').${context.method}()`,);if(// eslint-disable-next-line @typescript-eslint/no-explicit-anytypeof(contextasany).toJSON==='function'&&logger.level==='debug'){logger.debug('Hook Context',util.inspect(context,{colors:false}));}if(context.error&&!context.result){logger.error(context.error.stack);}};}
Enter fullscreen modeExit fullscreen mode

Log request id

  • I want to use error handler and bring the request id. First I will disable html output for error handler. Because I don't want to handle HTML output. You can update thesrc/app.ts like this.
// another code...// Configure a middleware for 404s and the error handlerapp.use(express.notFound());app.use(express.errorHandler({html:false}));app.hooks(appHooks);exportdefaultapp;
Enter fullscreen modeExit fullscreen mode
  • Generate application wide error hooks. You can see picture below. For more information. You can checkthis.

Application Wide hook error

  • Write the hooks. You can found atsrc/hooks/common-error.ts.
// Use this hook to manipulate incoming or outgoing data.// For more information on hooks see: http://docs.feathersjs.com/api/hooks.htmlimport{Hook,HookContext}from'@feathersjs/feathers';// eslint-disable-next-line @typescript-eslint/no-unused-varsexportdefault(options={}):Hook=>{returnasync(context:HookContext):Promise<HookContext>=>{if(context.error){console.log(context);const{params}=context;constrequestId=params.requestId;constrequestIdObject={requestId,};context.error.errors=Object.assign(context.error.errors,requestIdObject,);}returncontext;};};
Enter fullscreen modeExit fullscreen mode
  • After we write that, we will see therequestId under errors property like this. This will help to trace the error.

Example Error use requestId

Thank you

That is it. If you have another suggestions. Please feel free to comment here.

Thank you. :)

Thank you

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

AWS Community Builder | Software Engineer | Focus on topics: Microservices, Cloud Computing, and Cyber Security.
  • Location
    Bandung, Indonesia
  • Education
    Bachelor of Science, Computer Science
  • Pronouns
    He/His/Him
  • Work
    Software Engineer
  • Joined

More fromBervianto Leo Pratama

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp