express-openapi-validator icon indicating copy to clipboard operation
express-openapi-validator copied to clipboard

chore: apiSpec may be const literal

Open duncanbeevers opened this issue 2 years ago • 0 comments

🐸 Problem to Solve

The middleware may be instantiated with a string (path-on-disk to schema document) or with an object literal of the schema.

In Typescript, it is possible to import .json files as modules; however the types of their fields are "loose" (eg; the file ['foo', bar'] would be typed as string[] In order to get stronger typing on imported schemas, they can also be re-emitted as Typescript variables with an as const declaration.

const json = ['foo', 'bar'] as const;

In this case, the json const is typed as its literal value readonly ['foo', 'bar']. This is great, and can be really helpful both when developing, and at run-time.

However, the express-openapi-validator middleware is unhappy with such as const schemas, since the OpenAPIV3.Document type has many mutable fields.

image

👑 Proposed Solution

Through the type system, promise that the express-openapi-validator won't mangle your as const schema.

The middleware is already gentle with the schema, so this is a type-only change.

The change was motivated by the discovery that passing the schema object to other utilities (eg; openapi-typescript) may cause it to be mutated.

The implementation of DeepImmutable is lifted directly from this comment on the TypeScript repo.

duncanbeevers avatar Jun 22 '23 13:06 duncanbeevers