LoginSignup
13
4

More than 5 years have passed since last update.

Express の Request型・Response型を拡張して引き回す

Last updated at Posted at 2019-03-10

Express.Application型を拡張する

Request / Response の型拡張を行なったうえで、どこでもその型が適用されている状態としたい。拡張するモチーベーションとして、次のものを想定している。

  • Middleware で何かを注入している

拡張方法

この拡張定義ファイルは tsconfig の include スコープに含まれていればどこでも良い(つまりどこで良い)。global.Express の namespace で Request / Response のオーバーロードをする。

// ① Express を import

import Express from 'express'

// ② global.Express をオーバーロード

declare global {
  namespace Express {
    interface Request {
      // 拡張される何かのパラメーター
      exparam: { some: string }
    }
    interface Response {
      // 拡張される何かのパラメーター
      exparam: { some: string }
    }
  }
}

通常利用時

req / res は 拡張された Request / Request がキャストされている。同じ要領で、next: NextFunction も自由に定義が可能。Error Logging ハンドラーに渡す props を型キャスト出来る。この方法の場合、Request / Request そのものが拡張されるため、拡張パラメーターは optional にした方が安全。

import Express from 'express'

export default (app: Express.Application) => {
  app.use((req, res, next) => {
    // MiddleWare で拡張する処理
    req.exparam = { some: 'any' }
    next()
  })
  app.get('/path/to/endpoint', (req, res) => {
    console.log(req.exparam)
     // (property) Requesrt.exparams: { some: string }
    res.sendStatus(200)
  })
}
13
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
4