在 Fabric 應用程式中使用 GraphQL 讀寫資料

Fabric Apps 提供一個型別安全的 GraphQL 用戶端,讓你能在不寫原始查詢的情況下執行建立、讀取、更新和刪除操作。 客戶端會自動從你的方法呼叫產生 GraphQL,並根據你的資料模型定義回傳類型化的實體。

先決條件

  • 一個定義資料模型的 Fabric Apps 專案。 參見 定義資料模型。
  • 在本機執行或部署到 Fabric 的後端服務。

初始化用戶端

使用後端 URL、可發布金鑰和結構描述類型來將 RayfinClient 例項化:

import { RayfinClient } from '@microsoft/rayfin-client';
import type { UniversalAppSchema } from '@rayfin-app/shared';

const client = new RayfinClient<UniversalAppSchema>({
  baseUrl: import.meta.env.VITE_RAYFIN_API_URL,
  publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY,
});

generic type 參數使 TypeScript 能為所有資料操作提供自動補全與型別檢查。

這些範例假設你已啟用資料,並在通用 App 的 packages/data/src/index.ts 和共享架構合約中註冊了 Note 和 Notebook。 在平面範本中,可以改為從 rayfin/data/schema.ts 匯入你的結構型別。 參見 定義資料模型。

讀取資料

透過 client.data.<EntityName> 存取實體集合。 流暢 API 提供查詢、篩選、排序及分頁的方法。

取得一頁記錄

execute() 預設只會回傳一頁,包含 100 筆紀錄。 它不會回傳游標元資料,也不會抓取後續頁面。 對於能超過一頁的清單,使用 向前分頁。

const notes = await client.data.Note.select([
  'id',
  'title',
  'content',
  'createdAt',
  'isPinned',
]).execute();

以主鍵取得單一記錄

const note = await client.data.Note.findById('00000000-0000-0000-0000-000000000000');

findById() 若無紀錄則返回 null 。 已釋出的實作只選擇主鍵,因此不要假設其他實體欄位已被填入。 在需要欄位值時明確選擇:

const notes = await client.data.Note.select(['id', 'title', 'content'])
  .where({ id: { eq: '00000000-0000-0000-0000-000000000000' } })
  .first(1)
  .execute();

const note = notes[0] ?? null;

篩選記錄

使用以下 where() 方法篩選結果:

const pinnedNotes = await client.data.Note.select([
  'id',
  'title',
  'isPinned',
])
  .where({ isPinned: { eq: true } })
  .execute();

濾波器運算元

Operator Description Example
eq 等於 { status: { eq: 'active' } }
neq 不是平等的 { status: { neq: 'archived' } }
gt 大於 { age: { gt: 18 } }
gte 大於或等於 { age: { gte: 21 } }
lt 小於 { price: { lt: 100 } }
lte 小於或等於 { price: { lte: 50 } }
contains 包含子字串 { title: { contains: 'draft' } }

排序結果

用於 orderBy() 排序查詢結果:

const notes = await client.data.Note.select([
  'id',
  'title',
  'createdAt',
])
  .orderBy({ createdAt: 'desc' })
  .execute();

依多欄排序:

const notes = await client.data.Note.select([
  'id',
  'title',
  'isPinned',
  'createdAt',
])
  .orderBy({ isPinned: 'desc' })
  .orderBy({ createdAt: 'desc' })
  .execute();

當你使用 @one() 和 @many() 裝飾器定義關聯時,可以在同一個查詢中包含相關實體的欄位:

const notes = await client.data.Note.select([
  'id',
  'title',
  'content',
  'notebook.id',
  'notebook.name',
])
  .execute();

每筆筆記都包含其對應的筆記本資料,無需另行查詢。

將大型結果集分頁

對於大型清單,請使用游標分頁:

const page = await client.data.Note.select([
  'id',
  'title',
  'createdAt',
])
  .orderBy({ createdAt: 'desc' })
  .orderBy({ id: 'asc' })
  .first(25)
  .executePaginated();

