数据建模与实体定义
data-modeling
当应用需要存储或读取数据——记录、数据库、实体、CRUD、列表、“保存/记住 X”,或带行级安全的按用户数据时使用。本应用的数据层基于 Rayfin:你在 rayfin/data/ 中用装饰器将实体声明为 TypeScript 类,在 schema 中注册它们,并通过类型化的 rayfin-client 进行读写。涵盖:定义 @entity、字段装饰器、注册实体、使用 @role 进行按实体访问控制、仅限所有者的行级安全,以及客户端查询/变更 API。触发词:数据、数据库、模型、实体、schema、表、记录、CRUD、创建、读取、更新、删除、列表、存储、保存、持久化、按用户、行级安全、RLS、访问控制、所有权。
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 114
- Forks
- 70
01 前言 Front Matter
- name
- data-modeling
- description
- Use when the app needs to store or read data — records, a database, entities, CRUD, lists, "save/remember X", or per-user data with row-level security. This app's data layer is Rayfin's: you declare entities as TypeScript classes with decorators in rayfin/data/, register them in the schema, and read/write them through the typed rayfin-client. Covers: defining an @entity, field decorators, registering it, per-entity access with @role, owner-only row-level security, and the client query/mutation API. Triggers: data, database, model, entity, schema, table, record, CRUD, create, read, update, delete, list, store, save, persist, per-user, row-level security, RLS, access control, ownership.
03 SKILL.md 正文
Data modeling — entities, schema, and row-level security
This app persists data with Rayfin data. You define entities as decorated
TypeScript classes under rayfin/data/, register them in
rayfin/data/schema.ts, and read/write them with the typed client from
src/services/rayfinClient.ts (getRayfinClient()).
The data service is already enabled in rayfin/rayfin.yml
(data: { enabled: true, dialect: mssql }), so you don't need to turn anything
on — just add entities.
Data means auth — wire it in. Rayfin data is always accessed as an authenticated user (there's no anonymous/public data access on Fabric — see Notes). So adding data isn't complete until authentication is wired in: follow the
authenticationskill (AuthProvider+bootstrapAuth()insrc/main.tsx, the route guard insrc/App.tsx). Per-user rows and row-level security key off the signed-in identity. Only a purely static page over public data (no Rayfin data) can skip auth.
Step 1 — install the data package
npm install @microsoft/rayfin-data
(@microsoft/rayfin-core — which provides the decorators — and
@microsoft/rayfin-client are already in the base app.)
Step 2 — define an entity
Create one file per entity under rayfin/data/, e.g. rayfin/data/Note.ts:
import { entity, role, text, boolean, date, uuid } from '@microsoft/rayfin-core';
@entity()
export class Note {
@uuid() id!: string;
@text({ min: 1, max: 200 }) title!: string;
@text() body!: string;
@boolean() pinned!: boolean;
@date() createdAt!: Date;
}
Common field decorators: @uuid(), @text({ min, max }), @boolean(),
@date(), plus number/relation decorators. If you're unsure of a decorator or
option, check the docs: rayfin docs search '<topic>' --module guide.
Step 3 — register it in the schema
rayfin/data/schema.ts starts empty. Add each entity to the exported schema
array and the schema type so the client is typed:
import { Note } from './Note.js';
export type UniversalAppSchema = {
Note: Note;
};
export const schema = [Note];
Import entities with the
.jsextension ('./Note.js') — Rayfin compiles the data model as ESM. The client's generic type comes fromUniversalAppSchema(already referenced bysrc/services/rayfinClient.ts).
Step 4 — read and write with the client
import { getRayfinClient } from '@/services/rayfinClient';
const client = getRayfinClient();
// query
const notes = await client.data.Note
.select(['id', 'title', 'body', 'pinned', 'createdAt'])
.orderBy({ createdAt: 'desc' })
.execute();
// create / update / delete
const note = await client.data.Note.create({ title, body, pinned: false, createdAt: new Date() });
await client.data.Note.update({ id }, { pinned: true });
await client.data.Note.delete({ id });
const one = await client.data.Note.findById(id);
Row-level security (owner-only data)
When the user wants "each person sees only their own …", first turn on
authentication (see the authentication skill), then add an owner column and
a @role policy so the platform enforces access server-side:
import { entity, role, text, boolean, date, uuid } from '@microsoft/rayfin-core';
@entity()
@role('authenticated', '*', {
policy: (claims, item) => claims.sub.eq(item.user_id),
})
export class Note {
@uuid() id!: string;
@text({ min: 1, max: 200 }) title!: string;
@text() body!: string;
@boolean() pinned!: boolean;
@date() createdAt!: Date;
@text() user_id!: string;
}
-
@role('authenticated', '*', { policy })grants all operations ('*') to authenticated users, but thepolicyrestricts each row to its owner —claims.sub(the signed-in user id) must equal the row'suser_id. -
Stamp
user_idfrom the session on create:const session = client.auth.getSession(); if (!session.isAuthenticated || !session.user) throw new Error('Not signed in.'); await client.data.Note.create({ /* … */, user_id: session.user.id });
Row-level security is enforced by Rayfin on the server — the client can't read or write another user's rows regardless of what the UI does.
Notes
- Stable features only. Use
@authenticated/@role('authenticated', …); don't reach for experimental anonymous/public access (it doesn't deploy on Fabric). If asked for public data, say so and use authenticated access. - Deploy with
npm run rayfin:upwhen ready; a data-model change ships and migrates on that deploy.
04 同仓库更多 Skills
visuals
Use when user wants to incorporate charts, graphs, data grid, or other visual representations of data into their project. Use VegaVisual and DataGrid components to create these visuals, utilizing the shared DataTable input, formatting, theme, and interactivity. Covers the onInteraction selection/click events host apps consume, named multi-table data input for layered overlays and reference lines, and Vega-Lite native selections.
schema-discovery
Explore Power BI semantic model schemas using DAX INFO functions. Progressive metadata discovery strategy, scope estimation, and narrowing techniques for tables, columns, measures, and relationships.
rayfin
Use when doing ANY task involving Rayfin — scaffolding, data models, decorators, auth, deployment, CLI commands, or client setup. Triggers: rayfin, rayfin init, rayfin up, rayfin login, RayfinClient, @entity, @role, @anonymous, @authenticated, @text, @uuid, @int, @decimal, @boolean, @date, @email, @set, @one, @many, DAB, Data API Builder, rayfin.yml, publishableKey, signUp, signIn, signOut, sendMagicLink, handleMagicLinkCallback, ensureSignedInWithFabric, Fabric SSO, Entra ID, rayfin up db apply, rayfin up staticapp deploy, schema.ts, OpaqueSession, onSessionChange, GraphQL select, GraphQL create, GraphQL update, GraphQL delete, findById, executePaginated, RLS policy, row-level security, claims.sub, claims.email, TC39 decorators, config generation, dialect, mssql, postgresql
rayfin-connectors
Use for Rayfin connectors that wire existing Fabric SQL data sources (Lakehouse, Warehouse, SQL Database) into an app as GraphQL-backed entities. Triggers: rayfin connector, rayfin up connector apply, connectors:, fabric-sqlanalytics, fabric-warehouse, fabric-sqldatabase, kusto, kql, eventhouse, workspaceId, itemId, operations:, AppConnectorsSchema, ConnectorsSchema, rayfin/connectors/, metadata.json, connector @role policy, connector claims.sub filter, connector claims.email filter, ConnectorsRayfinClient, rayfin-client.ts, client.connectors, connectorConfig, GraphQLBackedConnector, RestrictedDataApi, schema.ts aggregate, generate entities from metadata, add a use case on specific entities, wire connector into client, call a connector from the SDK, rayfin connector inspect, inspect connector data, sample connector rows, fabric-semanticmodel, --entity, --query, DAX EVALUATE, read-only sample query, rayfin connector search, discover connectable sources, find fabric sources to add, --all-workspaces, --workspace-id, connector search interactive picker, rayfin connector invoke, invoke a connector operation, run executeQuery, --input, --file, RAYFIN_FEATURE_FLAGS, resultSetRowCountLimit, limit rows, row limit, cap rows, too many rows, overflow
query-design
Separates DAX data-fetching from TypeScript presentation. Guides when to use DAX vs. TypeScript vs. Vega-Lite for aggregation, total rows, FORMAT(), SELECTCOLUMNS, BLANK handling, filtering, multi-grain queries, cross-filtering and cross-highlight subset/overlay queries, and format strings.
playwright-cli
Automate browser interactions, test web pages and work with Playwright tests.