使用 Joi 验证包含小胡子模板的 uri
Validate an uri which contains mustache template with Joi
我正在尝试验证可以包含 mustache 语法的 uri:
{{ key }}
所以它看起来像这样(首先是一个无效的 URI):
http(s)://whatever.com/.../{{ key }}/...
我用的是Joi
,好像Joi.string().uri()
不能允许更多的字母。
我还检查了 Joi.alternatives()
但这会导致我创建自己的正则表达式,它可能不像 Joi
.
中的那样安全
有什么想法吗?
确实没有办法在不完全重写的情况下增加符合 RFC 的内部正则表达式。
如您所述,这是一个无效的 URI 首先。由于您似乎使用 "simple" 小胡子持有者并且没有条件标签,因此解决方法是为 Joi 提供一个已经呈现的 URI(那么我们应该说第二位吗?),例如:
const Mustache = require('mustache');
const Joi = require('joi');
// assuming objectToValidate.mustacheString holds a "potentially mustached URI"
/*async */function validateMyStuff(objectToValidate, myJoiSchema) {
// to catch standard and variable-like tags: {{standard}}, {{{variable}}} or {{&variable}}
const mustacheTypesToReplace = ['name', '&'];
// render into the object to validate
objectToValidate.mustacheString = Mustache.render(
objectToValidate.mustacheString,
// build a dummy view object
Mustache.parse(objectToValidate.mustacheString).reduce((accumulator, parsedItem) => {
if (mustacheTypesToReplace.includes(parsedItem[0])) {
accumulator[parsedItem[1]] = 'x'; // dummy data that won't break the RFC
}
return accumulator;
}, {})
);
// here the Joi.string().uri() shouldn't break unless URI is wrong
return Joi.validate(objectToValidate, myJoiSchema).then((validatedObject) => {
validatedObject.mustacheString = objectToValidate.mustacheString ; // set back the mustached data
return validatedObject;
});
}
我正在尝试验证可以包含 mustache 语法的 uri:
{{ key }}
所以它看起来像这样(首先是一个无效的 URI):
http(s)://whatever.com/.../{{ key }}/...
我用的是Joi
,好像Joi.string().uri()
不能允许更多的字母。
我还检查了 Joi.alternatives()
但这会导致我创建自己的正则表达式,它可能不像 Joi
.
有什么想法吗?
确实没有办法在不完全重写的情况下增加符合 RFC 的内部正则表达式。
如您所述,这是一个无效的 URI 首先。由于您似乎使用 "simple" 小胡子持有者并且没有条件标签,因此解决方法是为 Joi 提供一个已经呈现的 URI(那么我们应该说第二位吗?),例如:
const Mustache = require('mustache');
const Joi = require('joi');
// assuming objectToValidate.mustacheString holds a "potentially mustached URI"
/*async */function validateMyStuff(objectToValidate, myJoiSchema) {
// to catch standard and variable-like tags: {{standard}}, {{{variable}}} or {{&variable}}
const mustacheTypesToReplace = ['name', '&'];
// render into the object to validate
objectToValidate.mustacheString = Mustache.render(
objectToValidate.mustacheString,
// build a dummy view object
Mustache.parse(objectToValidate.mustacheString).reduce((accumulator, parsedItem) => {
if (mustacheTypesToReplace.includes(parsedItem[0])) {
accumulator[parsedItem[1]] = 'x'; // dummy data that won't break the RFC
}
return accumulator;
}, {})
);
// here the Joi.string().uri() shouldn't break unless URI is wrong
return Joi.validate(objectToValidate, myJoiSchema).then((validatedObject) => {
validatedObject.mustacheString = objectToValidate.mustacheString ; // set back the mustached data
return validatedObject;
});
}