console.log('Items:', page.items);
console.log('Has next page:', page.hasNextPage);
console.log('End cursor:', page.endCursor);

使用游標讀取下一頁:

if (page.hasNextPage) {
  if (!page.endCursor) {
    throw new Error('The next page is missing its cursor.');
  }
  const nextPage = await client.data.Note.select([
    'id',
    'title',
    'createdAt',
  ])
    .orderBy({ createdAt: 'desc' })
    .orderBy({ id: 'asc' })
    .first(25)
    .after(page.endCursor)
    .executePaginated();
}

備註

後端不會在 totalCount 類型上填入 PagedResult 屬性。 該 page.items.length 值僅計算當前頁面,而非所有匹配紀錄。

要處理所有匹配的記錄,請繼續前進直到 hasNextPage 為 false。 在不同請求中,保持選取、篩選和排序順序不變。

let cursor: string | undefined;
let matchingRecords = 0;

while (true) {
  let query = client.data.Note.select(['id'])
    .where({ isArchived: { eq: false } })
    .orderBy({ id: 'asc' })
    .first(100);

  if (cursor !== undefined) {
    query = query.after(cursor);
  }

  const page = await query.executePaginated();
  matchingRecords += page.items.length;

  if (!page.hasNextPage) {
    break;
  }
  if (!page.endCursor) {
    throw new Error('The next page is missing its cursor.');
  }
  cursor = page.endCursor;
}

console.log('Records read across all pages:', matchingRecords);

分頁無法提供跨請求的快照。 同時進行的變更會影響您讀取及計算的記錄。

彙總與群組資料

使用 aggregate() 表示伺服器端總數,並使用 groupBy() 表示每組摘要。 count()獨立 fluent 方法尚未提供,但在count聚合規範中被支援。

所有五個聚合運算(sum、max、avg、min 和 count)都需要一個數值欄位。 不要把 UUID id 或文字欄位算進去。 例如,以下查詢假設一個已註冊的 Product 實體具有必填的數值 stockQuantity 欄位:

const totals = await client.data.Product.where({ isAvailable: { eq: true } })
  .aggregate({
    matchingProducts: { count: 'stockQuantity' },
    totalStock: { sum: 'stockQuantity' },
    averageStock: { avg: 'stockQuantity' },
    lowestStock: { min: 'stockQuantity' },
    highestStock: { max: 'stockQuantity' },
  })
  .execute();

console.log(totals[0].aggregations.matchingProducts);

count 計算指定數值欄位的非空值。 使用必填數值欄位來計算匹配的列數。 如果您的實體沒有合適的欄位,請如前所述將識別碼計入 所有 頁面,而非只計算單一頁面。

對於分組總額:

const groups = await client.data.Product.groupBy(['status'])
  .aggregate({
    matchingProducts: { count: 'stockQuantity' },
    totalStock: { sum: 'stockQuantity' },
  })
  .execute();

for (const row of groups) {
  console.log(row.fields.status, row.aggregations.totalStock);
}

聚合結果是包含 fields 和 aggregations 的陣列。 總計則有一列有空的 fields 物件。 count 回傳 a number;其他操作則對於空輸入或全為 null 的輸入回傳 number | null。

在彙總前套用 where()。 不要將聚合與透過 select()、orderBy()、first() 或 after() 進行的列選取、排序或分頁結合。

建立紀錄

使用 create() 此方法插入新紀錄:

const newNote = await client.data.Note.create({
  title: 'Meeting notes',
  content: 'Discussion points from the team sync',
  isPinned: false,
  isArchived: false,
  createdAt: new Date(),
  updatedAt: new Date(),
  user_id: 'user-123',
});

該方法會回傳所建立的紀錄,包括其自動產生的 id。 當你需要額外的儲存欄位時,可以使用明確的 selected read。

建立帶有關聯性的紀錄

建立具有關聯的實體時,請傳入完整的關聯物件,或僅包含主鍵的物件:

