### RPC API Handler Setup Source: https://zenstack.dev/docs/service/api-handler/rpc Example of how to create and initialize the RPCApiHandler with your schema. ```APIDOC ## RPC API Handler Setup ### Description This snippet shows how to import and instantiate the `RPCApiHandler` with your ZenStack schema. ### Code ```javascript import { schema } from '~/zenstack/schema'; import { RPCApiHandler } from '@zenstackhq/server/api'; const handler = new RPCApiHandler({ schema }); ``` ``` -------------------------------- ### Express.js Server Adapter Setup (V3) Source: https://zenstack.dev/docs/migrate-v2 Example of setting up an Express.js server adapter with explicit API handler and getClient configuration in V3. ```typescript import { schema } from '~/zenstack/schema'; import { authDb } from '~/db'; app.use( '/api/model', ZenStackMiddleware({ // an API handler needs to be explicitly passed in apiHandler: new RPCApiHandler({ schema }), // `getPrisma` is renamed to `getClient` in v3 getClient: (request) => getClientForRequest(request), }) ); function getClientForRequest(request: Request) { const user = getCurrentUser(request); return authDb.$setAuth(user); } ``` -------------------------------- ### Installation Source: https://zenstack.dev/docs/reference/server-adapters/nuxt Install the ZenStack server package using your preferred package manager. ```APIDOC ## Installation ### npm ```npm install @zenstackhq/server ``` ### pnpm ```pnpm add @zenstackhq/server ``` ### bun ```bun add @zenstackhq/server ``` ### yarn ```yarn add @zenstackhq/server ``` ``` -------------------------------- ### Installation Source: https://zenstack.dev/docs/reference/server-adapters/express Install the ZenStack server package using your preferred package manager. ```APIDOC ## Installation Install the ZenStack server package using your preferred package manager: ### npm ``` npm install @zenstackhq/server ``` ### pnpm ``` pnpm add @zenstackhq/server ``` ### bun ``` bun add @zenstackhq/server ``` ### yarn ``` yarn add @zenstackhq/server ``` ``` -------------------------------- ### Installation Source: https://zenstack.dev/docs/reference/server-adapters/fastify Install the ZenStack server package using your preferred package manager. ```APIDOC ## Installation Install the ZenStack server package using your preferred package manager: ### npm ```bash npm install @zenstackhq/server ``` ### pnpm ```bash pnpm add @zenstackhq/server ``` ### bun ```bash bun add @zenstackhq/server ``` ### yarn ```bash yarn add @zenstackhq/server ``` ``` -------------------------------- ### Install MySQL Driver with bun Source: https://zenstack.dev/docs/migrate-prisma Install the MySQL database driver using bun. ```bash bun add mysql2 ``` -------------------------------- ### Plugin Configuration Example Source: https://zenstack.dev/docs/reference/zmodel/plugin A practical example of how to configure a custom plugin in ZModel. ```APIDOC ## Example Configuration ### Description This example demonstrates defining a plugin named 'custom' that points to a local JavaScript file and specifies an output directory. ### Request Example ``` plugin custom { provider = './my-plugin.js' output = './generated' } ``` ``` -------------------------------- ### Install V3 Packages Source: https://zenstack.dev/docs/migrate-v2 Install the new core ZenStack v3 packages. ```bash npm install @zenstackhq/schema @zenstackhq/orm npm install --save-dev @zenstackhq/cli ``` ```bash pnpm add @zenstackhq/schema @zenstackhq/orm pnpm add --save-dev @zenstackhq/cli ``` ```bash bun add @zenstackhq/schema @zenstackhq/orm bun add --dev @zenstackhq/cli ``` ```bash yarn add @zenstackhq/schema @zenstackhq/orm yarn add --dev @zenstackhq/cli ``` -------------------------------- ### Installation Source: https://zenstack.dev/docs/utilities/zod Install the @zenstackhq/zod package and zod. Zod 4.0 or above is required. ```APIDOC ## Installation ### npm ``` npm install @zenstackhq/zod zod ``` ### pnpm ``` pnpm add @zenstackhq/zod zod ``` ### bun ``` bun add @zenstackhq/zod zod ``` ### yarn ``` yarn add @zenstackhq/zod zod ``` Zod 4.0 or above is required. ``` -------------------------------- ### Install SQLite Driver with bun Source: https://zenstack.dev/docs/migrate-prisma Install the SQLite database driver and its types using bun. ```bash bun add better-sqlite3 bun add --dev @types/better-sqlite3 ``` -------------------------------- ### Install Better-Auth CLI Source: https://zenstack.dev/docs/recipe/auth-integration/better-auth Install the Better-Auth CLI as a development dependency to generate database models. ```bash npm install --save-dev @better-auth/cli ``` ```bash pnpm add --save-dev @better-auth/cli ``` ```bash bun add --dev @better-auth/cli ``` ```bash yarn add --dev @better-auth/cli ``` -------------------------------- ### Install PostgreSQL Driver with bun Source: https://zenstack.dev/docs/migrate-prisma Install the PostgreSQL database driver and its types using bun. ```bash bun add pg bun add --dev @types/pg ``` -------------------------------- ### Install MySQL Driver with npm Source: https://zenstack.dev/docs/migrate-prisma Install the MySQL database driver using npm. ```bash npm install mysql2 ``` -------------------------------- ### PostgreSQL Datasource Example Source: https://zenstack.dev/docs/reference/zmodel/datasource Example of configuring a PostgreSQL datasource using an environment variable for the database URL. Ensure the DATABASE_URL environment variable is set. ```prisma datasource db { provider = 'postgresql' url = env('DATABASE_URL') } ``` -------------------------------- ### Start ZenStack Proxy Server Source: https://zenstack.dev/docs/reference/cli Use this command to start the ZenStack proxy server. It can be aliased as 'studio'. Options allow specifying the schema file, port, output directory, database URL, and log level. ```bash Usage: zen proxy [options] Options: --schema schema file (with extension .zmodel). Defaults to "zenstack/schema.zmodel" unless specified in package.json. -p, --port port to run the proxy server on (default: 2311) -o, --output output directory for `zen generate` command -d, --databaseUrl database connection URL -l, --logLevel Query log levels (e.g., query, error) --no-version-check do not check for new version -h, --help Show this help message ``` -------------------------------- ### Initialize ZenStack in an existing project Source: https://zenstack.dev/docs/orm/quick-start Run the init command to install dependencies and create a sample schema. ```bash npx @zenstackhq/cli init ``` ```bash pnpm --package=@zenstackhq/cli dlx zen init ``` ```bash bunx @zenstackhq/cli init ``` ```bash npx @zenstackhq/cli init ``` -------------------------------- ### Install MySQL Driver with yarn Source: https://zenstack.dev/docs/migrate-prisma Install the MySQL database driver using yarn. ```bash yarn add mysql2 ``` -------------------------------- ### Example Usage of Custom Procedures in main.ts Source: https://zenstack.dev/docs/orm/custom-proc An example TypeScript file demonstrating how to create a ZenStack client and call the `signUp` and `getUserFeeds` custom procedures. ```typescript import { createClient } from './db'; async function main() { const db = await createClient(); const user = await db.$procs.signUp({ args: { email: 'alice@zenstack.dev' } }); console.log('Created user with "signUp" proc:', user); const feed = await db.$procs.getUserFeeds({ args: { userId: user.id } }); console.log('Feeds from "getUserFeeds" proc:', feed); } main(); ``` -------------------------------- ### Install MySQL Driver with pnpm Source: https://zenstack.dev/docs/migrate-prisma Install the MySQL database driver using pnpm. ```bash pnpm add mysql2 ``` -------------------------------- ### Install ZenStack Better-Auth Adapter Source: https://zenstack.dev/docs/recipe/auth-integration/better-auth Install the required adapter package using your preferred package manager. ```bash npm install @zenstackhq/better-auth ``` ```bash pnpm add @zenstackhq/better-auth ``` ```bash bun add @zenstackhq/better-auth ``` ```bash yarn add @zenstackhq/better-auth ``` -------------------------------- ### Install ZenStack Server Package Source: https://zenstack.dev/docs/reference/server-adapters/hono Install the required server package using your preferred package manager. ```bash npm install @zenstackhq/server ``` ```bash pnpm add @zenstackhq/server ``` ```bash bun add @zenstackhq/server ``` ```bash yarn add @zenstackhq/server ``` -------------------------------- ### Install PostgreSQL Driver with npm Source: https://zenstack.dev/docs/migrate-prisma Install the PostgreSQL database driver and its types using npm. ```bash npm install pg npm install --save-dev @types/pg ``` -------------------------------- ### Install better-sqlite3 for Node.js Source: https://zenstack.dev/docs/recipe/databases/sqlite Install the `better-sqlite3` package and its types for Node.js projects. ```bash npm install better-sqlite3 npm install --save-dev @types/better-sqlite3 ``` ```bash pnpm add better-sqlite3 pnpm add --save-dev @types/better-sqlite3 ``` ```bash bun add better-sqlite3 bun add --dev @types/better-sqlite3 ``` ```bash yarn add better-sqlite3 yarn add --dev @types/better-sqlite3 ``` -------------------------------- ### Install SQLite Driver with npm Source: https://zenstack.dev/docs/migrate-prisma Install the SQLite database driver and its types using npm. ```bash npm install better-sqlite3 npm install --save-dev @types/better-sqlite3 ``` -------------------------------- ### Import Example Source: https://zenstack.dev/docs/reference/zmodel/import Import a 'user.zmodel' file located in the same directory. All declarations from the imported file become available. ```zmodel // there is a file called "user.zmodel" in the same directory import "user" ``` -------------------------------- ### Install kysely-bun-sqlite for Bun Source: https://zenstack.dev/docs/recipe/databases/sqlite Install the `kysely-bun-sqlite` package for use with Bun's built-in `bun:sqlite` module. Note that `better-sqlite3` is not compatible with Bun. ```bash npm install kysely-bun-sqlite ``` ```bash pnpm add kysely-bun-sqlite ``` ```bash bun add kysely-bun-sqlite ``` ```bash yarn add kysely-bun-sqlite ``` -------------------------------- ### Install ZenStack Server Package Source: https://zenstack.dev/docs/reference/server-adapters/fastify Install the ZenStack server package using npm, pnpm, bun, or yarn. ```bash npm install @zenstackhq/server ``` ```bash pnpm add @zenstackhq/server ``` ```bash bun add @zenstackhq/server ``` ```bash yarn add @zenstackhq/server ``` -------------------------------- ### Install ZenStack Server Package Source: https://zenstack.dev/docs/reference/server-adapters/nuxt Install the ZenStack server package using npm, pnpm, bun, or yarn. ```bash npm install @zenstackhq/server ``` ```bash pnpm add @zenstackhq/server ``` ```bash bun add @zenstackhq/server ``` ```bash yarn add @zenstackhq/server ``` -------------------------------- ### Install PostgreSQL driver Source: https://zenstack.dev/docs/recipe/databases/postgres Install the pg package and its corresponding type definitions for your package manager. ```bash npm install pg npm install --save-dev @types/pg ``` ```bash pnpm add pg pnpm add --save-dev @types/pg ``` ```bash bun add pg bun add --dev @types/pg ``` ```bash yarn add pg yarn add --dev @types/pg ``` -------------------------------- ### Install SQLite Driver with pnpm Source: https://zenstack.dev/docs/migrate-prisma Install the SQLite database driver and its types using pnpm. ```bash pnpm add better-sqlite3 pnpm add --save-dev @types/better-sqlite3 ``` -------------------------------- ### Install SQLite Driver with yarn Source: https://zenstack.dev/docs/migrate-prisma Install the SQLite database driver and its types using yarn. ```bash yarn add better-sqlite3 yarn add --dev @types/better-sqlite3 ``` -------------------------------- ### Install Neon serverless driver Source: https://zenstack.dev/docs/recipe/databases/neon Commands to install the Neon serverless driver using various package managers. ```bash npm install @neondatabase/serverless ``` ```bash pnpm add @neondatabase/serverless ``` ```bash bun add @neondatabase/serverless ``` ```bash yarn add @neondatabase/serverless ``` -------------------------------- ### Install ZenStack dependencies manually Source: https://zenstack.dev/docs/orm/quick-start Install the required ORM and schema packages along with the CLI. ```bash npm install @zenstackhq/schema @zenstackhq/orm npm install --save-dev @zenstackhq/cli ``` ```bash pnpm add @zenstackhq/schema @zenstackhq/orm pnpm add --save-dev @zenstackhq/cli ``` ```bash bun add @zenstackhq/schema @zenstackhq/orm bun add --dev @zenstackhq/cli ``` ```bash yarn add @zenstackhq/schema @zenstackhq/orm yarn add --dev @zenstackhq/cli ``` -------------------------------- ### ZenStack Generate Command Output Example Source: https://zenstack.dev/docs/recipe/plugin-dev Example output from the 'npx zen generate' command, showing the successful execution of the custom 'Password Report' plugin during the generation process. ```text % npx zen generate ✔ Generating TypeScript schema ✔ Running plugin Password Report Generation completed successfully in 116ms. ``` -------------------------------- ### Install ZenStack Server Package Source: https://zenstack.dev/docs/reference/server-adapters/sveltekit Install the core ZenStack server package using npm, pnpm, bun, or yarn. ```bash npm install @zenstack/server ``` ```bash pnpm add @zenstack/server ``` ```bash bun add @zenstack/server ``` ```bash yarn add @zenstack/server ``` -------------------------------- ### Install @zenstackhq/sdk with bun Source: https://zenstack.dev/docs/recipe/plugin-dev Install the SDK package required for developing ZenStack CLI plugins using bun. ```bash bun add --dev @zenstackhq/sdk ``` -------------------------------- ### Install PostgreSQL Driver with pnpm Source: https://zenstack.dev/docs/migrate-prisma Install the PostgreSQL database driver and its types using pnpm. ```bash pnpm add pg pnpm add --save-dev @types/pg ``` -------------------------------- ### Install PostgreSQL Driver with yarn Source: https://zenstack.dev/docs/migrate-prisma Install the PostgreSQL database driver and its types using yarn. ```bash yarn add pg yarn add --dev @types/pg ``` -------------------------------- ### Install ZenStack Packages with bun Source: https://zenstack.dev/docs/migrate-prisma Install ZenStack schema and ORM packages, and the CLI as a dev dependency using bun. ```bash bun add @zenstackhq/schema @zenstackhq/orm bun add --dev @zenstackhq/cli ``` -------------------------------- ### Install @zenstackhq/sdk with pnpm Source: https://zenstack.dev/docs/recipe/plugin-dev Install the SDK package required for developing ZenStack CLI plugins using pnpm. ```bash pnpm add --save-dev @zenstackhq/sdk ``` -------------------------------- ### Install ZenStack Packages with pnpm Source: https://zenstack.dev/docs/migrate-prisma Install ZenStack schema and ORM packages, and the CLI as a dev dependency using pnpm. ```bash pnpm add @zenstackhq/schema @zenstackhq/orm pnpm add --save-dev @zenstackhq/cli ``` -------------------------------- ### Install ZenStack Server Package (bun) Source: https://zenstack.dev/docs/reference/server-adapters/express Install the core ZenStack server package using bun. This command is an alternative to npm for package management. ```bash bun add @zenstackhq/server ``` -------------------------------- ### SQLite Datasource Example Source: https://zenstack.dev/docs/reference/zmodel/datasource Example of configuring a SQLite datasource with a file path for the database connection. The URL specifies the location of the SQLite database file. ```prisma datasource db { provider = 'sqlite' url = 'file:./dev.db' } ``` -------------------------------- ### Install @zenstackhq/zod Source: https://zenstack.dev/docs/utilities/zod Commands to install the package and the required Zod dependency using various package managers. ```bash npm install @zenstackhq/zod zod ``` ```bash pnpm add @zenstackhq/zod zod ``` ```bash bun add @zenstackhq/zod zod ``` ```bash yarn add @zenstackhq/zod zod ``` -------------------------------- ### Install ZenStack Packages with npm Source: https://zenstack.dev/docs/migrate-prisma Install ZenStack schema and ORM packages, and the CLI as a dev dependency using npm. ```bash npm install @zenstackhq/schema @zenstackhq/orm npm install --save-dev @zenstackhq/cli ``` -------------------------------- ### Install @zenstackhq/sdk with npm Source: https://zenstack.dev/docs/recipe/plugin-dev Install the SDK package required for developing ZenStack CLI plugins using npm. ```bash npm install --save-dev @zenstackhq/sdk ``` -------------------------------- ### Install Access Control Plugin Source: https://zenstack.dev/docs/migrate-v2 Install the policy plugin required for access control in v3. ```bash npm install @zenstackhq/plugin-policy ``` ```bash pnpm add @zenstackhq/plugin-policy ``` ```bash bun add @zenstackhq/plugin-policy ``` ```bash yarn add @zenstackhq/plugin-policy ``` -------------------------------- ### Install @zenstackhq/sdk with yarn Source: https://zenstack.dev/docs/recipe/plugin-dev Install the SDK package required for developing ZenStack CLI plugins using yarn. ```bash yarn add --dev @zenstackhq/sdk ``` -------------------------------- ### Configure a Custom Plugin Source: https://zenstack.dev/docs/reference/zmodel/plugin An example of a plugin configuration specifying a local provider and output directory. ```zmodel plugin custom { provider = './my-plugin.js' output = './generated' } ``` -------------------------------- ### Install ZenStack Packages with yarn Source: https://zenstack.dev/docs/migrate-prisma Install ZenStack schema and ORM packages, and the CLI as a dev dependency using yarn. ```bash yarn add @zenstackhq/schema @zenstackhq/orm yarn add --dev @zenstackhq/cli ``` -------------------------------- ### Install TanStack Query Package Source: https://zenstack.dev/docs/service/client-sdk/tanstack-query Install the TanStack Query integration package for ZenStack using your preferred package manager. ```bash npm install @zenstackhq/tanstack-query ``` ```bash pnpm add @zenstackhq/tanstack-query ``` ```bash bun add @zenstackhq/tanstack-query ``` ```bash yarn add @zenstackhq/tanstack-query ``` -------------------------------- ### GET /api/post/findMany Source: https://zenstack.dev/docs/service/api-handler/rpc Example of a GET request to find multiple posts, using the 'q' query parameter for the query body. ```APIDOC ## GET /api/post/findMany ### Description This endpoint retrieves a list of posts based on the provided query parameters. For GET requests, the query body is serialized and passed as the `q` query parameter. ### Method GET ### Endpoint /api/post/findMany ### Query Parameters - **q** (string) - Required - The serialized query body, typically a JSON object. ### Request Example ``` GET /api/post/findMany?q=%7B%22where%22%3A%7B%22public%22%3Atrue%7D%7D ``` ### Response #### Success Response (200) - **data** (array) - An array of post objects matching the query. #### Response Example ```json { "data": [ { "id": 1, "title": "Hello World" } ] } ``` ``` -------------------------------- ### Scaffold a new project Source: https://zenstack.dev/docs/orm/quick-start Use the CLI to create a new project with a pre-configured starter. ```bash npm create zenstack my-project ``` -------------------------------- ### Install Policy Plugin Source: https://zenstack.dev/docs/orm/access-control/query Install the PolicyPlugin on a raw ORM client to enable access control enforcement. `ZenStackClient` instances are immutable; `$use()` returns a new client. ```typescript import { ZenStackClient } from '@zenstackhq/orm'; import { PolicyPlugin } from '@zenstackhq/plugin-policy'; // create an unprotected, "raw" ORM client const db = new ZenStackClient(...); // install the policy plugin const authDb = db.$use(new PolicyPlugin()); // make queries with `authDb` to have access control enforced ... ``` -------------------------------- ### Apply and Remove Plugins - ZenStack Client Source: https://zenstack.dev/docs/orm/plugins Install plugins using the $use method on the ZenStackClient, which returns a new client with the plugin applied. Use $unuseAll to remove all installed plugins. ```typescript const db = new ZenStackClient({ ... }); const withPlugin = db.$use({ ... }); const noPlugin = withPlugin.$unuseAll(); ``` -------------------------------- ### Install ZenStack Server Package (yarn) Source: https://zenstack.dev/docs/reference/server-adapters/express Install the core ZenStack server package using yarn. This command is an alternative to npm for package management. ```bash yarn add @zenstackhq/server ``` -------------------------------- ### Get ZenStack Package Information Source: https://zenstack.dev/docs/reference/cli Retrieve information about installed ZenStack packages. Specify a project path if not in the current directory. ```bash Usage: zen info [options] [path] Get information of installed ZenStack. Arguments: path project path (default: ".") Options: -h, --help display help for command ``` -------------------------------- ### Install ZenStack Server Package (pnpm) Source: https://zenstack.dev/docs/reference/server-adapters/express Install the core ZenStack server package using pnpm. This command is an alternative to npm for package management. ```bash pnpm add @zenstackhq/server ``` -------------------------------- ### Call Custom Procedures via REST Source: https://zenstack.dev/docs/service/api-handler/rest Examples of invoking custom procedures using GET with URL-encoded arguments and POST with a JSON body. ```http GET /$procs/getUserFeeds?args=%7B%22userId%22%3A1%2C%22limit%22%3A10%7D ``` ```http POST /$procs/signUp { "args": { "email": "alice@zenstack.dev" } } ``` -------------------------------- ### Svelte Context Provider Setup Source: https://zenstack.dev/docs/service/client-sdk/tanstack-query Configure the TanStack Query context provider in your Svelte application. This example sets a custom endpoint and a custom fetch function with an extra header. ```typescript
``` -------------------------------- ### Initialize ZenStack Project Source: https://zenstack.dev/docs/reference/cli Initialize an existing project for ZenStack. Specify the project path if it's not the current directory. ```bash Usage: zen init [options] [path] Initialize an existing project for ZenStack. Arguments: path project path (default: ".") Options: -h, --help display help for command ``` -------------------------------- ### Vue Context Provider Setup Source: https://zenstack.dev/docs/service/client-sdk/tanstack-query Set up the TanStack Query context provider in your Vue application. This example configures a custom endpoint and a custom fetch function with an added header. ```typescript ``` -------------------------------- ### React Context Provider Setup Source: https://zenstack.dev/docs/service/client-sdk/tanstack-query Configure the TanStack Query context provider in your React application. This example demonstrates setting a custom endpoint and a custom fetch function with an additional header. ```typescript import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QuerySettingsProvider, type FetchFn } from '@zenstackhq/tanstack-query/react'; // custom fetch function that adds a custom header const myFetch: FetchFn = (url, options) => { options = options ?? {}; options.headers = { ...options.headers, 'x-my-custom-header': 'hello world', }; return fetch(url, options); }; const queryClient = new QueryClient(); function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) { return ( ); } export default MyApp; ``` -------------------------------- ### ZenStack ORM Client Setup and Usage Source: https://zenstack.dev/docs/orm/access-control/query Demonstrates setting up a ZenStack client with the PolicyPlugin, authenticating users (Alice and Bob), and querying posts. Shows how different authenticated users see different results based on policies. ```typescript import { PolicyPlugin } from '@zenstack/plugin-policy'; import { createClient } from '../db'; import { schema } from './zenstack/schema'; async function main() { const db = await createClient(schema); // create users and posts with raw client const alice = await db.user.create({ data: { email: 'alice@example.com', posts: { create: [ { title: 'Alice Draft Post', published: false }, { title: 'Alice Published Post', published: true } ] } } }); const bob = await db.user.create({ data: { email: 'bob@example.com', posts: { create: [{ title: 'Bob Draft Post', published: false }] } } }); // install policy plugin const authDb = db.$use(new PolicyPlugin()); // create user-bound clients const aliceDb = authDb.$setAuth(alice); const bobDb = authDb.$setAuth(bob); // query posts as Alice console.log('Alice sees posts:'); console.table( await aliceDb.post.findMany({ select: { title: true, published: true } }) ); // query posts as Bob console.log('Bob sees posts:'); console.table( await bobDb.post.findMany({ select: { title: true, published: true } }) ); } main(); ``` -------------------------------- ### Initialize ZenStack Project Source: https://zenstack.dev/docs/orm/introspection Use this command to initialize a new ZenStack project. Available for npm, pnpm, bun, and yarn. ```bash npx zen init ``` ```bash pnpm zen init ``` ```bash bunx zen init ``` ```bash npx zen init ``` -------------------------------- ### FieldReference Parameter Example Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of declaring and applying the '@relation' attribute using FieldReferences. ```typescript attribute @relation( _ name: String?, fields: FieldReference[]?, references: FieldReference[]?, onDelete: ReferentialAction?, onUpdate: ReferentialAction?, map: String?) ``` ```typescript model Model { ... // [ownerId] is a list of FieldReference owner Owner @relation(fields: [ownerId], references: [id]) ownerId } ``` -------------------------------- ### String Parameter Type Example Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of declaring and applying an attribute with a String parameter. ```typescript attribute @id(map: String?) ``` ```typescript id String @id(map: "_id") ``` -------------------------------- ### Integer Parameter Type Example Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of declaring and applying an attribute with an Integer parameter. ```typescript attribute @password(saltLength: Int?, salt: String?) ``` ```typescript password String @password(saltLength: 10) ``` -------------------------------- ### Install and Use PolicyPlugin Source: https://zenstack.dev/docs/reference/plugins/policy Installs the PolicyPlugin on the ORM client to enable access control enforcement. ```APIDOC ## Install and Use PolicyPlugin ### Description Installs the `PolicyPlugin` on the ORM client to enable access control enforcement. ### Method `$use()` ### Endpoint N/A (Client-side installation) ### Request Example ```javascript import { ZenStackClient } from '@zenstackhq/orm'; import { PolicyPlugin } from '@zenstackhq/plugin-policy'; const db = new ZenStackClient(...); const authDb = db.$use(new PolicyPlugin()); ``` ### Response N/A (Client-side operation) ``` -------------------------------- ### Initialize ZenStack Client with PasswordHasherPlugin Source: https://zenstack.dev/docs/recipe/plugin-dev This example demonstrates how to initialize the ZenStackClient with the PasswordHasherPlugin. It sets up the database connection and includes the plugin in the configuration. ```typescript import { ZenStackClient } from "@zenstackhq/orm"; import { SqlJsDialect } from "@zenstackhq/orm/dialects/sql.js"; import initSqlJs from "sql.js"; import { PasswordHasherPlugin } from "./password-hasher-plugin"; import { schema } from "./zenstack/schema"; async function main() { const SQL = await initSqlJs(); const db = new ZenStackClient(schema, { dialect: new SqlJsDialect({ sqlJs: new SQL.Database() }), plugins: [new PasswordHasherPlugin()], }); // push database schema await db.$pushSchema(); console.log("Creating user with plain text password..."); const user = await db.user.create({ data: { email: "test@zenstack.dev", password: "abc123", }, }); console.log("User created:", user); console.log("\nUpdating user password..."); const updatedUser = await db.user.update({ where: { id: user.id }, data: { password: "def456" }, }); console.log("Updated user:", updatedUser); } main(); ``` -------------------------------- ### Initialize ZenStack client with SQLite Source: https://zenstack.dev/docs/orm/client Initialize the ZenStack client using the SqliteDialect with an in-memory SQLite database. Ensure better-sqlite3 is installed. ```typescript import { ZenStackClient } from '@zenstackhq/orm'; import { SqliteDialect } from '@zenstackhq/orm/dialects/sqlite'; import SQLite from 'better-sqlite3'; import { schema } from './zenstack/schema'; export const db = new ZenStackClient(schema, { dialect: new SqliteDialect({ database: new SQLite(':memory:'), }), }); ``` -------------------------------- ### List of FieldReference Example Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of applying a model attribute that takes a list of FieldReferences, such as '@@unique'. ```typescript model Model { ... f1 String f2 String // a list of FieldReference @@unique([f1, f2]) } ``` -------------------------------- ### Example Field Attribute Application Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of applying the '@id' field attribute with a 'map' argument. ```typescript model User { id Int @id(map: "_id") } ``` -------------------------------- ### Sample ZenStack Schema with Custom Procedures Source: https://zenstack.dev/docs/orm/custom-proc A sample ZModel schema demonstrating user and post models, along with definitions for `getUserFeeds` and `signUp` custom procedures. ```zmodel // This is a sample model to get you started. datasource db { provider = 'sqlite' } /// User model model User { id Int @id @default(autoincrement()) email String @unique posts Post[] } /// Post model model Post { id Int @id @default(autoincrement()) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt title String published Boolean @default(false) author User? @relation(fields: [authorId], references: [id]) authorId Int? } // get blog post feeds for a given user procedure getUserFeeds(userId: Int, limit: Int?) : Post[] // sign up a new user mutation procedure signUp(email: String) : User ``` -------------------------------- ### Enum Parameter Type Example Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of using an Enum type for attribute parameters, like ReferentialAction. ```typescript attribute @relation( _ name: String?, fields: FieldReference[]?, references: FieldReference[]?, // ReferentialAction is a predefined enum onDelete: ReferentialAction?, onUpdate: ReferentialAction?, map: String?) ``` ```typescript model Model { // 'Cascade' is a predefined enum value owner Owner @relation(..., onDelete: Cascade) } ``` -------------------------------- ### ContextType Parameter Example Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of using ContextType for the '@default' attribute, accepting different literal types. ```typescript attribute @default(_ value: ContextType) ``` ```typescript f1 String @default("hello") ``` ```typescript f2 Int @default(1) ``` -------------------------------- ### Boolean Parameter Type Example Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of declaring and applying an attribute with a Boolean parameter, including expressions. ```typescript attribute @@allow(_ operation: String, _ condition: Boolean) ``` ```typescript @@allow("read", true) ``` ```typescript @@allow("update", auth() != null) ``` -------------------------------- ### Create ZenStackClient with Bun.sqlite Source: https://zenstack.dev/docs/recipe/databases/sqlite Initialize ZenStackClient using the `BunSqliteDialect` with Bun's native `bun:sqlite` module. Ensure the schema is correctly imported. ```typescript import { schema } from './zenstack/schema'; import { Database } from 'bun:sqlite'; import { ZenStackClient } from '@zenstack/orm'; import { BunSqliteDialect } from 'kysely-bun-sqlite'; const db = new ZenStackClient(schema, { dialect: new BunSqliteDialect({ database: new Database('./dev.db') }), }); ``` -------------------------------- ### Create User and Posts with Query Builder Source: https://zenstack.dev/docs/orm/query-builder Demonstrates creating a user and then two posts associated with that user using the query builder API. Ensure the ORM client is created using `createClient`. ```typescript import { createClient } from './db'; async function main() { const db = await createClient(); console.log('Create a user'); const user = await db.$qb .insertInto('User') .values({ email: 'u1@test.com' }) .returningAll() .executeTakeFirstOrThrow(); console.log(user); console.log('Create two posts for the user'); console.log( await db.$qb .insertInto('Post') .values([ { title: 'Post1', authorId: user.id, updatedAt: new Date().toISOString() }, { title: 'Post2', authorId: user.id, updatedAt: new Date().toISOString() } ]) .returningAll() .execute() ); console.log('Find a user with at least two posts'); // build a query equivalent to the following SQL: // SELECT User.*, postCount FROM User LEFT JOIN // (SELECT authorId, COUNT(*) AS postCount FROM Post GROUP BY authorId) AS UserPosts // ON // UserPosts.authorId = User.id // WHERE // postCount > 1 const result = await db.$qb .selectFrom('User') .leftJoin( // express builder is type-safe eb => eb .selectFrom('Post') .select('authorId') .select(({fn}) => fn.countAll().as('postCount')) .groupBy('authorId') .as('UserPosts'), join => join.onRef('UserPosts.authorId', '=', 'User.id') ) .selectAll('User') .select('postCount') .where('postCount', '>', 1) .executeTakeFirstOrThrow(); // query result is type-safe console.log(`User ${result.email} has ${result.postCount} posts`); console.log('Use query builder inside filter'); console.log( await db.user.findMany({ where: { $expr: (eb) => eb .selectFrom('Post') .select(eb => eb(eb.fn.countAll(), '>', 1).as('postCountFilter')) .whereRef('Post.authorId', '=', 'User.id') } }) ); } main(); ``` -------------------------------- ### Initialize ZenStack client with PostgreSQL Source: https://zenstack.dev/docs/orm/client Initialize the ZenStack client using the PostgresDialect with a connection pool. Ensure the DATABASE_URL environment variable is set. ```typescript import { ZenStackClient } from '@zenstackhq/orm'; import { PostgresDialect } from '@zenstackhq/orm/dialects/postgres'; import { schema } from './zenstack/schema'; import { Pool } from 'pg'; export const db = new ZenStackClient(schema, { dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, }), }), }); ``` -------------------------------- ### Initialize ZenStackClient with Neon Source: https://zenstack.dev/docs/recipe/databases/neon Configuration for the ZenStackClient using the PostgresDialect and Neon's Pool. ```typescript import { schema } from '@/zenstack/schema'; import { Pool } from '@neondatabase/serverless'; import { ZenStackClient } from '@zenstackhq/orm'; import { PostgresDialect } from '@zenstackhq/orm/dialects/postgres'; const db = new ZenStackClient(schema, { dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL, }), }), }); ``` -------------------------------- ### Example Model Attribute Application Source: https://zenstack.dev/docs/reference/zmodel/attribute Example of applying the '@@unique' model attribute to enforce uniqueness on multiple fields. ```typescript model User { org String userName String @@unique([org, userName]) } ``` -------------------------------- ### Initialize ZenStack client with MySQL Source: https://zenstack.dev/docs/orm/client Initialize the ZenStack client using the MysqlDialect with a connection pool. Ensure the DATABASE_URL environment variable is set. ```typescript import { ZenStackClient } from '@zenstackhq/orm'; import { MysqlDialect } from '@zenstackhq/orm/dialects/mysql'; import { schema } from './zenstack/schema'; import { createPool } from 'mysql2'; export const db = new ZenStackClient(schema, { dialect: new MysqlDialect({ pool: createPool(process.env.DATABASE_URL), }), }); ``` -------------------------------- ### Install PolicyPlugin on ORM Client Source: https://zenstack.dev/docs/reference/plugins/policy Installs the PolicyPlugin on the ZenStackClient to enable access control enforcement. Ensure ZenStackClient and PolicyPlugin are imported. ```typescript import { ZenStackClient } from '@zenstackhq/orm'; import { PolicyPlugin } from '@zenstackhq/plugin-policy'; const db = new ZenStackClient(...); const authDb = db.$use(new PolicyPlugin()); ```