kogosoftwarellc / open-api

A Monorepo of various packages to power OpenAPI in node
MIT License
892 stars 235 forks source link

The Operation interface does not allow to access apiDoc from req parameter #661

Open j-zimnowoda opened 4 years ago

j-zimnowoda commented 4 years ago

Overview

Hi,

I am trying to access apiDoc object but typescript warns me that:

Property 'apiDoc' does not exist on type 'Request<ParamsDictionary, any, any, Query>'.

Is it a bug in the interface definition or I should access apiDoc another way ?

Steps to reproduce

import { Operation } from 'express-openapi'

export default function (otomi) {
  const GET: Operation = [
    (req, res, next) => {
      return res.json(req.apiDoc)
    },
  ]
  const api = {
    GET,
  }
  return api
}
jsau- commented 2 years ago

To get around this I've used declaration merging on express' Request type.

For example, add the following to your tsconfig.json:

"typeRoots": [
  "./src/typeRoots"
],

And then add a file ./src/typeRoots/express.d.ts:

import { OpenAPIV3 } from 'openapi-types';

declare global {
  declare namespace Express {
    export interface Request {
      apiDoc: OpenAPIV3.Document;
    }
  }
}

Anywhere you use express.Request now you should get type-hinting for apiDoc.

Worth noting that I've gotten lazy and hard-coded the explicit type of apiDoc that I expect for my application there. I think the general-case type right now would possibly be ExpressOpenAPIArgs['apiDoc'] which currently resolves as OpenAPIV2.Document | OpenAPIV3.Document | string.