// Option 1: Pass just the ID
const note = await client.data.Note.create({
  title: 'Weekly summary',
  content: 'Summary of this week',
  notebook: { id: '22222222-3333-4444-5555-666666666666' },
  isPinned: false,
  isArchived: false,
  createdAt: new Date(),
  updatedAt: new Date(),
});

// Option 2: Select the related fields you need before creating the note.
const notebooks = await client.data.Notebook.select(['id', 'name'])
  .where({ id: { eq: '22222222-3333-4444-5555-666666666666' } })
  .first(1)
  .execute();
const notebook = notebooks[0];
if (!notebook) {
  throw new Error('Notebook not found.');
}

const noteWithNotebook = await client.data.Note.create({
  title: 'Weekly summary',
  content: 'Summary of this week',
  notebook,
  isPinned: false,
  isArchived: false,
  createdAt: new Date(),
  updatedAt: new Date(),
});

兩種形式產生相同的結果。 當你已經知道相關實體的 ID,且想避免額外擷取一次時,請使用第一種形式。

用戶端會使用相關物件的主鍵來設定關係。 傳遞物件不會建立或更新相關的筆記本。

更新記錄

使用該 update() 方法修改現有紀錄。 傳入一個篩選物件,以及一個包含要更新欄位的物件:

await client.data.Note.update(
  { id: 'note-123' },
  {
    title: 'Updated title',
    updatedAt: new Date(),
  }
);

更新關係

要更改關係,請傳遞新的相關實體或僅傳遞其 ID:

// Move a note to a different notebook
await client.data.Note.update(
  { id: 'note-123' },
  { notebook: { id: 'new-notebook-789' } }
);

刪除記錄

使用 delete() 以下方法移除與篩選條件相符的紀錄:

await client.data.Note.delete({ id: 'note-123' });

當後端確認刪除時,方法就會解決。 如果沒有紀錄與濾波器相符,該方法仍然成功。

建立或更新紀錄

用 upsert(where, create, update) 來建立不存在的紀錄或更新現有紀錄。 在查找和建立輸入中提供相同的 ID:

const id = '11111111-2222-3333-4444-555555555555';
const now = new Date();

await client.data.Note.upsert(
  { id },
  {
    id,
    title: 'Daily summary',
    content: 'Summary of today',
    isPinned: false,
    isArchived: false,
    createdAt: now,
    updatedAt: now,
    user_id: 'user-123',
  },
  { title: 'Daily summary', updatedAt: now },
);

此輔助工具先執行讀取,接著進行獨立的建立或更新。 這不是原子性的,且並行呼叫可能發生競態。 不要把它當作事務或並行保證。

處理身份驗證

執行受保護資料操作前請先登入。 對於已部署的後端,請使用應用程式設定的 Microsoft Entra 登入流程。 以下電子郵件與密碼範例僅適用於本地後端:

await client.auth.signIn({ email, password });

// All subsequent data calls include authentication context
const notes = await client.data.Note.select(['id', 'title']).execute();

用戶端會自動將認證會話附加到所有資料 API 呼叫中。 你不需要手動傳遞代幣。

最佳做法

  • 只選擇需要的欄位 ——只取得你用來減少有效載荷大小並提升效能的欄位。
  • 大型清單請使用分頁——避免一次取得數千筆記錄,請使用 first() 和 executePaginated()。
  • 批次關係查詢 – 在同一查詢中包含相關的實體欄位,而非分別提出請求。
  • 快取頻繁存取的資料 ——將靜態參考資料儲存在記憶體中,以減少 API 呼叫。

目前的限制

  • 目前沒有 count() 獨立方法可用。 使用數值欄位 彙總,或是計算所有頁面的紀錄數。 陣列的長度只計算該頁面中回傳的紀錄。
  • 很多關係都不被支持。 使用具有兩個 @one() 導覽修飾詞的顯式聯結實體。
  • totalCount 上的 PagedResult 屬性不會由後端填入。