Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type safety #128

Open
severo opened this issue Jun 11, 2020 · 2 comments
Open

Add type safety #128

severo opened this issue Jun 11, 2020 · 2 comments

Comments

@severo
Copy link

severo commented Jun 11, 2020

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 severo changed the title Add type-safety Add type safety Jun 11, 2020
@severo
Copy link
Author

severo commented Jun 11, 2020

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

@kobik
Copy link
Collaborator

kobik commented Sep 2, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants