### Run the GraphQL server Source: https://fate.technology/example/server-graphql/README Run these commands from the example directory to set up and start the server. The server defaults to http://localhost:9021/graphql. ```sh vp run dev:setup vp run prisma migrate dev vp run dev ``` -------------------------------- ### Client setup with createFateClient Source: https://fate.technology/guide/live-views Configure the native transport and point the client at your fate endpoint. Live views use `GET /fate/live` for the SSE stream and `POST /fate/live` for control messages. ```tsx import { FateClient } from 'react-fate'; import { createFateClient } from 'react-fate/client'; export function App() { const fate = useMemo( () => createFateClient({ fetch: (input, init) => fetch(input, { ...init, credentials: 'include', }), url: `${env('SERVER_URL')}/fate`, }), [], ); return {/* Components go here */}; } ``` -------------------------------- ### Postgres database setup SQL Source: https://fate.technology/CONTRIBUTING SQL commands to create the 'fate' role and database, and set the database owner. Run after starting Postgres via docker-compose or local setup. ```sql CREATE ROLE fate WITH LOGIN PASSWORD 'echo'; CREATE DATABASE fate; ALTER DATABASE fate OWNER TO fate; ``` -------------------------------- ### useLiveView example Source: https://fate.technology/api/react-fate/functions/useLiveView Resolves a reference against a view and subscribes to live server updates for that selection. The example appears twice in the source, once for each call signature overload. ```ts const post = useLiveView(PostView, postRef); ``` -------------------------------- ### Install @nkzw/fate with npm, pnpm, and yarn Source: https://fate.technology/guide/getting-started Install the core `@nkzw/fate` package. Use this on the server if it's a separate package, or on the client for a barebones integration without a framework adapter. ```bash npm add @nkzw/fate ``` ```bash pnpm add @nkzw/fate ``` ```bash yarn add @nkzw/fate ``` -------------------------------- ### Create a new Void app with the Void template Source: https://fate.technology/integrations/void Use this command to scaffold a new Void app with the Void template, which includes client, routes, Drizzle setup, live transport, auth wiring, and generated fate client setup. ```sh vp create fate my-app --template void ``` -------------------------------- ### Install vue-fate with pnpm Source: https://fate.technology/packages/fate/docs/guide/vue No description ```bash pnpm add vue-fate ``` -------------------------------- ### Create full GraphQL + Prisma template Source: https://fate.technology/packages/fate/docs/integrations/graphql Creates a full GraphQL + Prisma example app. Use this template when you want a complete reference implementation. ```bash vp create fate my-app --template graphql ``` -------------------------------- ### Install vue-fate with yarn Source: https://fate.technology/packages/fate/docs/guide/vue No description ```bash yarn add vue-fate ``` -------------------------------- ### Install vue-fate with npm, pnpm, and yarn Source: https://fate.technology/guide/getting-started Install the Vue client package `vue-fate` using your preferred package manager. ```bash npm add vue-fate ``` ```bash pnpm add vue-fate ``` ```bash yarn add vue-fate ``` -------------------------------- ### Install vue-fate with npm Source: https://fate.technology/packages/fate/docs/guide/vue No description ```bash npm add vue-fate ``` -------------------------------- ### Add IndexedDB adapter with vp add Source: https://fate.technology/guide/persistence Install the IndexedDB storage adapter for the persistence layer. ```sh vp add @nkzw/fate-indexeddb ``` -------------------------------- ### useView example (TypeScript) Source: https://fate.technology/api/react-fate/functions/useView Example usage of useView() with a view and a reference. The function subscribes to updates for the selection. ```ts const post = useView(PostView, postRef); ``` -------------------------------- ### Install react-fate with npm, pnpm, and yarn Source: https://fate.technology/guide/getting-started Install the React client package `react-fate` using your preferred package manager. Requires React 19.2+. ```bash npm add react-fate ``` ```bash pnpm add react-fate ``` ```bash yarn add react-fate ``` -------------------------------- ### Install FateClient as a Vue plugin Source: https://fate.technology/guide/vue Install the FateClient as a Vue plugin using createFatePlugin. This is an alternative to using the FateClient provider component. ```ts import { createApp } from 'vue'; import { createFatePlugin } from 'vue-fate'; import { createFateClient } from 'vue-fate/client'; import App from './App.vue'; const fate = createFateClient({ url: '/fate' }); createApp(App).use(createFatePlugin(fate)).mount('#app'); ``` -------------------------------- ### Add packages to an existing Void project (React) Source: https://fate.technology/integrations/void Install the required packages for a React-based Void project. ```sh pnpm add @nkzw/fate react-fate void-fate void @void/react ``` -------------------------------- ### Create a fate client with FateClient provider (React and Vue) Source: https://fate.technology/packages/fate/docs/integrations/server Create a fate client instance and provide it to your app with the FateClient provider. The React example uses useMemo and the Vue example uses computed. Both configure httpBatchLink with credentials: 'include' and the SERVER_URL environment variable. ```tsx import { httpBatchLink } from '@trpc/client'; import { FateClient } from 'react-fate'; import { createFateClient } from 'react-fate/client'; export function App() { const fate = useMemo( () => createFateClient({ links: [ httpBatchLink({ fetch: (input, init) => fetch(input, { ...init, credentials: 'include', }), url: `${env('SERVER_URL')}/trpc`, }), ], }), [], ); return {/* Components go here */}; } ``` ```vue ``` -------------------------------- ### Create fate app with GraphQL templates Source: https://fate.technology/integrations/graphql Two CLI commands to scaffold a fate app: the first creates a client-only GraphQL integration template, the second creates a full GraphQL + Prisma example app. The client-only template is the smallest reference for the integration. ```bash vp create fate my-app --template graphql-client ``` ```bash vp create fate my-app --template graphql ``` -------------------------------- ### Add packages to an existing Void project (Vue) Source: https://fate.technology/integrations/void Install the required packages for a Vue-based Void project. ```sh pnpm add @nkzw/fate vue-fate void-fate void @void/vue ``` -------------------------------- ### Prisma tRPC Setup with createPrismaFate Source: https://fate.technology/integrations/server Sets up the Prisma tRPC integration by creating a router and procedure, then creating fate with createPrismaFate. ```tsx import { initTRPC } from '@trpc/server'; import { createPrismaFate } from '@nkzw/fate/server/prisma'; import type { AppContext } from './context.ts'; import { Root } from './views.ts'; const t = initTRPC.context().create(); export const router = t.router; export const procedure = t.procedure; export const fate = createPrismaFate({ procedure, views: Root, }); ``` -------------------------------- ### Create a new Void project with fate template Source: https://fate.technology/integrations/cloudflare Use the Void CLI to create a new project with the fate template. The command creates a project named 'my-app' using the 'void' template. After creation, run the setup and development commands. Add '--framework vue' to use Vue instead of React. ```sh vp create fate my-app --template void cd my-app vp run dev:setup vp run dev ``` -------------------------------- ### Import dataView from @nkzw/fate/server Source: https://fate.technology/api/%40nkzw/fate/server Shows how to import the dataView function from the @nkzw/fate/server library. This is the only code example on the page. ```typescript import { dataView } from '@nkzw/fate/server'; ``` -------------------------------- ### Import view from @nkzw/fate Source: https://fate.technology/api/%40nkzw/fate Shows how to import the view function from the @nkzw/fate core library. This is the only code example on the page. ```typescript import { view } from '@nkzw/fate'; ``` -------------------------------- ### useRequest with arguments for pagination Source: https://fate.technology/guide/requests Pass arguments to useRequest for pagination, filtering, or sorting. Example fetches the first 10 posts. ```tsx const { posts } = useRequest({ posts: { args: { first: 10 }, list: PostView, }, }); ``` -------------------------------- ### Customize fetch with credentials Source: https://fate.technology/integrations/graphql Use the fetch option to customize credentials or reuse an application fetch wrapper. This example includes credentials: 'include' and uses a server URL from env. ```tsx const fate = createFateClient({ fetch: (input, init) => fetch(input, { ...init, credentials: 'include', }), url: `${env('SERVER_URL')}/graphql`, }); ``` -------------------------------- ### Apply data view to a query (client view example) Source: https://fate.technology/integrations/server Shows a client-side view that attempts to select `password`. Because the server data view excludes it, this causes a type error and is ignored at runtime, keeping private fields hidden. ```tsx const UserData = view()({ // Type-error + ignored during runtime. password: true, }); ``` -------------------------------- ### Define CommentView and CommentConnectionView for useListView Source: https://fate.technology/guide/list-views Defines a CommentView and a CommentConnectionView with args and items, then uses them in a PostView. This setup is required before using the useListView hook. ```tsx import { useListView, ViewRef } from 'react-fate'; const CommentView = view()({ content: true, id: true, }); const CommentConnectionView = { args: { first: 10 }, items: { node: CommentView, }, }; const PostView = view()({ comments: CommentConnectionView, }); ``` -------------------------------- ### Deferred fields with useView and useListView Source: https://fate.technology/guide/deferred-views Example showing how to define a view with a deferred field using defer, then use useView to read the parent view and useListView to resolve the deferred handle. The deferred field is fetched separately and suspends the component that tries to resolve it. ```tsx import { Suspense } from 'react'; import { defer, useListView, useView, view, Deferred, ViewRef } from 'react-fate'; const CommentView = view()({ content: true, id: true, }); const CommentConnectionView = { args: { first: 3 }, items: { node: CommentView }, }; const PostView = view()({ comments: defer(CommentConnectionView), content: true, id: true, title: true, }); function PostCard({ post: postRef }: { post: ViewRef<'Post'> }) { const post = useView(PostView, postRef); return (

