[英]What's a simple way to do precondition checks in Firebase cloud functions in Node and Typescript?
The goal is to enforce that some required parameter has been successfully passed, it's of the right type and otherwise, throw a correct and informative error.目标是强制某些必需的参数已成功传递,它是正确的类型,否则抛出正确且信息丰富的错误。
This works, but requires too much boilerplate code.这可行,但需要太多样板代码。
export const joinSocialRequest = functions.https.onCall(async (data, context) => {
const eventId = data.eventId
if (eventId === undefined) {
throw new functions.https.HttpsError('unknown','Missing param eventId.')
}
...
}
This is better, but all errors are thrown as "Internal", which doesn't let my client engineers know what's going on!这样更好,但是所有错误都作为“内部”抛出,这不会让我的客户工程师知道发生了什么!
import { requiredStringFrom } from 'preconditions-ts';
export const acceptParticipantRequest = functions.https.onCall(async (data, context) => {
const eventId = requiredStringFrom(data, "eventId")
...
}
I can probably wrap the above in a try/catch and throw the correct error, but that means, I will need to write a lot of wrappers!我可能可以将上面的内容包装在 try/catch 中并抛出正确的错误,但这意味着,我将需要编写很多包装器!
Is there a better way?有没有更好的办法?
You could write your own validation assertion helper:您可以编写自己的验证断言助手:
function validate(condition, message, code = 'invalid-argument') {
if (!condition) {
throw new functions.https.HttpsError(code, message);
}
}
export const joinSocialRequest = functions.https.onCall(async (data, context) => {
const eventId = data.eventId
validate(eventId !== undefined, 'Missing param eventId.');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.