PayU / openapi-validator-middleware

Input validation using Swagger (Open API) and ajv
Apache License 2.0
144 stars 49 forks source link

Add type safety #128

Open severo opened 4 years ago

severo commented 4 years ago

Since it's possible to generate typescript definitions from an OpenAPI specification (ie with https://www.npmjs.com/package/dtsgenerator), I wonder if it would be possible to implement type safety between the validator middleware and the following middlewares.

For example, dtsgenerator would transform https://github.com/PayU/openapi-validator-middleware/blob/master/test/pet-store-swagger.yaml to the following types declarations file:

// extract of the file...
declare namespace Paths {
    namespace CreatePets {
        export interface BodyParameters {
            body: Parameters.Body;
        }
        namespace Parameters {
            export interface Body {
                name: string;
                age?: number;
                tag?: string;
                test: {
                    field1: "enum1" | "enum2";
                };
            }
        }
        namespace Responses {
            export type Default = Definitions.Error;
        }
    }
// ...

Ideally, the validator would return a request with the expected type (something like Request<{}, {}, Paths.CreatePets.Parameters.Body>, see https://stackoverflow.com/a/55413670/7351594), so that the following middleware / route handler would know the type of its req argument:

app.post(
  '/pets',
  swaggerValidation.validate,
  (req: Request<{}, {}, Paths.CreatePets.Parameters.Body>, res, next) => {
    return res.json({ result: 'OK' });
  }
);

That way, the following route handler would not have to assume validation has already been done, thus reducing code coupling.

severo commented 4 years ago

See also https://federicoferoldi.com/2017/12/28/using-the-typescript-type-system-to-validate-express-handlers.html that relies on that idea.

kobik commented 3 years ago

Thanks @severo, this is an interesting idea!

This is something that should be exposed from api-shema-builder, as this is the package that is responsible for parsing the definitions file.

We'll try to see what we can do when we'll have the time, but of course PRs are always welcome.