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

时间:2017-08-10 15:02:37

标签: joi

我正在构建一个JOI扩展,允许我将某些人列入黑名单,如果他们在JWT范围内缺少某些角色,则会将其列为黑名单。

到目前为止,我已经去了:

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)
    }
  }]
}))

完美无缺。

但是,请注意,名称和基数设置为“字符串”。我希望这适用于数字,数组,对象,你可以命名。

我试过这个:

  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

我认为任何允许我将该函数追加到JOI中的任何其他类型。但似乎我不能。

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

1 个答案:

答案 0 :(得分:1)

我解决此问题的方法是声明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([
    // ...
  ]),
}))
;