是否可以为 httpsCallable 函数指定输入和返回类型?

Raf*_*sas 5 firebase typescript google-cloud-functions

我正在应用程序中使用可调用函数来更新用户声明。firebase 函数位于 Typescript 中,并且有一个接口来描述函数所需的数据形状。

我想在客户端做同样的事情,这样团队中的任何开发人员都可以快速找到云函数的需求,而无需查看函数目录中的代码。

Firebase 云功能functions/src/index.ts


// This is the required data, that I would like to specify client side
interface GivePermissionsParams {
  uid: string;
  email: string;
  newClaim: Partial<Permissions>;
}

/**
 * Callable function to give a user new permissions in the form
 * of custom claims and firestore properties
 */
exports.givePermission = functions.https.onCall(
  async (data: GivePermissionsParams, context) => {
    if (!context.auth?.token.admin) {
      throw new HttpsError(
        'permission-denied',
        `Non admin user ${context.auth?.uid} attempted to update permissions`
      );
    }
    return grantPermission(data.uid, data.newClaim).then(() => {
      log(`Successfully updated permissions for ${data.email}`);
      return {
        result: `Successfully updated permissions for ${data.email}`,
      };
    });
  }
);
Run Code Online (Sandbox Code Playgroud)

客户端使用:

// firebase.ts

// I would like to specify the function param and return types here.
// eg: httpsCallable<myParamsType, myReturnType>
export const givePermission = httpsCallable(functions, 'givePermission');
Run Code Online (Sandbox Code Playgroud)
// in my reactComponent.tsx

  const changePermission = async (permission: string, value: boolean) => {

    // This payload should match the GivePermissionsParams type as defined in the functions index.ts file. 
    const functionParams = {
      uid: user.uid,
      email: user.email,
      newClaim: {[permission]: value}
    }

    const functionRes = await givePermission(functionParams);
  };
Run Code Online (Sandbox Code Playgroud)

Dha*_*raj 5

看来解决方案就是您正在尝试做的事情。您可以指定请求数据和响应的类型,如下所示:

interface ReqInterface {
  uid: string;
  email: string;
  newClaim: Partial<Permissions>;
}

interface ResInterface {
  result: string;
}

const givePermission = httpsCallable<ReqInterface, ResInterface>(functions, 'givePermission')

const { data } = await givePermission({ url })
// data is ResInterface
Run Code Online (Sandbox Code Playgroud)