If you have not already read the first part of the blog on Building a Serverless GraphQL API with Prisma, Apollo & TypeGraphQL-Prisma, I recommend doing so before proceeding with this second part.
In this second part, the focus is on configuring Prisma and establishing a connection with PostgreSQL. The steps involved in this process will be discussed in detail.
Pre-Requisites
Set up Prisma
The first step in configuring Prisma is to install the Prisma CLI as a development dependency in the project. This can be done using the following command in the terminal:
npm install prisma --save-dev
The next step is to set up Prisma using the init command of the Prisma CLI. This command creates a new Prisma project in the project directory. To do this, run the following command in the terminal:
npx prisma init --datasource-provider postgresql
Prisma will generate the necessary files and directories for the project, including the prisma directory, schema.prisma file
To model data in the Prisma schema, you may add the following models to the schema.prisma file
After defining the database schema in the schema.prisma file, you need to add the relevant database configuration data to the .env file. This is because the url property in the datasource block of the schema.prisma file is set to use the DATABASE_URL environment variable to connect to the database.
Ex :-
DB_TYPE=postgres
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=1234
DB_NAME=test_db
connection_limit=1
pool_timeout=10
ssl_accept=strict
DATABASE_URL=${DB_TYPE}://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}?sslaccept=${ssl_accept}&connection_limit=${connection_limit}&pool_timeout=${pool_timeout}
After defining the data models in the schema.prisma file, you can use the prisma-typegraphql-types-generator package to generate TypeScript interfaces for the Prisma models and enums.
npm i --dev prisma-typegraphql-types-generator type-graphql
To define the prisma-typegraphql-types-generator in the schema.prisma file, you can add the following generator block:
You can use the npx prisma db push command to apply the schema changes to the PostgreSQL database. this command should have created two tables in your PostgreSQL database: Post and User. These tables correspond to the data models defined in the schema.prisma file.
After defining the Prisma schema and adding the necessary configurations, you can use the
npx prisma generate
command to generate the Prisma client.it will generate the relevant user and post model files.
In order to use decorators in your TypeScript code, you need to enable the experimentalDecorators and emitDecoratorMetadata options in the tsconfig.json file.
To enable these options, open the tsconfig.json file and add the following lines to the compilerOptions section:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}