简体   繁体   中英

How to get all the keys in a joi schema?

I had a joi schema like this

const userModel = Joi.object({
  id: Joi.string().min(3).max(50),
  username: Joi.string().min(10).max(100)
  ... other 10 properties
})

the thing is I wanted to get the values of all the keys like

["id","username",...]

I tried using Object.keys(userModel), but that is returning an unexpected value like

[
  "isJoi",
  "_currentJoi",
  "_type",
  "_settings",
  "_baseType",
  "_valids",
  "_invalids",
  "_tests",
  "_refs",
  "_flags",
  "_description",
  "_unit",
  "_notes",
  "_tags",
  "_examples",
  "_meta",
  "_inner"
]

Something like this could help.

const userModel = Joi.object({
  id: Joi.string().min(3).max(50),
  username: Joi.string().min(10).max(100)
})


const keys = [];
for (var i of userModel._ids._byKey.entries()){
  keys.push(i[0])
}

console.log(keys);

The reason for the unexpected behaviour is due to the fact the userModel is not an ordinary object, it's a joi object.

A possible solution is to check the userModel._ids._byKey.keys() to get a Map iterator of all of the keys in the schema. The problem with this solution is that you count on the internals of the Joi framework.

I might suggest another approach: Extract the required fields in a separate data structure - array or object and extend the Joi schema based on that.


I've just been struggling with this myself. After some digging in the api I found this

For a Joi.object This returns a simple object with a property called keys

{
  type: 'object',
  keys: {
    nestedItem1: { type: 'any', rules: [Array], allow: [Array] },
    nestedItem2: { type: 'string', flags: [Object], rules: [Array] },
  }
}

It's pretty straightforward from there.

const userModel = Joi.object({
    id: Joi.string().min(3).max(50),
    username: Joi.string().min(10).max(100)
});

const keys = Object.keys(userModel.describe().keys);

console.log(keys)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM