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:
- Manually create TypeScript interfaces
- Write validation logic (often with Zod)
- 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
- Introspection: Query SurrealDB’s
INFO FOR DBandINFO FOR TABLEstatements - Parsing: Convert SurrealDB’s type system to Zod equivalents
- Generation: Output TypeScript files with both schemas and types
- 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.