搭配 Data Connect 使用 Admin SDK

Firebase Admin SDK 是一組伺服器程式庫,可讓您從具備權限的環境與 Firebase 互動,執行查詢和變動等動作,例如對 Firebase Data Connect 服務執行查詢和變動,以進行大量資料管理,以及使用具備權限和模擬憑證的其他作業。

Admin SDK 提供 API,讓您在讀寫和唯讀模式中呼叫作業。透過唯讀作業,您可以安心實作管理功能,因為這些功能無法修改資料庫中的資料。

設定 Admin SDK

如要在伺服器上開始使用 Firebase Data Connect,請先安裝及設定 Node.js 適用的 Admin SDK

在指令碼中初始化 Admin SDK

如要初始化 SDK,請匯入 Data Connect 擴充功能,並宣告專案服務 ID 和位置。


import { initializeApp } from 'firebase-admin/app';
import { getDataConnect } from 'firebase-admin/data-connect';

// If you'd like to use OAuth2 flows and other credentials to log in,
// visit https://firebase.google.com/docs/admin/setup#initialize-sdk
// for alternative ways to initialize the SDK.

const app = initializeApp();

const dataConnect = getDataConnect({
    serviceId: 'serviceId',
    location: 'us-west2'
});

設計要搭配 Admin SDK 使用的查詢和異動

考量下列事項後,Admin SDK 可用於測試 Data Connect 作業。

瞭解 SDK 和 @auth(level: NO_ACCESS) 作業指令

由於 Admin SDK 具有權限,因此無論使用 @auth 指令設定的存取層級為何,Admin SDK 都能執行任何查詢和突變,包括 NO_ACCESS 層級。

如果您在用戶端作業旁,將管理查詢和變動整理到 .gql 來源檔案中,以便匯入管理指令碼,Firebase 建議您標記沒有任何授權存取層級的管理作業,或更明確地將這些作業設為 NO_ACCESS。無論是哪種方式,都能防止這類作業從用戶端或在其他非具備權限的環境中執行。

搭配 Data Connect 模擬器使用 SDK

在原型和測試環境中,對本機資料執行資料植入和其他作業可能很有用。Admin SDK 可忽略本機流程的驗證和授權,簡化工作流程。

設定 DATA_CONNECT_EMULATOR_HOST 環境變數後,Firebase Admin SDK 會自動連線至模擬器:Data Connect

export DATA_CONNECT_EMULATOR_HOST="127.0.0.1:9399"

詳情請參閱:

實作常見用途

Admin SDK可用於對重要資料執行具備權限的作業。

Admin SDK 提供兩種介面:

  • 適用於大多數讀寫或唯讀作業的一般介面,您的程式碼會實作查詢和變動,並將這些項目傳遞至讀寫 executeGraphql 方法或唯讀 executeGraphqlRead 方法。
  • 專為大量資料作業設計的介面,可提供專用的變動作業方法,而非一般 executeGraphql 方法:insertinsertManyupsertupsertMany

使用 executeGraphql 方法管理使用者資料

Admin SDK 的常見用途是管理使用者資料。

使用管理員憑證

最簡單的方法是使用管理員憑證存取使用者資料。

// User can be publicly accessible, or restricted to admins
const query = "query getProfile(id: AuthID) { user(id: $id) { id name } }";

interface UserData {
  user: {
    id: string;
    name: string;
  };
}

export interface UserVariables {
  id: string;
}

const options:GraphqlOptions<UserVariables> = { variables: { id: "QVBJcy5ndXJ1" } };

// executeGraphql
const gqlResponse = await dataConnect.executeGraphql<UserData, UserVariables>(query, options);

// executeGraphqlRead (similar to previous sample but only for read operations)
const gqlResponse = await dataConnect.executeGraphqlRead<UserData, UserVariables>(query, options);

// gqlResponse -> { "data": { "user": { "id": "QVBJcy5ndXJ1", "name": "Fred" } } }

模擬使用者憑證

此外,您可能也會希望指令碼能代表特定使用者,根據有限的憑證修改使用者資料。這種做法符合最低權限原則。

如要使用這個介面,請從符合 Authentication 權杖格式的自訂 JWT 驗證權杖收集資訊。另請參閱自訂權杖指南

// Get the current user's data
const queryGetUserImpersonation = `
    query getUser @auth(level: USER) {
        user(key: {uid_expr: "auth.uid"}) {
            id,
            name
        }
    }`;

// Impersonate a user with the specified auth claims
const optionsAuthenticated: GraphqlOptions<undefined> = {
    impersonate: {
        authClaims: {
            sub: 'QVBJcy5ndXJ1'
        }
    }
};

// executeGraphql with impersonated authenticated user scope
const gqlResponse = await dataConnect.executeGraphql<UserData, undefined>(queryGetUserImpersonation, optionsAuthenticated);

// gqlResponse -> { "data": { "user": { "id": "QVBJcy5ndXJ1", "name": "Fred" } } }

使用 executeGraphql 方法管理公開資料

您可以透過 SDK 模擬未經驗證的使用者,處理公開存取的資料。

// Query to get posts, with authentication level PUBLIC
const queryGetPostsImpersonation = `
    query getPosts @auth(level: PUBLIC) {
        posts {
          description
        }
    }`;

// Attempt to access data as an unauthenticated user
const optionsUnauthenticated: GraphqlOptions<undefined> = {
    impersonate: {
        unauthenticated: true
    }
};

// executeGraphql with impersonated unauthenticated user scope
const gqlResponse = await dataConnect.executeGraphql<UserData, undefined>(queryGetPostsImpersonation, optionsUnauthenticated);

執行大量資料作業

Firebase 建議您使用 Admin SDK,對正式版資料庫執行大量資料作業。

SDK 提供下列方法,可處理大量資料。每個方法都會根據提供的引數建構及執行 GraphQL 突變。


// Methods of the bulk operations API
// dc is a Data Connect admin instance from getDataConnect

const resp = await dc.insert("movie" /*table name*/, data[0]);
const resp = await dc.insertMany("movie" /*table name*/, data);
const resp = await dc.upsert("movie" /*table name*/, data[0]);
const resp = await dc.upsertMany("movie" /*table name*/, data);

大量作業的效能注意事項

對後端的每項要求都會產生一次 Cloud SQL 往返行程,因此批次處理的次數越多,總處理量就越高。

不過,批次大小越大,產生的 SQL 陳述式就越長。達到 PostgreSQL SQL 陳述式長度上限時,就會發生錯誤。

在實務上,請嘗試找出適合工作負載的批次大小。

後續步驟