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
Creating robust APIs requires careful planning of access points, especially when dealing with sensitive information such as medical appointments. In this article, we will explore how to implement an endpoint that allows authenticated users to view their appointment history, ensuring data security and privacy through authentication tokens.
When developing an API to manage appointments, it is critical to consider that a user could have multiple appointments in the system. Therefore, we need to create a specific entry point that allows each user to see only their own appointments, while keeping the information protected through authentication.
To implement this functionality, we will follow these steps:
The first step is to modify our main routing file to include the new resource. We need to add the appointments router and link it to the users route:
// In the main routing file (index.js)const appointmentsRouter = require('./appointments');
// We set up the route for users to access their appointmentsrouter.use('/users', appointmentsRouter);
Now, we must create the specific routing file for the appointments. This file will define the endpoints available to manage appointments:
// In the appointments.js fileconst router = require('express').Router();const appointmentController = require('../controllers/appointmentController');const authenticateToken = require('../middlewares/authenticate');
// Path to get a specific user's appointments// Protected with authentication middlewarerouter.get('/:id/appointments', authenticateToken, appointmentController.getUserAppointments);
module.exports = router;
It is crucial to note that we have included authentication middleware to ensure that only authenticated users can access this information. This protects data privacy and prevents unauthorized access.
The controller acts as an intermediary between routes and services. Its function is to receive the request, process it and return an appropriate response:
// In appointmentController.jsconst appointmentService = require('../services/appointmentService');
exports.getUserAppointments = async (req, res) => { try { const userId = req.params.id; const appointments = await appointmentService.getUserAppointments(userId);
res.json(appointments); } catch (error) { res.status(500).json({ message: 'Error getting appointment history' }); } } };
The controller extracts the user ID from the request parameters, calls the corresponding service and returns the results in JSON format. In case of error, it responds with a status code 500 and a descriptive message.
The service contains the business logic and communicates directly with the database. For our case, we will use Prisma as the ORM:
// In appointmentService.jsconst prisma = require('../config/prisma');
exports.getUserAppointments = async (userId) => { try { const appointments = await prisma.appointment.findMany({ where: { userId: parseInt(userId) }, include: { timeBlock: true } });
return appointments; } catch (error) { throw new Error('Error getting appointment history'); } } };
In this service:
findMany
method to find all appointments associated with the user.parseInt
timeBlock
relation to get additional information about each appointmentTo verify that our endpoint is working correctly, we can use Postman:
/users/:id/appointments
If everything is configured correctly, we should receive a JSON with the list of appointments for the specified user.
Security is a critical aspect when we develop APIs that handle personal information. Some important considerations are:
Once the basic endpoint for listing appointments is implemented, we can consider several enhancements:
Implementing a robust appointment system requires attention to these details to provide a complete and secure experience for users.
Creating well-structured and secure APIs is fundamental to modern application development. By following REST design principles and applying good security practices, we can build reliable systems that protect our users' information while delivering full functionality. What other features do you consider important for an appointment management API? Share your ideas in the comments.
Contributions 0
Questions 0
Want to see more contributions, questions and answers from the community?