Skip to content

Update Handler typing with generic request and response types #96

@jgornick

Description

@jgornick

In order to get better typing on the arguments for the Handler type, does it make sense to use generics for the request and response arguments?

For example, what if there was:

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'
import { Params, ParamsDictionary } from 'express-serve-static-core'
import { Request } from 'openapi-backend'
import { Context } from 'openapi-backend/backend'

export type Handler<
  TRequest extends Request = any,
  TResponse = any
> = (context: Context, req: TRequest, res: TResponse, ...args: any[]) => any | Promise<any>;

export type OpenApiExpressRequest<
  P extends Params = ParamsDictionary,
  ResBody = any,
  ReqBody = any
  > = ExpressRequest<P, ResBody, ReqBody> & Request

export type ExpressHandler<
  P extends Params = ParamsDictionary,
  ResBody = any,
  ReqBody = any
> = Handler<OpenApiExpressRequest<P, ResBody, ReqBody>, ExpressResponse<ResBody>>

This way, when writing handlers for an express-backed service, they could be typed as:

import { ExpressHandler } from 'openapi-backend/backend'

export const getById: ExpressHandler = (c, req, res) => {
  res.status(200).json({ message: `getById: ${req.path}` })
}

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions