可以将 JOI 扩展应用于 'any()' 以便它适用于所有类型吗?

Can a JOI extension be applied to 'any()' so that it works for all types?

我正在构建一个 JOI 扩展,如果他们在 JWT 范围内缺少某些角色,我可以将某些人列入黑名单,禁止他们发送某些 API 值。

到目前为止我已经这样做了:

const Joi = require('joi')
const { string, number, ref, required, only, lazy } = Joi.extend(joi => ({
  name: 'string',
  base: Joi.string(),
  language: {
    permits: 'you are not allowed to edit {{key}}'
  },
  pre (value, state, options) {
    this.permissions = options.context.auth.credentials.scope
  },
  rules: [{
    name: 'whitelist',
    params: {
      permits: Joi.array()
    },
    validate(params, value, state, options) {
      const permitted = params.permits.find(value => this.permissions.includes(value))
      return permitted ? value : this.createError('string.permits', {}, state, options)
    }
  }]
}))

效果很好。

但是,请注意名称和基数设置为 'string'。我希望它适用于数字、数组、对象,随你便。

我试过这个:

  name: 'any',
  base: Joi.any()

但是好像不行:

/home/ant/Projects/roles-example/routes/validation.routes.js:55
          reference: string().whitelist(['all-loans']),
                              ^

TypeError: string(...).whitelist is not a function

我假设 any 允许我将函数附加到 JOI 中的任何其他类型。但是我好像做不到。

在我必须开始将其添加到所有 JOI 基本类型之前,有人对我有任何指示吗?

我解决这个问题的方法是声明 any 规则分开并将它们全部添加到每个 Joi 类型。

const Joi = require('joi')

const anyRules = j => [
  {
    name: 'whitelist',
    params: {
      permits: j.array()
    },
    validate(params, value, state, options) {
      const permitted = params.permits.find(value => this.permissions.includes(value))
      return permitted ? value : this.createError('string.permits', {}, state, options)
    }
  }
];

module.exports = Joi
.extend(j => ({
  name: 'any',
  base: j.any(),
  rules: anyRules(j),
}))
.extend(j => ({
  name: 'array',
  base: j.array(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'boolean',
  base: j.boolean(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'binary',
  base: j.binary(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'date',
  base: j.date(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'func',
  base: j.func(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'number',
  base: j.number(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'object',
  base: j.object(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'string',
  base: j.string(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
.extend(j => ({
  name: 'alternatives',
  base: j.alternatives(),
  rules: anyRules(j).concat([
    // ...
  ]),
}))
;