簡體   English   中英

在 Node 和 Typescript 中的 Firebase 雲函數中進行前提條件檢查的簡單方法是什么?

[英]What's a simple way to do precondition checks in Firebase cloud functions in Node and Typescript?

目標是強制某些必需的參數已成功傳遞,它是正確的類型,否則拋出正確且信息豐富的錯誤。

If 語句

這可行,但需要太多樣板代碼。

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.')
    }
    ...
}

使用前提條件-ts 或前提條件NPM package

這樣更好,但是所有錯誤都作為“內部”拋出,這不會讓我的客戶工程師知道發生了什么!

import { requiredStringFrom } from 'preconditions-ts';
export const acceptParticipantRequest = functions.https.onCall(async (data, context) => {
    const eventId = requiredStringFrom(data, "eventId")
    ...
}

我可能可以將上面的內容包裝在 try/catch 中並拋出正確的錯誤,但這意味着,我將需要編寫很多包裝器!

有沒有更好的辦法?

您可以編寫自己的驗證斷言助手:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM