FoalTS / foal

Full-featured Node.js framework, with no complexity. 🚀 Simple and easy to use, TypeScript-based and well-documented.
https://foalts.org/
MIT License
1.88k stars 137 forks source link

Validate a request body so that it does contain a non-empty array #962

Closed savissimo closed 3 years ago

savissimo commented 3 years ago

Say I have a schema like this:

const eventTimeSlotSchema = { /* ... */ }
const eventSchema = {
    additionalProperties: false,
    properties: {
        name: { type: 'string' },
        timeSlots: { 
            type: 'array',
            items: eventTimeSlotSchema,
        },
    },
    required: [ 'name', 'timeSlots' ],
    type: 'object',
}

I want to return a Bad Request when the timeSlots array of time slots is empty. In other words, the request must contain at least a time slot.

Can I do this in the schema definition?

Do I have to do it in the action's code? If that's the case, how do I return a Bad Request response?

LoicPoullain commented 3 years ago
{
  type: 'array',
  items: eventTimesSlotSchema,
  minItems: 1,
}

Could this work?

savissimo commented 3 years ago

That's exactly it, thank you a lot!

I'm new to the whole FoalTS / OpenAPI schemas thing, and I'm having a hard time finding documentation about it. Where can I find some good docs? Or, what keywords should I be looking for? Are FoalTS's schemas exactly OpenAPI schemas?

LoicPoullain commented 3 years ago

FoalTS validation hooks are based on AJV validator which uses JSON schemas. AJV's website has pretty good docs: https://ajv.js.org/json-schema.html.

Are FoalTS's schemas exactly OpenAPI schemas

OpenAPI and JSON schemas are very similar and will be the same in most cases, although there might be some differences in some special cases: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.1.md#schema-object

savissimo commented 3 years ago

Thanks a lot, that's what I needed.