【问题标题】:How to make sure user send right data to firebase callabe function?如何确保用户将正确的数据发送到 firebase 可调用函数?
【发布时间】:2020-11-12 03:57:19
【问题描述】:

我一直在努力确保用户将正确的数据发送到 firebase HTTPSCallable 云函数。 这是我到目前为止得到的:

import * as functions from "firebase-functions";

class Person {
  name: string;
}

class ExpectingData {
  a: string;
  b: number;
  c: Person;
  d: Person[];
}

export const example = functions.https.onCall((data, context) => {
  const uid = assertUID(context);
  // with "assertUID", I can make sure user is authenticated.
  const a = assertKey(data, "a");
  // With "assertKey", I can roughly make sure user data got the right property in the first nested layer.
  const b = assertKey(data, "b");
  const c = assertKey(data, "c");
  const d = assertKey(data, "d");
});

export const assertUID = (context: any) => {
  if (!context.auth) {
    throw new functions.https.HttpsError(
      "permission-denied",
      "function called without context.auth"
    );
  } else {
    return context.auth.uid as string;
  }
};

export const assertKey = (data: any, key: string) => {
  // data[key] should not be undefined or null;
  const value = data[key];
  if (typeof value === "undefined") {
    throw new functions.https.HttpsError(
      "invalid-argument",
      `${key} is miisng`
    );
  }
  return value;
};

这是我的问题: 1. 是否有一个断言函数可以检查客户端是否准确发送了 ExpectingData 形状(或任何其他形状)的数据? 2. 是否可以在此函数中检查 typeof a 是字符串,c 是 Person 的实例,而不仅仅是检查键(如示例中的“assertKey”)?

【问题讨论】:

    标签: javascript typescript firebase google-cloud-functions


    【解决方案1】:
    1. 不,您必须手动检查属性和类型以确保您拥有所需的内容。归结为 TypeScript 必须编译为 JavaScript 的事实,除非您检查它们,否则在运行时无法保证。

    2. 任何普通的 JavaScript 对象(包括传递给您的可调用对象的对象)都没有构造函数类型,您可以在 TypeScript 中检查类型安全性。如果你想知道它是否包含你需要的一切,你将不得不深入探索每个对象及其属性。您当然可以使用typeof 通过typeof foo === "string" 来检查JavaScript 字符串。

    【讨论】:

    • 我可以递归地映射对象属性来检查数据吗,比如 (dataFromClient:any,expectingDataClass:Funcion)=>checkResult。
    • 我试过了,很沮丧。我需要学习一些基本的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2013-07-19
    相关资源
    最近更新 更多