API Services
Relevant source files
The following files were used as context for generating this wiki page:
The API services layer in the frontend application is responsible for all communication with the backend server. It abstracts the HTTP request/response logic, providing a clean and reusable interface for components to interact with server-side resources. This layer is built using the axios library and is organized into modules based on data domains, such as authentication, user accounts (taiKhoan), and devices (thietBi).
The backend is an Express.js application that defines the corresponding API endpoints. It handles business logic, database interactions with MongoDB, and user authentication. The main server file (server.js) acts as the entry point, configuring middleware and mounting the various API route modules.
Sources: frontend/src/services/authAPI.js, frontend/src/services/taiKhoanAPI.js, backend/src/server.js:81-83
Core Configuration
The API services rely on a centrally configured axios instance. This setup ensures consistency across all API calls.
Axios Instance
A pre-configured axios instance is created in each service file. The key configurations are:
baseURL: The base URL for all API requests. It is sourced from theREACT_APP_API_BASEenvironment variable, with a fallback tohttp://localhost:5001/api.withCredentials: Set totrueto automatically send and receive cookies, which is crucial for the JWT-based authentication strategy used in the application.headers: TheContent-Typeis set toapplication/jsonby default.
Sources: frontend/src/services/authAPI.js:7-16, frontend/src/services/taiKhoanAPI.js:3-6
Error Handling
A global response interceptor is configured to handle API errors. It currently passes errors through to be handled by the calling context (e.g., an AuthContext). The taiKhoanAPI service implements more specific error handling, wrapping axios errors in a custom Error object with a message and status code.
Sources: frontend/src/services/authAPI.js:26-30, frontend/src/services/taiKhoanAPI.js:29-34
Backend API Routing
The backend Express server organizes its endpoints into modular route files. The main server.js file mounts these modules under the /api base path.
This diagram shows the API routing structure on the backend.
Sources: backend/src/server.js:81-83
Authentication Service (authAPI.js)
This service handles all user authentication-related API calls. It corresponds to the /api/auth endpoints on the backend.
Sources: frontend/src/services/authAPI.js, backend/src/routes/auth.js
Endpoints
| Function | HTTP Method | Endpoint | Description |
|---|---|---|---|
register | POST | /auth/register | Registers a new user account. |
login | POST | /auth/login | Logs in a user and receives a JWT. |
getProfile | GET | /auth/me | Fetches the profile of the currently logged-in user. |
logout | POST | /auth/logout | Logs out the user. |
forgotPassword | POST | /auth/forgot-password | (Not yet used) Initiates a password reset. |
resetPassword | PUT | /auth/reset-password/:token | (Not yet used) Resets password with a token. |
updatePassword | PUT | /auth/update-password | (Not yet used) Updates the password for a logged-in user. |
Sources: frontend/src/services/authAPI.js:35-45, backend/src/routes/auth.js
Login Flow
The following diagram illustrates the sequence of events during user login. The frontend sends credentials, and the backend validates them, returning a JWT if successful.
Account Management Service (taiKhoanAPI.js)
This service provides functions for managing user accounts, primarily for administrative purposes. It interacts with the /api/taikhoan backend endpoints.
Sources: frontend/src/services/taiKhoanAPI.js, backend/src/controllers/userController.js
Endpoints & Methods
The taiKhoanAPI object exposes several methods for account management.
| Method | HTTP Verb | Endpoint | Description |
|---|---|---|---|
getAll() | GET | /taikhoan | Fetches a list of all user accounts. |
create(data) | POST | /taikhoan | Creates a new user account. |
remove(id) | DELETE | /taikhoan/:id | Deletes a user account by its ID. |
updateStatus(id, newStatus) | PATCH | /taikhoan/:id/status | Updates the status of a user account. |
update(id, payload) | PATCH | /taikhoan/:id | Updates a user's information. |
Sources: frontend/src/services/taiKhoanAPI.js:8-64
Data Transformation
The service transforms the data received from the backend to a format more suitable for the frontend. For example, it maps _id to id and HoTen to name.
// Example from taiKhoanAPI.getAll()
return res.data.map((u) => ({
id: u._id,
name: u.HoTen || u.TenDangNhap, // ƯU TIÊN HoTen, fallback TenDangNhap
email: u.Email,
role: Array.isArray(u.VaiTro) ? u.VaiTro[0] : u.VaiTro,
status: (u.TrangThai || "").toLowerCase(),
}));
Sources: frontend/src/services/taiKhoanAPI.js:10-17
Device Service
This service is responsible for fetching data related to IoT devices. The backend logic for this service is defined in backend/src/routes/thietBi.js.
Sources: backend/src/routes/thietBi.js
Endpoint: Get Devices
The primary endpoint fetches a list of devices and their associated sensor data. It supports pagination, searching, and filtering.
- Endpoint:
GET /api/thietbi - Description: Retrieves a paginated list of devices. It performs a join with the
CamBien(sensor) collection to include related sensor information.
Query Parameters
| Parameter | Type | Description |
|---|---|---|
search | string | Filters devices by name (TenThietBi) using a case-insensitive regex match. |
status | string | Filters devices by the status of their associated sensor (camBien.TrangThai). Defaults to 'all'. |
page | number | The page number for pagination. Defaults to 1. |
limit | number | The number of items per page. Defaults to 10. |
Sources: backend/src/routes/thietBi.js:6-8
Data Aggregation Flow
The backend uses a MongoDB aggregation pipeline to construct the response. The following diagram shows the steps involved in this process.
Sources: backend/src/routes/thietBi.js:11-51