Search code examples
javascriptnode.jsexpressvalidationjoi

How can we write a Joi schema for different request types?


I've been trying to create a schema. It represents my object, which is like {name:"Joe Doe", id:"1234567890"} But on the first request which is for creating new one; it should not have an id parameter in the object. Otherwise it might be meaning an update to consumer...

Would you have any idea about the best way to implement it?

What I need as a joi schema;

joi.object().keys({
    id: joi.string().forbidden() or required(),
    name: joi.string(),
    ...

Sample requests;

Create:

POST Request... 'api/v1/item/'

Object : {name:"Joe Doe"}

Update:

PUT Request... 'api/v1/item/'

Object : {id:"1234567890", name:"Joe Doe"}


Solution

  • On the project, we still use 14.3.1 version of joi. I could solve my problem with creating a base joi object and extending it like;

    const base = joi.object().keys({name: joi.string()});
    const put = base.keys({
        id: joi.string().required(),
    });
    const post = base.keys({
        id: joi.string().forbidden(),
    });
    

    Even it looks cleaner to read. I leave that here for if someone needs something similar.