{post.title}

{post.content}

}>
); } function PostComments({ comments, }: { comments: Deferred<{ items: ReadonlyArray<{ node: ViewRef<'Comment'> }> }>; }) { const [items, loadNext] = useListView(CommentConnectionView, comments); return (
{items.map(({ node }) => ( ))} {loadNext ? : null}
); } ``` -------------------------------- ### Typical React data fetching with useFetch Source: https://fate.technology/posts/introducing-fate Shows a common pattern for data fetching in React, handling loading, error, and null states. This is presented as an example of what fate aims to improve. ```tsx const { data: post, isLoading, isError } = useFetch(…) if (isLoading) return ; if (isError) return ; if (!post) return ; return ; ``` -------------------------------- ### Set up live event bus and expose native handler Source: https://fate.technology/guide/live-views Creates a live event bus and passes it to createFateServer, then exposes the native handler via app.all. This is required for live views to work. ```tsx import { createFateServer, createHonoFateHandler, createLiveEventBus } from '@nkzw/fate/server'; import type { AppContext } from './context.ts'; import { sources } from './sources.ts'; import { Root } from './views.ts'; export const live = createLiveEventBus(); export const fate = createFateServer({ live, roots: Root, sources, }); app.all('/fate/*', createHonoFateHandler(fate)); ``` -------------------------------- ### createFateServer() Source: https://fate.technology/api/@nkzw/fate/server/functions/createFateServer Documentation for the createFateServer function, including its signature, type parameters, parameters, and return type. ```APIDOC ## createFateServer() ### Description Creates a FateServer instance with the provided options, enabling the server to handle queries, lists, and mutations defined by the user. ### Signature `createFateServer(__namedParameters): FateServer, AdapterContext>` ### Type Parameters - **Context** (`unknown`) - Default: `unknown` - The context type for the server. - **Roots** (`RootMap`) - Default: `RootMap` - The root map type. - **Queries** (`Record>`) - Default: `Record` - The query definitions. - **Lists** (`Record>`) - Default: `Record` - The list definitions. - **Mutations** (`Record>`) - Default: `Record` - The mutation definitions. - **AdapterContext** (`unknown`) - Default: `unknown` - The adapter context type. ### Parameters - **__namedParameters** (`FateServerOptions`) - Required - The options for creating the FateServer. ### Returns - **FateServer, AdapterContext>** - The created FateServer instance. ### Defined in `fate/src/server/http.ts:630` ``` -------------------------------- ### createFateClient with live URL Source: https://fate.technology/integrations/graphql Configures GraphQL live views using GraphQL SSE. Requires `graphql-sse` in the client package and `live` enabled. ```tsx const fate = createFateClient({ live: { url: 'https://api.example.com/graphql/stream', }, url: 'https://api.example.com/graphql', }); ``` -------------------------------- ### getScopedArgs Source: https://fate.technology/api/%40nkzw/fate/server Gets scoped arguments for a source. ```APIDOC ## getScopedArgs ### Description Gets scoped arguments for a source. ### Signature ```ts import { getScopedArgs } from '@nkzw/fate/server'; ``` ### Parameters - `args` (Object) - Required - The arguments. - `scope` (Object) - Required - The scope. ### Returns - `Object` - The scoped arguments. ``` -------------------------------- ### Create Void live adapter and Fate server Source: https://fate.technology/integrations/void Sets up a Void live adapter with createVoidFateLive, passes its live event bus to createFateServer, and exports the adapter. Requires a Drizzle source adapter and a context factory. ```tsx import { createFateServer } from '@nkzw/fate/server'; import { createDrizzleSourceAdapter } from '@nkzw/fate/server/drizzle'; import { createVoidFateLive } from 'void-fate/server'; import { db } from 'void/db'; import schema from '../db/schema.ts'; import { createContext } from './context.ts'; import { Root } from './views.ts'; const sources = createDrizzleSourceAdapter({ db, schema, views: Root, }); export const fateLive = createVoidFateLive(); export const { live } = fateLive; export const fateServer = createFateServer({ context: ({ request }) => createContext({ request }), live, roots: Root, sources, }); ``` -------------------------------- ### Set up native fate server with Prisma and Hono Source: https://fate.technology/integrations/server Sets up the native fate protocol with a Prisma source adapter, `createFateServer`, and a Hono handler. Exposes `POST /fate` and `POST /fate/live` endpoints. ```tsx import { createFateServer, createHonoFateHandler } from '@nkzw/fate/server'; import { createPrismaSourceAdapter } from '@nkzw/fate/server/prisma'; import { Hono } from 'hono'; import type { AppContext } from './context.ts'; import { prisma } from './prisma.ts'; import { Root, userDataView } from './views.ts'; export { Root } from './views.ts'; const sources = createPrismaSourceAdapter({ prisma: (ctx) => ctx.prisma, views: Root, }); export const fate = createFateServer({ context: async ({ adapterContext }) => ({ prisma, request: adapterContext.req.raw, sessionUser: await getSessionUser(adapterContext.req.raw), }), queries: { viewer: { resolve: ({ ctx, select }) => sources.resolveById({ ctx, id: ctx.sessionUser.id, input: { select }, view: userDataView, }), }, }, roots: Root, sources, }); const app = new Hono(); const handler = createHonoFateHandler(fate); app.post('/fate', handler); app.post('/fate/live', handler); ``` -------------------------------- ### getNestedSelection Source: https://fate.technology/api/%40nkzw/fate/server Gets nested selection from a selection set. ```APIDOC ## getNestedSelection ### Description Gets nested selection from a selection set. ### Signature ```ts import { getNestedSelection } from '@nkzw/fate/server'; ``` ### Parameters - `selection` (FieldSelection) - Required - The selection set. ### Returns - `FieldSelection` - The nested selection. ``` -------------------------------- ### createFateServer Source: https://fate.technology/api/%40nkzw/fate/server Creates a Fate server instance. ```APIDOC ## createFateServer ### Description Creates a Fate server instance. ### Signature ```ts import { createFateServer } from '@nkzw/fate/server'; ``` ### Parameters - `manifest` (FateServerManifest) - Required - The server manifest. ### Returns - `FateServer` - The created Fate server instance. ``` -------------------------------- ### createClient() Source: https://fate.technology/packages/react-fate/docs/api/functions/createClient Documentation for the createClient function, including its signature, type parameters, parameters, and return type. ```APIDOC ## Function: createClient() ### Description Creates a Fate client instance with the provided options. The client is typed with the given roots and mutations, and supports a hydration scope. ### Signature `createClient(options): FateClient` ### Type Parameters - **T** - Extends `[FateRoots, FateMutations]`, defaults to `[Record>, Record>]` - **HydrationScope** - Extends `string`, defaults to `string` ### Parameters - **options** (`FateClientOptions`) - The client options. ### Returns - `FateClient` - The created Fate client. ``` -------------------------------- ### useRequest Source: https://fate.technology/packages/react-fate/docs/api/functions/useRequest Documentation for the useRequest function, including its signature, parameters, return type, and an example. ```APIDOC ## useRequest(request, options?): RequestResult ### Description Declares the data a screen needs and kicks off fetching, suspending while the request resolves. ### Signature `useRequest(request, options?): RequestResult` ### Type Parameters - **R** - extends `Request$1` - **O** - extends `FateRoots` = `FateRoots` ### Parameters - **request** (`R`) - Required - The request object describing the data needed. - **options?** (`Readonly<{ mode?: RequestMode; persist?: Readonly<{ maxAge: number; }>; }>`) - Optional - Configuration options for the request. ### Returns `RequestResult` ### Example ```ts const { posts } = useRequest({ posts: { list: PostView } }); ``` ``` -------------------------------- ### Create a new Void app with Vue framework Source: https://fate.technology/integrations/void Use this command to create a new Void app with the Vue framework instead of React. ```sh vp create fate my-app --template void --framework vue ``` -------------------------------- ### Replace useView with useLiveView Source: https://fate.technology/posts/fate-1.0 Shows the diff to switch from useView to useLiveView for real-time updates via SSE. ```diff - const post = useView(PostView, postRef); + const post = useLiveView(PostView, postRef); ``` -------------------------------- ### dataView() usage example Source: https://fate.technology/api/%40nkzw/fate/server/functions/dataView Declares a server data view for a PostItem, exposing the 'id' and 'title' fields to the client. ```typescript const Post = dataView('Post')({ id: true, title: true, }); ``` -------------------------------- ### useRequest() example Source: https://fate.technology/api/react-fate/functions/useRequest Declares a request for posts using the PostView component and destructures the result. The hook suspends while the request resolves. ```ts const { posts } = useRequest({ posts: { list: PostView } }); ``` -------------------------------- ### new FateClient(options) Source: https://fate.technology/api/%40nkzw/fate/classes/FateClient Creates a new FateClient instance with the provided options. The constructor initializes the client with roots, mutations, and hydration scope. ```APIDOC ## Constructor ### Description Creates a new FateClient instance. ### Signature `new FateClient(options: FateClientOptions): FateClient` ### Parameters - **options** (`FateClientOptions`) - Required - Configuration options for the client. ### Returns `FateClient` ``` -------------------------------- ### Create a new fate app with Vite+ Source: https://fate.technology/guide/getting-started Run this command to scaffold a new fate project. The template selector can create React or Vue clients for Void, tRPC, GraphQL, or a fate client for an existing GraphQL server. React is the default UI framework; pass `--framework vue` to choose Vue. ```bash vp create fate my-app ``` -------------------------------- ### Configure Vite plugin for Vue with native transport Source: https://fate.technology/integrations/server Configures the Vite plugin for Vue with the native transport. The plugin handles the HTTP transport setup. ```ts import vue from '@vitejs/plugin-vue'; import { fate } from 'vue-fate/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ vue(), fate({ module: '@your-org/server/fate.ts', transport: 'native', }), ], }); ``` -------------------------------- ### Configure Vite plugin for React with native transport Source: https://fate.technology/integrations/server Configures the Vite plugin for React with the native transport. The plugin handles the HTTP transport setup. ```tsx import { fate } from 'react-fate/vite'; import { defineConfig } from 'vite'; export default defineConfig({ plugins: [ fate({ module: '@your-org/server/fate.ts', transport: 'native', }), ], }); ``` -------------------------------- ### liveConnectionTopic(procedure, args?) Source: https://fate.technology/api/%40nkzw/fate/functions/liveConnectionTopic Generates a topic string for live connections based on a procedure name and optional arguments. ```APIDOC ## Function: liveConnectionTopic() ### Description Generates a topic string for live connections based on a procedure name and optional arguments. ### Signature `liveConnectionTopic(procedure: string, args?: Record): string` ### Parameters - **procedure** (`string`) - Required - The procedure name. - **args** (`Record`) - Optional - Additional arguments for the topic. ### Returns `string` - The generated topic string. ### Source Defined in: fate/src/liveTopics.ts:20 ``` -------------------------------- ### createFateFetchHandler() Source: https://fate.technology/api/%40nkzw/fate/server/functions/createFateFetchHandler Creates a fetch handler for a FateServer instance. The handler processes incoming requests and returns a Response. ```APIDOC ## Function: createFateFetchHandler() ### Description Creates a fetch handler for a FateServer instance. The returned handler processes a request and returns a Promise resolving to a Response. ### Signature `createFateFetchHandler(server): (request, adapterContext?) => Promise` ### Type Parameters - **AdapterContext** - The adapter context type. ### Parameters - **server** (`FateServer`) - The FateServer instance to create the handler for. ### Returns A function that takes a `request` and an optional `adapterContext` and returns a `Promise`. ### Defined in fate/src/server/http.ts:1466 ``` -------------------------------- ### LikeButton with useTransition and fate.actions Source: https://fate.technology/guide/actions Use fate.actions.post.like with useActionState and useTransition when not using an async component library. The action is started in a transition, and the button is disabled while pending. ```tsx const LikeButton = ({ post }: { post: { id: string; likes: number } }) => { const fate = useFateClient(); const [, startTransition] = useTransition(); const [result, like, isPending] = useActionState(fate.actions.post.like, null); return ( ); }; ``` -------------------------------- ### useRequest with stale-while-revalidate mode Source: https://fate.technology/guide/requests Pass a request mode as an option to useRequest. This example uses stale-while-revalidate to return cached data and fetch fresh data in the background. ```tsx const { posts } = useRequest( { posts: { list: PostView }, }, { mode: 'stale-while-revalidate', }, ); ``` -------------------------------- ### Request multiple objects by IDs with useRequest Source: https://fate.technology/guide/requests Fetches multiple objects by specifying an array of ids and a view. The example requests posts with ids '6' and '7'. ```tsx const { posts } = useRequest({ posts: { ids: ['6', '7'], view: PostView }, }); ``` -------------------------------- ### createFateServer() Source: https://fate.technology/api/%40nkzw/fate/server/functions/createFateServer Creates a FateServer instance with a native Fate API. The function accepts a FateServerOptions object and returns a FateServer instance. ```APIDOC ## Function: createFateServer() ### Description Creates a FateServer instance with a native Fate API. The function accepts a FateServerOptions object and returns a FateServer instance. ### Signature `createFateServer(__namedParameters): FateServer, AdapterContext>` ### Type Parameters - **Context** (`unknown`) - Default: `unknown` - **Roots** (`RootMap`) - Default: `RootMap` - **Queries** (`Record>`) - Default: `Record` - **Lists** (`Record>`) - Default: `Record` - **Mutations** (`Record>`) - Default: `Record` - **AdapterContext** (`unknown`) - Default: `unknown` ### Parameters - **__namedParameters** (`FateServerOptions`) - Required - The options for creating the FateServer. ### Returns - **FateServer, AdapterContext>** - The created FateServer instance. ### Defined in fate/src/server/http.ts:630 ``` -------------------------------- ### Request a single object by ID with useRequest Source: https://fate.technology/guide/requests Fetches a single object by specifying the id and view in the useRequest hook. The example requests a post with id '12'. ```tsx const { post } = useRequest({ post: { id: '12', view: PostView }, }); ``` -------------------------------- ### createPrismaFate (Factory) Source: https://fate.technology/api/@nkzw/fate/server/prisma/functions/createPrismaFate Creates a complete Prisma data source adapter, providing methods like fetchById, fetchConnection, and createPlan for a given Context and Procedure. ```APIDOC ## createPrismaFate(__namedParameters): object ### Description Creates a data source adapter for Prisma-based apps, providing a set of functions for fetching and resolving data. ### Parameters #### __namedParameters - `PrismaSourceAdapterOptions` & `object` - Required - Configuration options for the adapter. ### Returns An object with the following methods: - `connection` - `connection` - `connection` - `fetchById` - `fetchByIds` - `fetchConnection` - `getSource` - `procedures` - `registry` - `resolveById` ### Methods #### connection - **Signature**: `(options) => ConnectionProcedure<...>` - **Description**: Creates a connection procedure for paginated list queries. - **Parameters**: `options` (object) - Required - `defaultSize` (number) - Optional - Default page size. - `getCursor` ((node) => string) - Optional - Function to extract cursor from a node. - `input` (TAdditionalInput) - Optional - Additional input schema. - `map` (MapFn) - Optional - Mapping function. - `query` (QueryFn) - Required - Query function. #### `createPlan` - **Signature**: `(__namedParameters) => object` - **Description**: Creates a source plan for a data view. - **Parameters**: `__namedParameters` (SourceInput & object) - Required - **Returns**: object with properties: `args`, `ctx`, `resolve`, `resolveMany`, `root`, `selectedPaths`, `source`, `view`. #### `fetchById` - **Signature**: `(__namedParameters) => Promise` - **Description**: Fetches a single record by ID. - **Parameters**: `__namedParameters` (object) - Required - `ctx` (Context) - Required - `extra?` (FateRecord) - Optional - `id` (string) - Required - `plan` (SourcePlan) - Required - **Returns**: Promise resolving to Item or null. #### `fetchByIds` - **Signature**: `(__namedParameters) => Promise` - **Description**: Fetches multiple records by IDs. - **Parameters**: `__namedParameters` (object) - Required - `ctx` (Context) - Required - `extra?` (FateRecord) - Optional - `ids` (string[]) - Required - `plan` (SourcePlan) - Required - **Returns**: Promise resolving to array of Items. #### `fetchConnection` - **Signature**: `(__namedParameters) => Promise` - **Description**: Fetches a paginated list of items. - **Parameters**: `__namedParameters` (object) - Required - `ctx` (Context) - Required - `cursor?` (string) - Optional - `direction` ('backward' | 'forward') - Required - `extra?` (FateRecord) - Optional - `plan` (SourcePlan) - Required - `skip?` (number) - Optional - `take` (number) - Required - **Returns**: Promise resolving to array of Items. #### `getSource` - **Signature**: `(target) => SourceDefinition` - **Description**: Returns the source definition for a given target. - **Parameters**: `target` (SourceTarget) - Required #### `procedures` - **Signature**: `(input) => SourceProcedureResult<...>` - **Description**: Creates procedure result items based on input configuration. - **Parameters**: `input` (ViewProcedureInput) - Required #### `registry` - **Property**: `SourceRegistry` - A registry of sources. #### `resolveById` - **Signature**: `(__namedParameters) => Promise` - **Description**: Resolves a record by ID using input and view targets. - **Parameters**: `__namedParameters` (object) - Required - `ctx` (Context) - Required - `extra?` (FateRecord) - Optional - `id` (string) - Required - `input` (SourceInput) - Required - `view` (ViewTarget) - Required - **Returns**: Promise resolving to FateRecord or null. ``` -------------------------------- ### createClient() Source: https://fate.technology/api/%40nkzw/fate/functions/createClient Creates a Fate client instance with the provided options. The client is typed with the given roots, mutations, and hydration scope. ```APIDOC ## createClient() ### Description Creates a Fate client instance with the provided options. The client is typed with the given roots, mutations, and hydration scope. ### Signature `createClient(options): FateClient` ### Type Parameters - **T** - extends [`FateRoots`, `FateMutations`] = [`Record>`, `Record>`] - **HydrationScope** - extends `string` = `string` ### Parameters - **options** (`FateClientOptions`) - Required - The client options. ### Returns `FateClient` ``` -------------------------------- ### Reset action state after error with 'reset' token Source: https://fate.technology/guide/actions Use the 'reset' token to clear the action state after a failure without re-invoking the action. This example resets the error state after 3 seconds using a timeout. ```tsx const [result, like] = useActionState(fate.actions.post.like, null); useEffect(() => { if (result?.error) { // Reset the action state after 3 seconds. const timeout = setTimeout(() => startTransition(() => like('reset')), 3000); return () => clearTimeout(timeout); } }, [like, result]); ``` -------------------------------- ### fetchList()? Source: https://fate.technology/api/%40nkzw/fate/interfaces/Transport Fetches a list of items using a procedure, returning items and pagination information. ```APIDOC ## fetchList()? ### Description Fetches a list of items using a procedure, returning items and pagination information. ### Method fetchList ### Parameters - **proc** (`string`) - Required - The procedure to execute. - **select** (`Iterable`) - Required - The fields to select. - **args?** (`FateRecord`) - Optional - Additional arguments. ### Returns `Promise<{ items: object[]; pagination: Pagination; }>` ``` -------------------------------- ### Override node ID encoding/decoding for GraphQL Source: https://fate.technology/integrations/graphql Overrides the default ID conversion. The default sends `${type}-${id}` and strips the prefix. This example uses base64-encoded Relay-style IDs and throws an error if the node type mismatches. ```tsx const fate = createFateClient({ decodeNodeId: (type, id) => { const [nodeType, nodeId] = atob(String(id)).split(':'); if (nodeType !== type) { throw new Error(`Expected a ${type} node id.`); } return nodeId; }, encodeNodeId: (type, id) => btoa(`${type}:${id}`), url: '/graphql', }); ``` -------------------------------- ### Add route for live SSE transport Source: https://fate.technology/integrations/void Adds a second route for the live SSE transport using defineVoidFateLiveRoute. Handles GET /fate-live SSE connections and POST /fate-live control messages. void-fate does not use WebSockets. ```tsx // routes/fate-live.ts import { defineVoidFateLiveRoute } from 'void-fate/server'; import { fateStream } from '../src/fate/live.ts'; export const { GET, POST } = defineVoidFateLiveRoute(fateStream); ``` -------------------------------- ### createDrizzleSourceAdapter() Source: https://fate.technology/packages/fate/docs/api/server/drizzle/functions/createDrizzleSourceAdapter Creates a DrizzleSourceAdapter instance for the provided context and options. ```APIDOC ## Function: createDrizzleSourceAdapter() ### Description Creates a DrizzleSourceAdapter instance for the provided context and options. ### Signature `createDrizzleSourceAdapter(__namedParameters: DrizzleSourceAdapterOptions): DrizzleSourceAdapter` ### Type Parameters - **Context** - The context type used by the adapter. ### Parameters - **__namedParameters** (`DrizzleSourceAdapterOptions`) - The options for creating the adapter. ### Returns - **DrizzleSourceAdapter** - The created Drizzle source adapter. ``` -------------------------------- ### Custom Prisma Query with createPlan and toPrismaSelect Source: https://fate.technology/integrations/server Shows how to use fate.createPlan and toPrismaSelect for custom Prisma queries and mutations. ```tsx import { toPrismaSelect } from '@nkzw/fate/server'; const plan = fate.createPlan({ ...input, ctx, view: postDataView, }); const post = await ctx.prisma.post.update({ data: { likes: { increment: 1, }, }, select: toPrismaSelect(plan), where: { id: input.id }, }); ``` -------------------------------- ### Use useRequest and useListView in a Vue component Source: https://fate.technology/guide/vue Declare data needs with useRequest in a Vue single-file component. Await ready() to participate in Vue Suspense. Use useListView to get paginated items and a loadNext function for a 'Load more' button. ```vue ``` -------------------------------- ### Create GraphQL client and provide via FateClient (React and Vue) Source: https://fate.technology/packages/fate/docs/integrations/graphql Create a GraphQL client with createFateClient and provide it through the FateClient provider for React or Vue. The headers function supplies an authorization token, and the client is passed to the provider. ```tsx import { FateClient } from 'react-fate'; import { createFateClient } from 'react-fate/client'; const fate = createFateClient({ headers: () => ({ authorization: `Bearer ${token}`, }), url: 'https://api.example.com/graphql', }); export function App() { return {/* Components go here */}; } ``` ```vue ``` -------------------------------- ### TypeConfig Source: https://fate.technology/api/@nkzw/fate/type-aliases/TypeConfig Type alias for configuration of a server entity type used by the client cache. It defines the structure for entity type configuration, including optional relation fields, a function to get the record ID, and the entity type name. ```APIDOC ## TypeConfig ### Description Configuration for a server entity type used by the client cache. ### Type Alias `TypeConfig` = `object` ### Properties #### fields? (optional) - **Type**: `Record` - **Description**: Optional map of field names to relation descriptors. #### getId - **Type**: `(record: unknown) => string | number` - **Description**: Function that takes a record (unknown) and returns the record's ID as a string or number. #### type - **Type**: `string` - **Description**: The entity type name as a string. ### Defined in fate/src/types.ts:123 ``` -------------------------------- ### Import createPrismaFate from @nkzw/fate/server/prisma Source: https://fate.technology/api/%40nkzw/fate/server/prisma Import the createPrismaFate function from the @nkzw/fate/server/prisma module. This is the entry point for integrating Prisma with fate. ```ts import { createPrismaFate } from '@nkzw/fate/server/prisma'; ``` -------------------------------- ### Type Safety: Omitting content field causes TypeScript error and undefined at runtime Source: https://fate.technology/guide/views This example shows a PostView that omits the content field. Accessing post.content causes a TypeScript error and is undefined during runtime, enforcing that all data dependencies are declared. ```tsx const PostView = view()({ id: true, title: true, // `content: true` is omitted. }); const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => { const post = useView(PostView, postRef); return (

