Serialize in request validation and authorize object when toJSON() matches to the format
See original GitHub issueIs your feature request related to a problem? Please describe. I would like to do 2 things :
- serialize String data to Object when I receive it from request
- deserialize object when i want to return the response and validate my response
I have two kinds of objects in my mind :
- Date objects
- Mongodb ObjectID
Describe the solution you’d like It could be great to allow developers to add some adapters that could be considered by express-openapi-validator on request and on response. For example, i could declare in my openapi components section :
components:
schemas:
ObjectId:
type: "string"
pattern: "^[0-9a-fA-F]{24}$"
Date:
type: "string"
format: "date"
DateTime:
type: "string"
format: "date-time"
then i could configure my OpenAPIValidator with those adapters :
OpenApiValidator({
apiSpec: './test/resources/openapi.yaml',
validateRequests: true, // (default)
validateResponses: true, // false by default
formatAdapters : {
'#/components/schemas/ObjectId' : {
serialize : o => new ObjectID(o)
deserialize : o => o.toJSON()
},
'#/components/schemas/Date' : {
serialize : o => new Date(o)
deserialize : o => o.toISOString().slice(0,10);
},
'#/components/schemas/DateTime' : {
serialize : o => new Date(o)
deserialize : o => o.toISOString();
}
}
})
Describe alternatives you’ve considered I already tried to hack the formats.js by adding new formats and a “validate” description I also used in the past (2014-2015), a library, “tdegrunt/jsonschema” ,in which I added a hook to do this. I manage to do this but I need to parse twice the JSON body : once with jsonschema then once with express-openapi-validator.
Additional context I saw some issues related to this issue even if they are not explained the same way. I think this solution would be adaptable :
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:7 (7 by maintainers)
Top GitHub Comments
In my pull request, I tested it. It also worked for request parameters.
v4.10.0
resolves this issue fordate-time
anddate
formats. a custom serializer mechanism is still required for custom types e.g. MongoDbObjectId
This issue must remain open as a solution is still needed for custom serializers to handle cases like
ObjectId