Alle Artikel

Artikel

Type-Safe Database Clients with SurrealDB: Automating Schema Generation

How generated Zod schemas, TypeScript types, and client helpers reduce drift between SurrealDB schemas and application code.

Type safety across the full stack is a holy grail for TypeScript developers. While tools like Prisma and Drizzle have solved this for SQL databases, NoSQL databases often leave you manually maintaining type definitions.

The Type Safety Gap

When working with SurrealDB, you define your schema in the database. But then you need to:

  1. Manually create TypeScript interfaces
  2. Write validation logic (often with Zod)
  3. Keep everything in sync when the schema changes

This manual process is error-prone and tedious.

Automated Schema Generation

The solution is to introspect the database schema and generate both TypeScript types and Zod schemas automatically:

// Generated automatically from your SurrealDB schema
export const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
  createdAt: z.string().datetime(),
});

export type User = z.infer<typeof UserSchema>;

How It Works

  1. Introspection: Query SurrealDB’s INFO FOR DB and INFO FOR TABLE statements
  2. Parsing: Convert SurrealDB’s type system to Zod equivalents
  3. Generation: Output TypeScript files with both schemas and types
  4. Client Generation: Create a type-safe query builder on top

Benefits

  • Single Source of Truth: Your database schema is the canonical definition
  • Runtime Validation: Zod schemas validate data at runtime
  • IDE Support: Full autocomplete and type checking
  • No Drift: Regenerate whenever the schema changes

Getting Started

Install the generator:

npm install -D surrealdb-client-generator

Run it against your database:

npx surrealdb-client-generator --url http://localhost:8000

Check out the full project on GitHub.