### Tenant Context Setup Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/configuration.md Example demonstrating how to set up tenant context and create a typed client with tenant-specific headers. ```typescript type TenantKeyMap = Record type TenantContext = { [K in keyof TMap]?: string | null } // Define mapping from context keys to header names const tenantKeyMap = { organizationId: 'x-org-id', userId: 'x-user-id' } // Provide initial tenant values const tenantContext = { organizationId: 'org_123', userId: 'user_456' } const client = createTypedClient(url, key, registry, { tenantKeyMap, tenantContext }) // Tenant headers are automatically added to all requests: // x-org-id: org_123 // x-user-id: user_456 ``` -------------------------------- ### Setup Source: https://github.com/xylex-group/athena-js/blob/main/test-sdk/README.md Commands to build the project, navigate to the test-sdk directory, and install dependencies. ```bash pnpm build cd test-sdk pnpm install ``` -------------------------------- ### Common Copy-Paste Starts for Schema Generation Source: https://github.com/xylex-group/athena-js/blob/main/README.md Provides common command-line examples for schema generation, including direct PostgreSQL connection, multiple schema synchronization with table-builder output, and gateway-only CI job setup. ```bash # direct postgres, no config file DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/app_db athena-js generate --dry-run # direct postgres + Zero-style output + multiple schemas DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/app_db \ ATHENA_GENERATOR_OUTPUT_FORMAT=table-builder \ ATHENA_GENERATOR_SCHEMAS=public,analytics \ athena-js generate --dry-run # gateway-only CI job, no config file ATHENA_URL=https://athena-db.com \ ATHENA_API_KEY=secret \ ATHENA_GENERATOR_DB=app_db \ athena-js generate --dry-run ``` -------------------------------- ### Development Setup Source: https://github.com/xylex-group/athena-js/blob/main/CONTRIBUTING.md Commands to clone the repository, install dependencies, and build the project. ```bash git clone https://github.com/xylex-group/athena-js cd athena-js npm install npm run build ``` -------------------------------- ### RPC GET Request Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/runtime-method-ast-models.md Demonstrates how to use the `rpc` method with `options.get === true` to construct a GET request, flattening arguments and filters into query parameters. ```APIDOC ## Example Usage with GET Compatibility ```ts athena .rpc("list_orders", { status: "open" }, { get: true }) .gte("created_at", "2026-01-01") .lt("created_at", "2027-01-01") ``` This can produce query parameters like: ```text /rpc/list_orders?status=open&created_at=gte.2026-01-01&created_at=lt.2027-01-01 ``` ``` -------------------------------- ### List Storage Buckets Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/storage/index.md An example demonstrating how to use the `callRawStorageRoute` function to list storage buckets. ```APIDOC ## List Storage Buckets ### Description This example shows how to use the `callRawStorageRoute` helper function to list storage buckets. It requires environment variables for the Athena URL, API key, and S3 credentials. ### Method POST ### Endpoint /storage/buckets/list ### Parameters #### Request Body - **endpoint** (string) - The endpoint for the S3 service. - **region** (string) - The AWS region for the S3 service. - **access_key_id** (string) - The AWS access key ID. - **secret_key** (string) - The AWS secret access key. ### Request Example ```json { "endpoint": "https://s3.us-east-1.amazonaws.com", "region": "us-east-1", "access_key_id": "YOUR_S3_ACCESS_KEY_ID", "secret_key": "YOUR_S3_SECRET_ACCESS_KEY" } ``` ### Response #### Success Response (200) - **buckets** (array) - A list of storage buckets. ``` -------------------------------- ### ERR_MODULE_NOT_FOUND Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/cli-command-reference.md This error indicates that the global package installation is missing the generated CLI bundle files. It is common with old or broken published versions or stale shims. ```text Cannot find module .../@xylex-group/athena/dist/cli/index.js ``` -------------------------------- ### Install @xylex-group/athena SDK Source: https://github.com/xylex-group/athena-js/blob/main/README.md Install the SDK using npm, pnpm, or yarn. React peer dependency is optional and requires a separate installation if hooks are used. ```bash npm install @xylex-group/athena # or pnpm add @xylex-group/athena # or yarn add @xylex-group/athena ``` ```bash npm install react # React >=17 required for the hook ``` -------------------------------- ### Example: Custom Request Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Demonstrates making a custom GET request with query parameters. ```typescript const result = await auth.request({ endpoint: '/ok', query: { ping: 'pong' } }) ``` -------------------------------- ### Example Usage Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/gateway.md Example of creating a client with different backend configurations. ```typescript const client = createClient(URL, API_KEY, { backend: Backend.PostgreSQL, // or custom: backend: { type: 'postgrest', options: { version: '1.0' } } }) ``` -------------------------------- ### RPC GET Request Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/runtime-method-ast-models.md Demonstrates how to construct an RPC GET request with filters applied using chained method calls. This example shows the usage of `.gte()` and `.lt()` for date range filtering. ```typescript athena .rpc("list_orders", { status: "open" }, { get: true }) .gte("created_at", "2026-01-01") .lt("created_at", "2027-01-01") ``` -------------------------------- ### Get Session Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Example of retrieving the current authenticated user's session. ```typescript const result = await auth.session.get() if (!result.error) { console.log('User:', result.data?.user.email) console.log('Session expires at:', result.data?.session.expiresAt) } else { console.log('Not authenticated:', result.error) } ``` -------------------------------- ### Email Sign-Up Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Example of creating a new user account with email and password. ```typescript const result = await auth.signUp.email({ name: 'Bob Smith', email: 'bob@example.com', password: 'newpassword123' }) if (!result.error) { // User created and signed in console.log('Welcome,', result.data?.user.name) } ``` -------------------------------- ### AthenaQueryClientProvider Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/configuration.md Example of how to configure the AthenaQueryClientProvider with default query and mutation options. ```typescript import { AthenaQueryClientProvider } from '@xylex-group/athena/react' export function App() { return ( Math.pow(2, attempt) * 100, refetchOnWindowFocus: true, refetchOnReconnect: true }, defaultMutationOptions: { retry: 1, retryDelay: 500 } }} > ) } ``` -------------------------------- ### Updating Tenant Context Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/configuration.md Example showing how to create a new client instance with updated tenant context for different requests. ```typescript // Create new client instance with different tenant const orgClient = client.withTenantContext({ organizationId: 'org_789', userId: 'user_000' }) // All queries from orgClient use the new tenant headers await orgClient.fromModel('public', 'public', 'users').select() ``` -------------------------------- ### Prefetching Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/react-hooks.md Example demonstrating how to prefetch query data before navigation using client.prefetchQuery. ```typescript const client = useAthenaQueryClient() // Prefetch before navigation const prefetchUser = (userId) => { client.prefetchQuery({ queryKey: ['user', userId], queryFn: () => fetchUser(userId) }) } // On route change or hover prefetchUser('123')}>User 123 ``` -------------------------------- ### Email Sign-In Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Example of signing in a user with their email and password. ```typescript const result = await auth.signIn.email({ email: 'alice@example.com', password: 'secure-password', rememberMe: true }) if (!result.error) { console.log('User:', result.data?.user.name) console.log('Token:', result.data?.token) } ``` -------------------------------- ### Athena Client Creation Source: https://github.com/xylex-group/athena-js/blob/main/test-sdk/examples/react-hooks/README.md Example of creating an Athena client using environment variables for connection details. ```tsx import { createExampleAthenaClient } from './shared' const athena = createExampleAthenaClient({ athenaUrl: process.env.NEXT_PUBLIC_ATHENA_URL!, apiKey: process.env.NEXT_PUBLIC_ATHENA_API_KEY!, client: process.env.NEXT_PUBLIC_ATHENA_CLIENT, }) ``` -------------------------------- ### Username Sign-In Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Example of signing in a user with their username and password. ```typescript const result = await auth.signIn.username({ username: 'alice', password: 'password123' }) ``` -------------------------------- ### Table Builder Output Format Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/generator-config.md Example configuration for using the 'table-builder' format with custom target paths for generated files. ```typescript output: { format: "table-builder", targets: { model: "src/generated/{database_kebab}/{schema_kebab}/{model_kebab}.ts", schema: "src/generated/{database_kebab}/{schema_kebab}/index.ts", database: "src/generated/{database_kebab}/index.ts", registry: "src/generated/index.ts", }, } ``` -------------------------------- ### AthenaQueryClientProvider Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/react-hooks.md Example of how to set up the AthenaQueryClientProvider with configuration. ```typescript import { AthenaQueryClientProvider } from '@xylex-group/athena/react' export function App() { return ( ) } ``` -------------------------------- ### Query-Level Options Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/configuration.md Examples demonstrating the usage of query-level options like specifying count mode, schema, and controlling data output. ```typescript // Get exact row count const result = await client .from('users') .select(undefined, { count: 'exact' }) // Query with different schema const result = await client .from('users') .select(undefined, { schema: 'private' }) // Only return count, not data const result = await client .from('posts') .select(undefined, { head: true, count: 'exact' }) // Keep null fields in response const result = await client .from('users') .select(undefined, { stripNulls: false }) ``` -------------------------------- ### Social Sign-In Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Example of initiating an OAuth sign-in flow. ```typescript const result = await auth.signIn.social({ provider: 'google', callbackURL: 'https://app.example.com/auth/callback', scopes: ['profile', 'email'] }) if (!result.error && result.data?.redirect) { window.location.href = result.data.url } ``` -------------------------------- ### Select Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/client.md Example demonstrating how to use the `select` method with filters and ordering. ```javascript const data = await client .from('posts') .select('id, title, author:user_id(name)') .eq('published', true) .order('created_at', { ascending: false }) .limit(10) ``` -------------------------------- ### OpenAPI Success Example (Outdated) Source: https://github.com/xylex-group/athena-js/blob/main/docs/findmany-ast-and-server-contract.md The success example for POST /gateway/fetch and POST /gateway/query as documented in the live OpenAPI, which may differ from actual server payloads. ```json { "status": "success", "message": "Fetched 25 rows", "data": { "rows": [], "row_count": 25 } } ``` -------------------------------- ### Install Athena.js Globally Source: https://github.com/xylex-group/athena-js/blob/main/docs/cli-command-reference.md Install the Athena.js CLI globally on your system if you need a system-wide binary. This allows you to run `athena-js` commands from any directory. ```bash pnpm add -g @xylex-group/athena ``` -------------------------------- ### Install React Email Dependencies Source: https://github.com/xylex-group/athena-js/blob/main/docs/auth/react-email.mdx Install the necessary React Email components and rendering utilities using pnpm. ```bash pnpm add @react-email/components @react-email/render ``` -------------------------------- ### QueryKey Usage Examples Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/react-hooks.md Examples demonstrating the usage of QueryKey with useQuery for different scenarios. ```typescript useQuery({ queryKey: 'users', queryFn: () => ... }) useQuery({ queryKey: ['user', userId], queryFn: () => ... }) useQuery({ queryKey: ['users', { status: 'active', page: 1 }], queryFn: () => ... }) ``` -------------------------------- ### List Sessions Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Example of listing all active sessions for the current user. ```typescript const result = await auth.session.list() if (!result.error) { result.data?.forEach(session => { console.log(`Session ${session.id}:`, { device: session.userAgent, ip: session.ipAddress, expiresAt: session.expiresAt }) }) } ``` -------------------------------- ### TenantContext Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/schema.md Example of using the TenantContext type alias. ```typescript type MyTenantContext = TenantContext<{ organizationId: 'x-org-id' userId: 'x-user-id' }> // { organizationId?: string | null; userId?: string | null } ``` -------------------------------- ### Example Usage of createModelFormAdapter Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/schema.md Example of creating a user adapter and using its methods. ```typescript const userAdapter = createModelFormAdapter(userModel, { status: 'active' }) const defaults = userAdapter.getDefaults() // { status: 'active', name: '', email: '' } const formData = userAdapter.toFormValues(user) // { name: user.name, email: user.email, status: user.status } const payload = userAdapter.toPayload(formData) // { name, email, status } ready for insert/update ``` -------------------------------- ### Install Athena JS SDK Source: https://github.com/xylex-group/athena-js/blob/main/docs/getting-started.md Install the Athena JS SDK using pnpm. React runtime support is optional and available from a separate package. ```bash pnpm add @xylex-group/athena ``` -------------------------------- ### useQuery Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/react-hooks.md An example of how to use the useQuery hook to fetch user data. ```typescript import { useQuery } from '@xylex-group/athena/react' function UserProfile({ userId }: { userId: string }) { const { data, isLoading, error, refetch } = useQuery({ queryKey: ['user', userId], queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()), refetchOnWindowFocus: true, retry: 3, onSuccess: (user) => { console.log('Loaded user:', user.name) } }) if (isLoading) return
Loading...
if (error) return
Error: {error.message}
return (

{data?.name}

) } ``` -------------------------------- ### GitHub Actions for Gateway-Only Introspection Source: https://github.com/xylex-group/athena-js/blob/main/docs/generator-cicd.md Example GitHub Actions workflow for generating schemas using gateway-only introspection. Includes steps for checkout, setup, installation, dry-run verification, and enforcing committed artifacts. ```yaml name: generator-gateway on: pull_request: branches: [main] jobs: generate: runs-on: ubuntu-latest timeout-minutes: 15 steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v4 with: node-version: 20 - run: pnpm install --frozen-lockfile # dry-run verification (no files written) - name: Verify generator (dry-run) env: ATHENA_URL: ${{ secrets.ATHENA_GENERATOR_URL }} ATHENA_API_KEY: ${{ secrets.ATHENA_GENERATOR_API_KEY }} run: pnpm exec athena-js generate --config ./athena.config.ts --dry-run # optional write + diff gate for PRs that include generated artifacts - name: Enforce generated artifacts are committed env: ATHENA_URL: ${{ secrets.ATHENA_GENERATOR_URL }} ATHENA_API_KEY: ${{ secrets.ATHENA_GENERATOR_API_KEY }} run: | pnpm exec athena-js generate --config ./athena.config.ts git diff --exit-code ``` -------------------------------- ### Install React Email Support Packages Source: https://github.com/xylex-group/athena-js/blob/main/README.md Install the necessary packages for using React Email components within your application. ```bash pnpm add @react-email/components @react-email/render ``` -------------------------------- ### Basic Product Management with useQuery and useMutation Source: https://github.com/xylex-group/athena-js/blob/main/README.md Demonstrates how to fetch a list of products and create new ones using `useQuery` and `useMutation`. It includes setting up the Athena client and query client provider. Manual refetching is used after mutations. ```tsx "use client"; import { AthenaQueryClientProvider, createAthenaQueryClient, useAthenaGateway, useMutation, useQuery, } from "@xylex-group/athena/react"; import { createClient } from "@xylex-group/athena"; const queryClient = createAthenaQueryClient({ cache: { mode: "none" }, // default: no persistent data cache, inflight dedupe only }); const athena = createClient( process.env.NEXT_PUBLIC_ATHENA_URL!, process.env.NEXT_PUBLIC_ATHENA_API_KEY!, ); type Product = { id: string; name: string; price: number; }; type CreateProductInput = { name: string; price: number; }; function ProductsInner() { const products = useQuery({ queryKey: ["products"], queryFn: () => athena.from("products").select("id,name,price").limit(50), }); const createProduct = useMutation({ mutationFn: (input) => athena.from("products").insert(input).select("id,name,price").single(), onSuccess: () => { void products.refetch(); }, }); if (products.isLoading) return
Loading...
; if (products.error) return
{products.error.message}
; return (
{products.data?.map((product) => (
{product.name} - {product.price}
))}
); } export function Products() { return ( ); } ``` -------------------------------- ### Insert Example (Single and Batch) Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/client.md Examples showing how to insert a single row and multiple rows using the `insert` method. ```javascript const result = await client .from('users') .insert({ name: 'Alice', email: 'alice@example.com' }) .select('id, name') const batch = await client .from('posts') .insert([ { title: 'Post 1', content: 'Lorem' }, { title: 'Post 2', content: 'Ipsum' } ]) .returning('id, title') ``` -------------------------------- ### Connection Probe GET Request Source: https://github.com/xylex-group/athena-js/blob/main/docs/runtime-method-ast-models.md Illustrates the underlying GET request performed by `verifyConnection`. The default path is '/'. ```text GET ``` -------------------------------- ### Authentication Examples Source: https://github.com/xylex-group/athena-js/blob/main/docs/auth/sign-in-up.mdx Demonstrates how to use the client to perform social sign-in, email sign-in, username sign-in, and email sign-up operations. Ensure the client is properly initialized before use. ```typescript import { client } from "./auth-client" await client.auth.signIn.social({ provider: "google", callbackURL: "https://app.example.com/auth/callback", }) await client.auth.signIn.email({ email: "user@example.com", password: "password", rememberMe: true, }) await client.auth.signIn.username({ username: "user1", password: "password", rememberMe: true, }) await client.auth.signUp.email({ name: "New User", email: "new-user@example.com", password: "password", callbackURL: "https://app.example.com/onboarding", }) ``` -------------------------------- ### GitHub Actions for Direct PostgreSQL Introspection Source: https://github.com/xylex-group/athena-js/blob/main/docs/generator-cicd.md Example GitHub Actions workflow for generating schemas using direct PostgreSQL introspection. Includes steps for checkout, setup, installation, dry-run verification, and enforcing committed artifacts. ```yaml name: generator-direct on: pull_request: branches: [main] jobs: generate: runs-on: ubuntu-latest timeout-minutes: 15 steps: - uses: actions/checkout@v4 - uses: pnpm/action-setup@v4 - uses: actions/setup-node@v4 with: node-version: 20 - run: pnpm install --frozen-lockfile # dry-run verification (no files written) - name: Verify generator (dry-run) env: PG_URL: ${{ secrets.GENERATOR_PG_URL }} run: pnpm exec athena-js generate --config ./athena.config.ts --dry-run # optional write + diff gate for PRs that include generated artifacts - name: Enforce generated artifacts are committed env: PG_URL: ${{ secrets.GENERATOR_PG_URL }} run: | pnpm exec athena-js generate --config ./athena.config.ts git diff --exit-code ``` -------------------------------- ### Client Initialization with Environment Variables Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/configuration.md Example of creating a client instance, typically loading configuration from environment variables. ```typescript // Typically loaded from process.env const client = createClient( process.env.VITE_ATHENA_URL || 'http://localhost:3000', process.env.VITE_ATHENA_API_KEY || 'dev-key', { client: process.env.VITE_APP_NAME || 'app', backend: process.env.VITE_ATHENA_BACKEND || 'athena' } ) ``` -------------------------------- ### Example Usage of createAuthClient Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Example demonstrating how to create and use the Athena Auth client for email sign-in. ```typescript import { createAuthClient } from '@xylex-group/athena' const auth = createAuthClient({ baseUrl: 'http://localhost:3001/api/auth', credentials: 'include', }) const { data, error } = await auth.signIn.email({ email: 'user@example.com', password: 'password123' }) if (!error) { console.log('Logged in as:', data?.user.email) } ``` -------------------------------- ### from Method Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/client.md Examples demonstrating the usage of the 'from' method for selecting all users and selecting active users with specific fields. ```typescript const users = await client .from<{ id: string; name: string }>('users') .select() const filtered = await client .from('users') .eq('status', 'active') .select('id, name') ``` -------------------------------- ### Server Capabilities Flag Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/findmany-ast-and-server-contract.md An example of a capability flag that the Athena server could expose to indicate support for findMany AST. ```json { "capabilities": { "find_many_ast": { "available": true } } } ``` -------------------------------- ### Example Usage of createClient Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/configuration.md Demonstrates how to create an Athena client with various configuration options. ```typescript import { createClient } from '@xylex-group/athena' const client = createClient( 'https://api.example.com/athena', 'sk_live_abc123...', { client: 'my-app', backend: 'athena', headers: { 'x-custom-header': 'value' }, userId: 'user_123', organizationId: 'org_456' } ) ``` -------------------------------- ### Define-Model Output Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/generator-quickstart.md Illustrates the default legacy output format of the define-model function. This example defines the structure and types for a 'users' model. ```typescript import { defineModel } from "@xylex-group/athena"; export interface PublicUsersRow { id: string email: string } export type PublicUsersInsert = Partial; export type PublicUsersUpdate = Partial; export const publicUsers = defineModel({ meta: { database: "app_db", schema: "public", model: "users", tableName: "public.users", primaryKey: ["id"], nullable: { id: false, email: false, }, }, }); ``` -------------------------------- ### Example Usage of createAuthClient Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/configuration.md Demonstrates how to create an authentication client with specific configuration. ```typescript import { createAuthClient } from '@xylex-group/athena' const auth = createAuthClient({ baseUrl: 'https://auth.example.com/api/auth', credentials: 'include', headers: { 'x-api-version': 'v1' } }) ``` -------------------------------- ### athena.auth.twoFactor.getTotpUri Source: https://github.com/xylex-group/athena-js/blob/main/docs/complete-method-reference.md Get TOTP URI for setup. Retrieves the Time-based One-Time Password URI for setting up authenticator apps. ```APIDOC ## POST /two-factor/get-totp-uri ### Description Get TOTP URI for setup. ### Method POST ### Endpoint /two-factor/get-totp-uri ### Parameters #### Request Body - **input** (AthenaTwoFactorGetTotpUriRequest & AthenaAuthFetchCompatibleInput) - Required - Input object for getting the TOTP URI. #### Options - **options** (AthenaAuthCallOptions) - Optional - Call options for authentication. ### Response #### Success Response (200) - **result** (AthenaAuthResult) - The result of the operation, containing the TOTP URI. ``` -------------------------------- ### Boot Generated Registry Immediately Source: https://github.com/xylex-group/athena-js/blob/main/docs/generator-quickstart.md Use generated files directly without further wrapping. This example shows how to create a typed client and query data from a model. ```typescript import { createTypedClient } from "@xylex-group/athena"; import { registry } from "./athena/config"; const athena = createTypedClient(registry, process.env.ATHENA_URL!, process.env.ATHENA_API_KEY!); const { data } = await athena.fromModel("primary", "public", "users").select("id,email"); ``` -------------------------------- ### Create and List Storage Catalogs Source: https://github.com/xylex-group/athena-js/blob/main/docs/storage/index.md Demonstrates how to create a new storage catalog with S3-compatible connection settings and then list all available storage catalogs. ```typescript const created = await athena.storage.createStorageCatalog({ name: "documents", description: "Private document bucket", endpoint: "https://s3.us-east-1.amazonaws.com", region: "us-east-1", bucket: "acme-documents", provider: "s3", access_key_id: process.env.S3_ACCESS_KEY_ID!, secret_key: process.env.S3_SECRET_ACCESS_KEY!, metadata: { environment: "production", }, }) const catalogs = await athena.storage.listStorageCatalogs() const active = catalogs.data.find(catalog => catalog.is_active) ``` -------------------------------- ### GET / Route for Live Version Probe Source: https://github.com/xylex-group/athena-js/blob/main/docs/findmany-ast-and-server-contract.md Demonstrates the basic GET / route, which serves as a live version probe for the Athena server. It returns server status, API version, and available routes. ```json { "message": "athena is online", "athena_api": "online", "version": "3.12.3", "cargo_toml_version": "3.12.3", "routes": [ { "methods": ["POST"], "path": "/gateway/fetch" }, { "methods": ["POST"], "path": "/gateway/query" } ] } ``` -------------------------------- ### Quick Start: Create Client and Fetch Data Source: https://github.com/xylex-group/athena-js/blob/main/README.md Demonstrates creating an Athena client with URL, API key, and client configuration, then fetching multiple records from a table with nested selections. Handles potential errors. ```typescript import { createClient } from "@xylex-group/athena"; const athenaClient = createClient( ATHENA_URL, ATHENA_API_KEY, { client: "CLIENT_NAME", backend: { type: "athena" }, }, ); const { data, error } = await athenaClient.from("orchestral_sections").findMany({ select: { name: true, instruments: { select: { name: true, }, }, }, }); if (error) { console.error("gateway error", error); } else { console.table(data); } ``` -------------------------------- ### AthenaGatewayCondition Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/gateway.md Example of an AthenaGatewayCondition. ```typescript const cond: AthenaGatewayCondition = { column: 'created_at', operator: 'gte', value: '2024-01-01', value_cast: 'date' } ``` -------------------------------- ### auth Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/errors.md Example of handling an auth error. ```typescript const result = await client .from('admin_users') .select() const normalized = normalizeAthenaError(result) if (normalized.kind === 'auth') { console.error('Access denied:', normalized.message) } ``` -------------------------------- ### verifyConnection(options?) Source: https://github.com/xylex-group/athena-js/blob/main/docs/runtime-method-ast-models.md Performs a lightweight GET probe to verify the connection to the Athena base URL. It sends a GET request to a specified path (defaulting to '/') with merged headers, ensuring the `X-Athena-Sdk` header is present. ```APIDOC ## GET ### Description Performs a lightweight GET probe to verify the connection to the Athena base URL. It sends a GET request to a specified path (defaulting to '/') with merged headers, ensuring the `X-Athena-Sdk` header is present. ### Method GET ### Endpoint (default path is '/') ### Parameters #### Query Parameters - **options** (object) - Optional - Configuration for the connection probe. - **path** (string) - Optional - The specific path to probe. Defaults to '/'. - **headers** (Record) - Optional - Additional headers to include in the probe request. - **signal** (AbortSignal) - Optional - An AbortSignal to cancel the probe request. ### Request Example (No explicit request body, but headers can be provided in options) ### Response #### Success Response (200) Indicates a successful connection probe. #### Response Example (Typically an empty response or a simple success indicator) ``` -------------------------------- ### validation Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/errors.md Example of handling a validation error. ```typescript const result = await client.from('users').insert({ email: 'invalid-email' // Not actually validated by Athena }) const normalized = normalizeAthenaError(result) if (normalized.kind === 'validation') { console.error('Invalid data:', normalized.message) } ``` -------------------------------- ### not_found Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/errors.md Example of handling a not_found error. ```typescript const result = await client .from('users') .eq('id', 'nonexistent') .single() const normalized = normalizeAthenaError(result) if (normalized.kind === 'not_found') { console.log('User not found') } ``` -------------------------------- ### unique_violation Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/errors.md Example of handling a unique_violation error. ```typescript const result = await client .from('users') .insert({ email: 'existing@example.com' }) const normalized = normalizeAthenaError(result) if (normalized.kind === 'unique_violation') { console.error(`Constraint violated: ${normalized.constraint}`) } ``` -------------------------------- ### Create Athena Client (Fastest) Source: https://github.com/xylex-group/athena-js/blob/main/docs/getting-started.md Create an Athena client using the `createClient` function for the quickest setup. Ensure environment variables for URL and API key are set. ```typescript import { createClient } from "@xylex-group/athena"; const athena = createClient(process.env.ATHENA_URL!, process.env.ATHENA_API_KEY!, { client: "web-dashboard", backend: { type: "athena" }, }); ``` -------------------------------- ### createPostgresIntrospectionProvider Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/schema.md Example usage of createPostgresIntrospectionProvider. ```typescript const provider = createPostgresIntrospectionProvider({ host: 'localhost', port: 5432, database: 'myapp', user: 'postgres', password: 'password' }) const snapshot = await provider.introspect() console.log(snapshot.tables) ``` -------------------------------- ### toModelPayload Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/schema.md Example usage of toModelPayload. ```typescript const payload = toModelPayload(userModel, formData, { nullishMode: 'null', excludeFields: ['id'] }) // Ready to pass to insert() or update() ``` -------------------------------- ### toModelFormDefaults Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/schema.md Example usage of toModelFormDefaults. ```typescript const defaults = toModelFormDefaults(userModel, { nullishMode: 'empty-string', excludeFields: ['createdAt', 'id'] }) // { name: '', email: '', status: '' } ``` -------------------------------- ### Direct Athena useQuery and useMutation Pattern Source: https://github.com/xylex-group/athena-js/blob/main/test-sdk/examples/react-hooks/README.md Demonstrates using useQuery for fetching products and useMutation for creating a new product, with automatic refetching on success. ```tsx const products = useQuery({ queryKey: ['products', organizationId], enabled: Boolean(organizationId), queryFn: async () => { const result = await athena .from('products') .select('id,name,price') .eq('organization_id', organizationId) .limit(50) if (result.error) throw new Error(result.error) return result.data ?? [] }, }) const createProduct = useMutation({ mutationFn: async (input) => { const result = await athena .from('products') .insert(input) .select('id,name,price') .single() if (result.error || !result.data) throw new Error(result.error ?? 'insert failed') return result.data }, onSuccess: () => void products.refetch(), }) ``` -------------------------------- ### athena.auth.apiKey.get Source: https://github.com/xylex-group/athena-js/blob/main/docs/complete-method-reference.md Get API key metadata. This method corresponds to the `GET /api-key/get` route. ```APIDOC ## GET /api-key/get ### Description Get API key metadata. ### Method GET ### Endpoint /api-key/get ### Parameters #### Query Parameters - **query** (AthenaApiKeyGetQuery) - Optional - Query parameters for retrieving API key metadata. #### Request Body - **options** (AthenaAuthCallOptions) - Optional - Call options. ### Response #### Success Response (200) - **result** (AthenaAuthResult) - The API key record. ``` -------------------------------- ### Sign Up with Email Source: https://github.com/xylex-group/athena-js/blob/main/docs/complete-method-reference.md Creates a new user account using an email and password. Corresponds to the POST /sign-up/email route. ```javascript await athena.auth.signUp.email({ /* input */ }) ``` -------------------------------- ### transient Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/errors.md Example of handling a transient error with automatic retries. ```typescript const normalized = normalizeAthenaError(result) if (normalized.kind === 'transient' && normalized.retryable) { // Automatically retry with exponential backoff const data = await withRetry( async () => { const result = await client.from('users').select() if (result.error) throw normalizeAthenaError(result) return result.data }, { retries: 5, backoff: 'exponential' } ) } ``` -------------------------------- ### Create and Use Typed Client Source: https://github.com/xylex-group/athena-js/blob/main/docs/typed-schema-registry.md Creates a typed client with tenant key mapping and demonstrates querying user data with tenant context. ```typescript const typed = createTypedClient(registry, "https://athena-db.com", "secret", { tenantKeyMap: { organizationId: "X-Organization-Id", workspaceId: "X-Workspace-Id", }, }); await typed .withTenantContext({ organizationId: "org-1" }) .fromModel("app", "public", "users") .select("id, email") .eq("active", true); ``` -------------------------------- ### root.athenaAuth Source: https://github.com/xylex-group/athena-js/blob/main/docs/complete-method-reference.md Initializes an Athena authentication server with the provided configuration. ```APIDOC ## root.athenaAuth ### Description Initializes an Athena authentication server with the provided configuration. ### Signature `(config: TConfig) => AthenaAuthServer` ### Example `athenaAuth(/* ... */)` ``` -------------------------------- ### Disable Registry Emission Example Source: https://github.com/xylex-group/athena-js/blob/main/docs/generator-config.md Example configuration to disable the emission of the registry file in constrained workflows. ```typescript features: { emitRegistry: false, } ``` -------------------------------- ### Storage Module Initialization and Usage Source: https://github.com/xylex-group/athena-js/blob/main/docs/api-reference.md This snippet demonstrates how to enable the experimental storage backend and use various storage functions like creating upload URLs, uploading files, getting file proxies, and deleting files. ```APIDOC ## Storage Module (experimental) Storage bindings are only available when `experimental.athenaStorageBackend` is enabled. ### Initialization ```ts const athena = createClient(url, apiKey, { experimental: { athenaStorageBackend: true, storage: { onError(error) { console.error(error.code, error.athenaCode, error.kind, error.toDetails()) }, }, }, }) ``` ### Core Operations - **Create Storage Upload URL** - **Description**: Generates a pre-signed URL for uploading a file to storage. - **Method**: `athena.storage.createStorageUploadUrl` - **Parameters**: - `s3_id` (string) - Required - Identifier for S3. - `bucket` (string) - Required - The bucket name. - `storage_key` (string) - Required - The key (path) for the file in the bucket. - **Example Request**: ```json { "s3_id": "s3_1", "bucket": "documents", "storage_key": "reports/report.pdf" } ``` - **File Upload** - **Description**: Uploads a file to the specified storage location. - **Method**: `athena.storage.file.upload` - **Parameters**: - `s3_id` (string) - Required - Identifier for S3. - `bucket` (string) - Required - The bucket name. - `files` (File) - Required - The file object to upload. - `extensions` (string[]) - Optional - Allowed file extensions. - `maxFileSizeMb` (number) - Optional - Maximum file size in megabytes. - **Example Request**: ```json { "s3_id": "s3_1", "bucket": "documents", "files": selectedFile, "extensions": ["pdf"], "maxFileSizeMb": 25 } ``` - **Get Storage File Proxy** - **Description**: Retrieves a proxy response for a storage file, often used for downloading. - **Method**: `athena.storage.getStorageFileProxy` - **Parameters**: - `fileId` (string) - Required - The ID of the file. - `query` (object) - Optional - Query parameters, e.g., `{ purpose: "download" }`. - **Example Request**: ```json { "fileId": "file_1", "query": { "purpose": "download" } } ``` - **Response**: Returns a `Response` object from which `arrayBuffer()` can be called. - **Delete File** - **Description**: Deletes a file from storage. - **Method**: `athena.storage.delete` - **Parameters**: - `fileId` (string) - Required - The ID of the file to delete. - **Example Usage**: ```ts await athena.storage.delete("file_1") ``` ``` -------------------------------- ### Manage Organization Members Source: https://github.com/xylex-group/athena-js/blob/main/docs/auth/organization-members.mdx Examples demonstrating how to interact with organization member endpoints. Ensure the 'client' is properly initialized before use. ```typescript import { client } from "./auth-client" await client.auth.organization.member.remove({ memberIdOrEmail: "member@example.com", }) await client.auth.organization.member.updateRole({ memberId: "member_1", role: "admin", }) await client.auth.organization.member.invite({ email: "new-member@example.com", role: "member", }) await client.auth.organization.member.getActive() await client.auth.organization.member.list({ query: { organizationId: "org_1", limit: 50, sortBy: "createdAt", sortDirection: "desc", }, }) ``` -------------------------------- ### UNIQUE_VIOLATION Error Code Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/errors.md Example of checking for the UNIQUE_VIOLATION error code. ```typescript if (normalized.code === AthenaErrorCode.UniqueViolation) { console.error(`Duplicate: ${normalized.constraint}`) } ``` -------------------------------- ### Schema Selection Examples Source: https://github.com/xylex-group/athena-js/blob/main/docs/generator-config.md Demonstrates different ways to specify schemas for generation, including arrays, comma-separated strings, and environment variables. ```typescript schemas: ["public", "athena"] ``` ```typescript schemas: process.env.ATHENA_GENERATOR_SCHEMAS ?? "public,athena" ``` ```typescript schemas: generatorEnv.list("ATHENA_GENERATOR_SCHEMAS", { default: ["public", "athena"], }) ``` -------------------------------- ### Start a query builder with athena.from Source: https://github.com/xylex-group/athena-js/blob/main/docs/complete-method-reference.md Initialize a query builder using `athena.from`. This can be used with a model or a table name. ```typescript athena.from(/* ... */) ``` -------------------------------- ### rate_limit Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/errors.md Example of handling a rate_limit error and implementing retry logic. ```typescript const normalized = normalizeAthenaError(result) if (normalized.kind === 'rate_limit' && normalized.retryable) { // Implement exponential backoff before retrying await new Promise(r => setTimeout(r, 5000)) // Retry operation } ``` -------------------------------- ### ModelAt Usage Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/schema.md Example of using the ModelAt type alias. ```typescript type User = ModelAt // Same as the userModel definition ``` -------------------------------- ### RowOf Usage Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/schema.md Example of using the RowOf type alias. ```typescript type UserRow = RowOf // Equivalent to the Row generic passed to defineModel ``` -------------------------------- ### Create Client with Legacy Gateway and Auth URLs Source: https://github.com/xylex-group/athena-js/blob/main/README.md Demonstrates creating an Athena client using legacy top-level aliases for gateway, authentication, and storage URLs. ```typescript const athena = createClient({ key: ATHENA_API_KEY, gatewayUrl: process.env.ATHENA_DB_URL, authUrl: process.env.ATHENA_AUTH_URL, storageUrl: process.env.ATHENA_STORAGE_URL, }); ``` -------------------------------- ### AthenaClient.fromEnvironment Source: https://github.com/xylex-group/athena-js/blob/main/docs/api-reference.md Initializes an AthenaClient by reading configuration from environment variables. It looks for `ATHENA_URL` or `ATHENA_GATEWAY_URL` and `ATHENA_API_KEY` or `ATHENA_GATEWAY_API_KEY`. Throws an error if the URL or API key is missing. ```APIDOC ## AthenaClient.fromEnvironment() ### Description Initializes an `AthenaClient` by reading configuration from environment variables. It looks for `ATHENA_URL` or `ATHENA_GATEWAY_URL` and `ATHENA_API_KEY` or `ATHENA_GATEWAY_API_KEY`. Throws an error if the URL or API key is missing. ### Usage ```ts const client = AthenaClient.fromEnvironment() ``` ``` -------------------------------- ### useAthenaGateway Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/react-hooks.md An example of how to use the useAthenaGateway hook to fetch user data. ```typescript import { useAthenaGateway } from '@xylex-group/athena/react' function CustomQuery() { const { fetchGateway, isLoading, error } = useAthenaGateway() const loadUsers = async () => { const response = await fetchGateway({ table_name: 'users', columns: 'id, name, email', limit: 10 }) console.log(response.data) } return ( ) } ``` -------------------------------- ### useMutation Example Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/react-hooks.md An example of how to use the useMutation hook to create a new post. ```typescript import { useMutation } from '@xylex-group/athena/react' function CreatePost() { const { mutate, isLoading, error } = useMutation({ mutationFn: async (title: string) => { const result = await client .from('posts') .insert({ title, user_id: 'me' }) .select() return result.data }, onSuccess: (data) => { console.log('Post created:', data?.id) }, onError: (error) => { console.error('Failed to create post:', error.message) } }) return ( ) } ``` -------------------------------- ### List, Download, and Delete Files Source: https://github.com/xylex-group/athena-js/blob/main/docs/storage/index.md Provides examples for listing files within a prefix, downloading single or multiple files, and deleting single files or batches of files. ```typescript const page = await athena.storage.file.list({ s3_id: "s3_1", prefix: "reports", }) const response = await athena.storage.file.download("file_1", { purpose: "download", }) const bytes = await response.arrayBuffer() const responses = await athena.storage.file.download(["file_1", "file_2"], { purpose: "stream", }) await athena.storage.file.delete("file_1") await athena.storage.delete(["file_2", "file_3"]) ``` -------------------------------- ### Example: List Linked Accounts Source: https://github.com/xylex-group/athena-js/blob/main/_autodocs/api-reference/auth.md Demonstrates how to list and log the provider and account ID of linked accounts. ```typescript const result = await auth.account.list() result.data?.forEach(account => { console.log(`${account.provider}: ${account.providerAccountId}`) }) ```