7

Is there a syntax to add a function to a chain under conditions?

In this example, I would like myKey to be Joi.string().required() if modifier === true, but just Joi.string() if it is false:

function customJoi(modifier) {
  return Joi.object({
    myKey: Joi.string() //#If(modifier) .required() #EndIf
  });
}

I know I could do without this feature, with multiple steps. I'm just wondering if there is a nice way to write it concisely for large objects.

8
  • 1
    @Touffy :shrug: OP states "conditional chaining" which seems to describe the problem pretty well and the question elaborates; IMO it's fine. Commented Jan 3, 2022 at 17:23
  • I agree, once you read it carefully it's a good description. But who reads carefully nowadays ? (see first comment on this post…). Maybe just write "optional" in italics or something ? Commented Jan 3, 2022 at 17:29
  • @Touffy I think most people who answered and commented here did read correctly :) Commented Jan 3, 2022 at 17:31
  • @Touffy My bad - happens sometimes to me - hope I get pardoned.. ;) Commented Jan 3, 2022 at 17:33
  • @Touffy It literally doesn't say "optional" anywhere? Commented Jan 3, 2022 at 17:34

2 Answers 2

8

You could take optional, if not required.

myKey: Joi.string()[modifier ? 'required' : 'optional']()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I think that's the best we can get :) Although one limitation is that you have to have a fallback method for the ternary operator to work, as undefined doesn't seem to be acceptable.
True. Though I guess in a controlled environment you could define a "noop" method on any chainable you design, so you always have that option. Or… gasp… define it on Object.prototype and be despised by all your coworkers.
5

You can achieve that with a ternary.

function customJoi(modifier) {
    return Joi.object({
        myKey: modifier ? Joi.string().required() : Joi.string()
    });
}

1 Comment

Thanks, it's a good answer too, but I'll accept Nina Scholz's answer because it's closer to what I was looking for, especially for longer chains. Although one advantage of your method is you don't need a fallback method for the ternary operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.