I am using Joi to validate a payload of a service in my node.js server using hapijs framework. It used to look like this (in my typescript code as well as after compiling to javascript):
payload: {
para1: Joi.number().required(),
para2: Joi.string()
}
Now I want to set default value of the two parameters. If the code is written in javascript, I can do this:
payload: {
para1: Joi.number().required().default(1),
para2: Joi.string().default("defaultstring")
}
I tested it in swagger and the default values actually became the values I set.
However, my project is written in typescript. I did the same thing and compiled typescript code. The result javascript looks like this:
payload: {
para1: Joi.number().required()["default"](1),
para2: Joi.string()["default"]("defaultstring")
}
In swagger, the default values are not applied.
Here are my questions:
["default"]("defaultstring")
mean and what does it do?Joi.string().default("defaultstring")
Update
According to @rsp's post, the format in question 2 is just different way to access object's property. I also get reference from here. But it doesn't explain if they have any difference. Does anyone have any idea?
Update2
Here is the difference between the two ways accessing JS property. It seems there is no negative effect using brackets way. However, in my case, the default values are not reflected on swagger. Will be doing research on it.
In JavaScript this:
required().default(1)
is the same as this:
required()["default"](1)
because you can access object properties either as:
object["propertyName"]
or:
object.propertyName
(with certain restrictions in the second case).
So it's strange that TypeScript would output the longer style if it doesn't have to, but it's also strange that the longer style doesn't work exactly the same as the shorter one.
I would try to manually change the compiled JavaScript to the shorter version and see if that helps. If it doesn't then the problem is somewhere else. My suspicion is that it will not help.
The .default()
should work in TypeScript because it is defined in @types/joi - see:
But on the other hand there is this comment:
// TODO express type of Schema in a type-parameter (.default, .valid, .example etc)
Which may suggest that .default()
implementation is not ready yet - see:
and also there's this issue: joi.d.ts out of date, missing types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With