Prisma Client is a fully type-safe database access client that is automatically generated based on our Prisma Schema files. In this lesson, we use Prisma Client to access records in our database programmatically. We show how to return the data from an endpoint built with express.
Ryan Chenkie: [0:00] This server.ts file has a single endpoint called "/ping" and that just gives a simple message. Run the app with npm run dev and verify in the browser that this will give us our message, message: "hello".
[0:13] Prisma Client can be used to get the data that is currently in the database and return it as JSON from an endpoint. Copy app.get here and create a new endpoint called "/products". Import { PrismaClient } from "@Prisma/client". Create an instance of Prisma clients with const prisma = new PrismaClient().
[0:37] In the new endpoint, retrieve the records using Prisma. We'll use async/await, so make sure that this function here is async and then call for the products, const products = await prisma.product.findMany(). Then in the response as JSON, we can return that products array. Save the file and in the browser navigate to the products endpoint.
[1:02] Prisma Client gets the products data from the database and the endpoint sends it back as JSON. When using the Prisma Client, it is important to note that it gives a full type-safe database access. On this Prisma object, there are methods and properties that are applicable to interacting with the database.
[1:22] The single table that we have right now is product and that's reflected if we look for what's available as we autocomplete this call. We have several Prisma methods, methods that are useful in various scenarios when interacting with Prisma Client.
[1:37] This property down here, product, points to the products table. On this property we have a number of methods that we can call, and all of these are generated by Prisma based on what we should be able to do with our database. In this scenario, when we want to find all of the records in our table, the findMany method would be the appropriate one to call.