So, once you've done that, kind of your next question is whether you want to use a query builder or write raw SQL. So, let's look at the query builder option.
So, connects JS is probably the most popular query builder for JavaScript and TypeScript. So, let's take a look at what this example looks like using connects. So, to query the database, we use this connects object and we tell it we want to look at the book table and we want to select everything from it. And connects is smart enough to figure out that it has a book type and we already get some type errors, which is what we wanted.
So, how does this work? So, I'm assuming that you're running pg2ts or something like that to get this book interface to find in TypeScript. That's an important building block. Then there's also this connects types table, which you can use to tell Kinects about your schema. So, you define this tables interface and it has a list of all your tables. And it's able to, if you query from one of these tables, it's able to pull in the correct types. So, that's pretty neat.
So, we can go ahead and fix the error here. And so, over here. Great. So, let's save that. And reload. Great. The bug's fixed.
So, let's take a look at what a migration looks like in this world. So, I'm gonna go ahead and run my migration. And so, now, as you might remember, the publication year is nullable. So, now, I have to regenerate the DB schema. So, now, if I go ahead and look in DB schema, yep, publication year is nullable. And sure enough, we have a type error in index.ts, which is exactly what we want. And so, we can go ahead and plug in the bug fix, and if we go over here, great, it's fixed.
So, you can also do slightly more elaborate queries with connects. So, here's an example of joining the books table on the author. So, let's plug that in. So, we're querying the books table as before, but now, we're going to join on the users table, joining the book.createdBy column to the users.id column, and if you look at the inferred type, it's book and users, the intersection type, which is actually exactly right.
Comments