{post.title}

{/* TypeScript errors here, and `post.content` is undefined during runtime */}

{post.content}

); }; ``` -------------------------------- ### Create GraphQL client template Source: https://fate.technology/packages/fate/docs/integrations/graphql Creates a client-only template for integrating fate with an existing GraphQL server. This is the smallest reference for the integration and includes a src/fate/graphql.ts file that maps your GraphQL schema to fate views and roots. ```bash vp create fate my-app --template graphql-client ``` -------------------------------- ### View Resolution Error: useView throws when ref does not include required view Source: https://fate.technology/guide/views This example shows that resolving a view against a ref that doesn't include it (via view spreads) throws an error during runtime. The PostDetailView is not included in the ref passed to PostDetail, so useView throws. ```tsx const PostDetailView = view()({ content: true, }); const AnotherPostView = view()({ content: true, }); const PostView = view()({ id: true, title: true, ...AnotherPostView, }); const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => { const post = useView(PostView, postRef); return ; }; const PostDetail = ({ post: postRef }: { post: ViewRef<'Post'> }) => { // This throws because the post reference passed into this component // is of type `AnotherPostView`, not `PostDetailView`. const post = useView(PostDetailView, postRef); }; ``` -------------------------------- ### createClient with gcReleaseBufferSize Source: https://fate.technology/guide/requests Tune the release buffer size when creating the client. Set to 0 for immediate collection in tests or memory-sensitive environments. ```tsx const fate = createClient({ gcReleaseBufferSize: 20, roots, transport, types, }); ``` -------------------------------- ### GraphQL schema shape for Post list Source: https://fate.technology/integrations/graphql Example GraphQL schema shape expected by the GraphQL transport: entity objects include id and __typename, object fetches go through nodes(ids:), list fields return Relay connections with edges, cursor, node, and pageInfo. Root queries and mutations return the entity type selected by the fate view. ```graphql type Query { posts(first: Int, after: String): PostConnection! viewer: User nodes(ids: [ID!]!): [Node]! } type PostConnection { edges: [PostEdge!]! pageInfo: PageInfo! } ```