我正在使用此代码并创建了一个微服务
const { json, send } = require('micro')
const { router, post } = require('microrouter')
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)
console.log(process.env.STRIPE_SECRET_KEY)
module.exports = router(
post('/', async (req, res) => {
const data = await json(req)
try {
const { status } = await stripe.charges.create(data)
send(res, 200, { status })
} catch (err) {
send(res, 500, { message: err.message })
}
})
)
我可以在此处使用post
发出microrouter
请求,但是如何验证有效载荷主体以仅获取必需的字段。
如果有人知道用于验证微服务发布有效载荷的任何模块,请提供帮助。
答案 0 :(得分:1)
您可以使用joi npm并表达验证器
const Joi = require("joi");
const validate = require("express-validation");
const validationSchema = {
body: {
Id: Joi.string()
.guid()
.required(), // mandatory
FirstName: Joi.string().required(), // mandatory
LastName: Joi.string().required(), // mandatory
Email: Joi.string()
.email({ minDomainAtoms: 2 })
.required(), // mandatory
Password: Joi.string().required(), // mandatory
createdOn: Joi.date()
.timestamp()
.required(), // mandatory
}
};
路由器文件
module.exports = router(
post('/',validate(validationSchema), async (req, res) => {
const data = await json(req)
try {
const { status } = await stripe.charges.create(data)
send(res, 200, { status })
} catch (err) {
send(res, 500, { message: err.message })
}
})
)
答案 1 :(得分:0)
您遇到了这么普遍的问题,据我了解,您可以将这些负载用于https://validatejs.org/#validators
这是电子邮件验证示例:
var constraints = {
from: {
email: true
}
};
validate({from: null}, constraints);
// => undefined
validate({from: ""}, constraints);
// => {"email": ["From is not a valid email"]}
validate({from: "nicklas@ansman"}, constraints);
// => {"email": ["From is not a valid email"]}
// Any TLD is allowed
validate({from: "nicklas@foo.faketld"}, constraints);
// => undefined
// Upper cased emails are allowed
validate({from: "NICKLAS@ANSMAN.SE"}, constraints);
// => undefined
constraints = {
from: {
email: {
message: "doesn't look like a valid email"
}
}
};
validate({from: "foobar"}, constraints);
// => {"email": ["From doesn't look like a valid email"]}
// It allows unicode
validate({from: "first.läst@example.com"}, constraints);
// => undefined