How to annotate Express middlewares with JSDoc? How to annotate Express middlewares with JSDoc? javascript javascript

How to annotate Express middlewares with JSDoc?


Use DefinitelyTyped

  1. Install express types npm install --save-dev @types/express
  2. use e.Response as usually @param {e.Response} res

More types

  • in file /node_modules/@types/express/index.d.ts
  • for Response it is e.Response because:

...declare namespace e { ... export interface Response extends core.Response { } ...

WebStorm

install types via Settings > Languages & Frameworks > Javascript > Libraries > @types/express


You can document your middleware with

const express = require("express");/** * @param {express.Request} req * @param {express.Response} res * @param {express.NextFunction} next */function (req, res, next) {}

when you have middleware that add attribute to req, you can also add them with

const express = require("express");/** * @param {express.Request & {specialParam1 : string, specialParam2 : any}} req * @param {express.Response} res * @param {express.NextFunction} next */function (req, res, next) {}

or event better, create a typedef for each source of new elem added on "req" and use "&" to create a type combining them all.


First, we agree that middleware are functions; no special type declaration will generally be warranted. Beyond that, middleware tend to be highly decoupled—modular—which means the @module tag is usually applicable (and this has nice consequences when you run jsdoc).

/** * Description of my middleware. * @module myMiddleware * @function * @param {Object} req - Express request object * @param {Object} res - Express response object * @param {Function} next - Express next middleware function * @return {undefined} */

The return tag is optional depending on your style guide, since middleware don't return a value. Finally, contrary to what Nick and mmm claim, the next parameter is a function.

http://expressjs.com/en/guide/using-middleware.html

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

next isn't a fancy Express-internal concoction; Express passes each middleware function the request, the response, and the next middleware function in the stack, like this:

mw1 = function(req, res, next){}.bind(undefined, req, res, mw2)mw2 = function(req, res, next){}.bind(undefined, req, res, mw3)

The value of next within the scope of mw1 is mw2.