简体   繁体   中英

How to extends express request interface

I'm using express with typescript. I want to extend my express request interface for that I have done something like this:-

Middleware.ts

import { NextFunction, Request, Response } from 'express';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const configureI18n = require('../helpers/i18n');
const [_, i18nObj] = configureI18n(false);

export interface CRequest extends Request {
  i18nObj: any;
}

const langHeadersMiddleware = (
  request: CRequest,
  response: Response,
  next: NextFunction
): void => {
  try {
    const language = request.headers['accept-language'];

    i18nObj.setLocale(language ? language : 'en');
    request.i18nObj = i18nObj;
    next();
  } catch (error) {
    i18nObj.setLocale('en');
  }
};

export default langHeadersMiddleware;

route.ts

getUserProfile.get(
  '/:id',
  async (request: CRequest, response: express.Response) => {
    try {
           const id = request.params.id;
           response.json({
        err: 0,
        message: request.i18nObj.__('MESSAGES.USER_FETCH'),
        data
      });
    } catch (error: any) {
      response.json({ err: 1, message: error.message, error });
    }
  }
);

In this route I'm getting an error:-

No overload matches this call. The last overload gave the following error. Argument of type '(request: CRequest, response: express.Response) => Promise' is not assignable to parameter of type 'Application<Record<string, any>>'. Type '(request: CRequest, response: Response<any, Record<string, any>>) => Promise' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 61 more.

I went through so many blogs, article but everyone is using the same as I did.

you would have to fork and rework the whole express package, which would definitely not recommend:)

But You can:

  • add your i18n to the request in the middleware as you're doing and just use it with //@ts-ignore above it
  • add your i18n to the request body in the middleware and just use it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM