You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
5 Hrs
47 Min
21 Seg
Curso de Backend con ExpressJS

Curso de Backend con ExpressJS

Oscar Barajas Tavares

Oscar Barajas Tavares

Instalar Prisma y PostgreSQL Client

16/30
Resources

Database integration in modern applications is an essential component for robust software development. Prisma, as an ORM (Object-Relational Mapping), greatly simplifies the communication between our Node.js application and databases such as PostgreSQL, allowing us to work more efficiently and securely with our data.

How to configure Prisma with PostgreSQL in a Node.js application?

To start using Prisma with PostgreSQL in our Node.js application, we need to follow several installation and configuration steps. This process will allow us to establish an effective communication between our application and the database.

Installation of necessary dependencies

The first thing we need to do is to install the packages required to work with Prisma and PostgreSQL:

npm install prisma --save-devnpm install @prisma/clientnpm install pg

These installations provide us with:

  • Prisma CLI: As a development dependency to manage our schema and migrations.
  • Prisma Client: To interact with the database from our code.
  • pg: The PostgreSQL driver needed for the connection.

Initialization and configuration of the project

Once the dependencies are installed, we must initialize Prisma in our project:

npx prisma init

This command creates:

  • A prisma folder with a file schema.prisma
  • An .env file for our environment variables

It is recommended to install the Prisma extension for your code editor, which will make it easier to read and edit the .prisma files with syntax highlighting.

Now we must configure the connection to our database in the .env file:

DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/postgres"

Where:

  • USER: The PostgreSQL user name.
  • PASSWORD: The user's password
  • 5432: The default port of PostgreSQL
  • postgres: The database name

Definition of the data model

In the schema.prism file, we define our data models. For example, for a user model:

model User { id Int @id @default(autoincrement()) name String email String @unique}

This model defines:

  • An id field as an integer, primary key and autoincremental.
  • A name field as a text string
  • An email field as a text string with uniqueness constraint

Client generation and migrations

After defining our model, we generate the Prisma client:

npx prisma generate

And we create the migration to apply these changes to the database:

npx prisma migrate dev --name init

This command:

  1. Analyzes our schema
  2. Generates the necessary SQL files
  3. Applies the changes to the database
  4. Creates a migration log for tracking

How to integrate Prisma into an Express application?

Once Prisma is configured, we can integrate it into our Express application to perform database operations.

Prisma client configuration

In our main file (e.g. app.js), we import and configure the Prisma client:

const { PrismaClient } = require('@prisma/client');constprisma = new PrismaClient();

Implementing endpoints to access the data

Now we can create routes that use Prisma to interact with the database. For example, to get all the users:

app.get('/db/users', async (req, res) => { try { const users = await prisma.user.findMany(); res.json(users); } catch (error) { res.status(500).json({ error: "Error communicating with database" }); } } });

It is important to note that when working with Prisma:

  • We use asynchronous functions(async/await) to handle database operations.
  • We implement error handling with try/catch blocks.
  • Prisma provides intuitive methods such as findMany(), findUnique(), create(), etc.

Advantages of using Prisma as an ORM

Working with Prisma offers multiple benefits:

  • Secure typing: Especially useful when working with TypeScript.
  • Programmatic queries: More readable and less error-prone than writing SQL directly.
  • Automatic migrations: Facilitates database schema evolution.
  • SQL injection prevention: Increased security in database operations
  • Auto-completion in the editor: Improves the development experience

How to test the database connection?

Once everything is configured, we can test our connection by running the application:

npm run dev

And accessing the path we have created, for example: http://localhost:3000/db/users

If the connection is successful but there is no data, we will see an empty array ([]). This indicates that the connection is working correctly, but we have not yet added users to the database.

If there was a connection problem, we would see the error message we defined in our error handler.

Prisma's integration with PostgreSQL provides a solid foundation for developing applications with data persistence efficiently. In future steps, you will be able to expand this configuration to implement full CRUD operations and inter-model relationships.

Have you worked with ORMs before, and how does Prisma compare to other alternatives? Share your experience in the comments.

Contributions 1

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Para a帽adir nuevos usuarios en una base de datos PostgreSQL utilizando Prisma, debes seguir los siguientes pasos: 1. Aseg煤rate de tener el modelo de usuario definido en tu archivo `schema.prisma`. 2. Utiliza el m茅todo `create` de Prisma Client. Por ejemplo: ```javascript const newUser = await prisma.user.create({ data: { name: "Nombre del Usuario", email: "[email protected]", }, }); ``` 3. Verifica que los datos cumplan con las restricciones de tu modelo, como la unicidad del email. Recuerda ejecutar el c贸digo dentro de una funci贸n as铆ncrona y manejar errores con un bloque `try-catch`.