gpt4 book ai didi

javascript - 扩展的 Joi 没有实现自定义操作符

转载 作者:行者123 更新时间:2023-12-04 08:42:52 28 4
gpt4 key购买 nike

我在使用自定义运算符扩展 joi 类时遇到问题。我想验证 mongodb Id,但扩展对象引发以下错误:

error: uncaughtException: JoiObj.string(...).objectId is not a function
TypeError: JoiObj.string(...).objectId is not a function
代码如下:
import Joi from 'joi';
import * as mongodb from 'mongodb';

interface ExtendedStringSchema extends Joi.StringSchema {
objectId(): this;
}

interface ExtendedJoi extends Joi.Root {
string(): ExtendedStringSchema;
}

const JoiObj: ExtendedJoi = Joi.extend({
base: Joi.string(),
type: 'objectId',
messages: {
'objectId.invalid': '"{{#label}}" must be a valid mongo id'
},
validate(value, helpers) {
if (!mongodb.ObjectId.isValid(value)) {
return helpers.error('objectId.invalid');
}

return value;
}
});

const objIdSchema = JoiObj.object({
id: JoiObj.string().objectId()
});
我找到了2个例子:
https://github.com/sideway/joi/issues/2357
How to extend a module from npm using TypeScript?
但是,它们使用的属性与 TS 定义文件中描述的属性不同,因此不起作用。

最佳答案

您想扩展 Joi.string()根据。请记住,您无法验证 new mongodb.ObjectID()因为它的类型是 object .您扩展了 Joi.string()这会检查 第一 如果您的值属于 string 类型.如果不是,它将停止验证。您只能验证 new mongodb.ObjectID().toHexString()看起来像:"5f91a1449b13e3010c5548a2" .
这个答案正在使用 joi 17.2.1 和 mongodb 3.6.2

import Joi from 'joi';
import * as mongodb from 'mongodb';

interface ExtendedStringSchema extends Joi.StringSchema {
objectId(): this;
}

interface ExtendedJoi extends Joi.Root {
string(): ExtendedStringSchema;
}

const stringObjectExtension: Joi.Extension = {
type: 'string',
base: Joi.string(),
messages: {
'string.objectId': '{{#label}} must be a valid mongo id'
},
rules: {
objectId: {
validate: (value: any, helpers) => {
if (!mongodb.ObjectId.isValid(value)) {
return helpers.error('string.objectId')
}

return value;
}
}
}
};

// create extended Joi
const JoiObj: ExtendedJoi = Joi.extend(stringObjectExtension);

// create new mongodb id
const id = new mongodb.ObjectID();

const objIdSchema = JoiObj.object({
id: JoiObj.string().objectId()
});

// will fail because it won't pass the Joi.string() validation
const data1 = {
id: id
};
console.log(objIdSchema.validate(data1).error);

// will succeed
const data2 = {
id: id.toHexString()
};
console.log(objIdSchema.validate(data2).error);

关于javascript - 扩展的 Joi 没有实现自定义操作符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64476991/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com