
Lesson Description
The "Exporting Database Types & Schemas" Lesson is part of the full, API Design in Node.js, v5 course featured in this preview video. Here's what you'd learn in this lesson:
Scott demonstrates exporting TypeScript types and Zod schemas for tables like user, habit, entry, and tag. He shows validating inputs against database rules to ensure data consistency at runtime.
Transcript from the "Exporting Database Types & Schemas" Lesson
[00:00:00]
>> Speaker 1: We want to export some types that are going to help us do some stuff At the bottom, typically what I do is import some helpers first from Zod I'm going to say import from, I think it's Drizzle, yeah So I'm going to get to create insert schema and then I'm going to get the create select schema
[00:00:00]
At the bottom, what I'm going to do is export some types and then export some schemas I'll say export const type I'll make a capital User here and say type of Users table I'll export type Users select So what is this actually saying
[00:00:00]
I'm basically making a TypeScript type whose fields will be the same fields as the Users table, and I'm inferring that type by doing type of This is built into all Drizzle schema's infer select, which allows me to do type of to infer what it is and create a TypeScript type that we can use all over our app, which is super useful
[00:00:00]
I'll do this for everything we have: User, Habit, Entries, Entry, and Tags or Habitat That will give us the types, and then we can also use schemas to validate different inputs using Zod What we can do is export a schema based on the rules of the database for creating a user
[00:00:00]
If I look at the user, what does a user need to be created It has to have an ID that gets generated for us You have to pass in an email (it's got to be unique), a username (also unique), and a password Some of these are optional and get created with defaults
[00:00:00]
I want to make an enforceable schema that I can use at runtime based on this table without having to write it myself So I'll create an insert user schema that can be used to validate inputs to ensure they follow the database schema
[00:00:00]
I'll use create insert schema and pass in the Users table, which will give me an insert user schema I can do the same thing for a select user schema The benefit is that what a user needs to be created is very different from what you would get back when querying a user
[00:00:00]
When querying, you'd see an ID, created at, updated at, and other metadata When inserting a user, you wouldn't see any of that This schema helps me check at runtime that the object follows the selected schema I still have the TypeScript type, but this allows me to validate at runtime
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops