Introducci贸n a Node.js y Express
Node.js y Express
Entorno de trabajo
Variables de entorno
Rutas din谩micas
Body parser
Postman
CRUD
驴Que es una API Restful?
Solicitudes GET
Solicitudes POST
CRUD
Soluci贸n del reto de validaci贸n
Solicitudes DELETE
MIddlewares
Middlewares - logger
Middlewares - ErrorHandler
DB
Instalar Postgresql
Instalar Prisma y PostgreSQL Client
Prisma Models
JWT
Autenticaci贸n utilizando JSON Web Tokens (JWT)
Auth - Register
Auth - Login
Expres.js
Arquitectura
Arquitectura parte 2
Creaci贸n y Migraci贸n de Modelos con Prisma para Citas M茅dicas
Admin controllers / services
Admin controllers / services parte 2
Reservations
Reservations parte 2
Appointments
Deploy
PostgreSQL
Deploy
You don't have access to this class
Keep learning! Join and start boosting your career
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.
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.
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:
Once the dependencies are installed, we must initialize Prisma in our project:
npx prisma init
This command creates:
prisma
folder with a file schema.prisma
.env
file for our environment variablesIt 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 password5432
: The default port of PostgreSQLpostgres
: The database nameIn 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:
id
field as an integer, primary key and autoincremental.name
field as a text stringemail
field as a text string with uniqueness constraintAfter 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:
Once Prisma is configured, we can integrate it into our Express application to perform database operations.
In our main file (e.g. app.js
), we import and configure the Prisma client:
const { PrismaClient } = require('@prisma/client');constprisma = new PrismaClient();
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:
(async/await
) to handle database operations.try/catch
blocks.findMany()
, findUnique()
, create()
, etc.Working with Prisma offers multiple benefits:
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
Want to see more contributions, questions and answers from the community?