Set default validation value

I use Joi to check the service payload on my node.js server using the hapijs framework. It looked like this (in my typescript code, and also after compiling to javascript):

payload: { para1: Joi.number().required(), para2: Joi.string() } 

Now I want to set a default value for 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 and compiled typescript code. The javascript result 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:

  • Why does the code become different after compilation?
  • what does ["default"]("defaultstring") mean and what does it do?
  • how can I write typescript code to make sure it can be compiled as Joi.string().default("defaultstring")

Update

According to @rsp, the format in question 2 is just another way to access the object. I also get a link from here . But that doesnโ€™t explain if they have any difference. Somebody knows?

Update2

There is a difference between the two ways to access the JS property. There seems to be no negative effect using parentheses. However, in my case, the default values โ€‹โ€‹do not affect swagger. Will be engaged in research.

+5
source share
2 answers

In JavaScript, this is:

 required().default(1) 

matches this:

 required()["default"](1) 

since you can access the properties of the object either as:

 object["propertyName"] 

or

 object.propertyName 

(with some restrictions in the second case).

It is so strange that TypeScript displays a longer style if it is not necessary, but it is also strange that a longer style does not work just like a shorter one.

I would try to manually compile JavaScript into a shorter version and see if that helps. If not, the problem is elsewhere. My suspicion is that this will not help.

.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 the implementation of .default() is not ready yet - see:

and also this problem: joi.d.ts out of date, missing types

+2
source

Usage should use default () as shown below:

  validate: { payload: { para1: Joi.number().integer().min(1).max(100).default(10).required(), para2: Joi.string().min(1).max(100).default("TEST").required(), } } 
0
source

Source: https://habr.com/ru/post/1265891/


All Articles