Savvi Studio

Codegen Examples

Purpose: Code examples for common codegen scenarios
Last Updated: 2024-11-28

Overview

This directory contains practical examples of using generated code in various scenarios.

Examples

Basic Usage

  • Simple function calls
  • Parameter handling
  • Return type handling
  • Error handling basics

Custom Types

  • Working with enums
  • Using composite types
  • Domain types with constraints
  • Array and range types

Testing

  • Unit tests with mocks
  • Integration tests with real database
  • Test fixtures and utilities
  • Testing patterns

Quick Examples

Simple Function Call

import { withClient } from '@/lib/db';
import { createResource } from '@db/graph';

const id = await withClient(async (client) => {
  return await createResource(client, {
    p_type_namespace: 'test.user',
    p_data: { name: 'John' }
  });
});

With Transaction

import { withTransaction } from '@/lib/db';
import { createResource, linkResources } from '@db/graph';

await withTransaction(async (client) => {
  const user = await createResource(client, {
    p_type_namespace: 'test.user',
    p_data: {}
  });
  
  const post = await createResource(client, {
    p_type_namespace: 'test.post',
    p_data: {}
  });
  
  await linkResources(client, {
    p_from_id: user,
    p_to_id: post,
    p_edge_type: 'authored'
  });
});

Error Handling

import { ZodError } from 'zod';
import { DatabaseError } from 'pg';

try {
  await createResource(client, params);
} catch (error) {
  if (error instanceof ZodError) {
    console.error('Validation error:', error.errors);
  } else if (error instanceof DatabaseError) {
    console.error('Database error:', error.message);
  }
}

Testing

import { describe, it, expect } from 'vitest';
import { withTestClient } from '@/test/utils';
import { createResource } from '@db/graph';

describe('createResource', () => {
  it('creates resource', async () => {
    await withTestClient(async (client) => {
      const id = await createResource(client, {
        p_type_namespace: 'test.user',
        p_data: { name: 'Test' }
      });
      
      expect(id).toBeDefined();
    });
  });
});

Note: All examples assume you've run pnpm db:codegen and have generated code in src/__generated__/.