Connecting Frontend to API
Relevant source files
The following files were used as context for generating this wiki page:The LostData project implements a client-server architecture where a single-page frontend application communicates with a backend RESTful API to manage a database of models. The frontend is a static HTML file enhanced with client-side JavaScript, responsible for rendering the user interface and making asynchronous requests to the API.
The backend is built with Node.js and Express, handling business logic, data persistence, and user authentication. It exposes a set of API endpoints for CRUD (Create, Read, Update, Delete) operations on the model data, which is stored in a MongoDB database. This separation of concerns allows the frontend and backend to be developed and maintained independently.
Architecture Overview
The system consists of three main components: a web-based frontend, an Express.js backend server, and a MongoDB database. The frontend (public/index.html) is served statically by the Express server. All dynamic data is fetched from the backend via API calls. The backend (server.js) processes these requests, interacts with the MongoDB database using Mongoose, and returns data in JSON format.
The following diagram illustrates the high-level architecture of the application.
Sources: public/index.html, server.js, APP/models/index.js
Backend API
The backend is a Node.js application using the Express framework to create and manage API endpoints. It handles all data manipulation, authentication, and serves the frontend application.
Sources: server.js, package.json
Server Configuration
The main server file, server.js, configures the Express application. It uses several middleware packages:
cors: Enables Cross-Origin Resource Sharing for all origins (*).express.json&express.urlencoded: Parses incoming JSON and URL-encoded request bodies.express-session: Manages user sessions for authentication.multer: Handles file uploads, specifically for CSV imports.express.static: Serves the static frontend files from thepublicdirectory.
The server connects to a MongoDB database using the connection string defined in APP/config/db.config.js, which pulls the URI from environment variables or defaults to a local instance.
Sources: server.js:2-25, APP/config/db.config.js:2-3
API Endpoints
All API routes are defined directly within server.js, as noted in the placeholder APP/routes/model.routes.js file. The endpoints provide full CRUD functionality for the Model resource, along with authentication and data import/export features.
| Method | Endpoint | Admin Only | Description |
|---|---|---|---|
POST | /api/login | No | Creates a user session based on email. Role is 'admin' if email ends with @admin.com. |
POST | /api/logout | No | Destroys the current user session. |
GET | /api/models | No | Retrieves a list of all models, sorted by name. |
POST | /api/models | Yes | Creates a new model. |
GET | /api/models/:id | No | Retrieves a single model by its ID. |
PUT | /api/models/:id | Yes | Updates an existing model by its ID. |
DELETE | /api/models/:id | Yes | Deletes a model by its ID. |
GET | /api/export/json | Yes | Exports all model data as a JSON file. |
GET | /api/export/csv | Yes | Exports all model data as a CSV file. |
POST | /api/import/csv | Yes | Imports model data from an uploaded CSV file. |
Sources: server.js:27-142, APP/routes/model.routes.js
Authentication & Authorization
Authentication is handled via sessions. A POST request to /api/login with an email creates a session. The user's role (admin or chatter) is determined by the email address format.
Certain routes are protected by the isAdmin middleware, which checks if req.session.user.role is 'admin'. If not, it returns a 403 Forbidden status.
The diagram below shows the login sequence.
Sources: server.js:27-31, server.js:38-41
Frontend Client
The frontend is a single HTML file, public/index.html, which contains the page structure, styling references, and all necessary client-side JavaScript for interactivity.
Sources: public/index.html
API Communication
The client-side JavaScript uses the fetch() API to communicate with the backend. Functions like login(), logout(), and fetchModels() make asynchronous calls to the corresponding API endpoints.
The fetchModels function is called on page load and after login/logout to retrieve and display the list of models.
// public/index.html:84-89
async function fetchModels() {
const res = await fetch('/api/models');
models = await res.json();
models.sort((a, b) => a.name.localeCompare(b.name));
renderModels(models);
}
The following sequence diagram illustrates the process of fetching and rendering models.
Sources: public/index.html:84-95, server.js:49-55
UI Interaction
JavaScript functions handle all user interactions:
login()/logout(): Manage user sessions and update the UI to show/hide admin controls.fetchModels(): Fetches all model data from/api/models.renderModels(): Renders the fetched models into the grid.openModal(): Finds a model by its_idin the locally storedmodelsarray and displays its details in a modal.- Event Listeners: Handle search input, adding new models, and data import/export actions.
Admin-only buttons like "Add Model", "Edit", and "Delete" are hidden by default and are only shown if the user's role, stored in localStorage, is 'admin'.
Sources: public/index.html:64-169
Data Model
The data structure for a "Model" is defined by a Mongoose schema. This schema enforces the data types and validation rules for documents stored in the models collection in MongoDB.
Sources: APP/models/model.model.js, APP/models/index.js
Model Schema
The schema is defined in APP/models/model.model.js. It includes fields for model attributes, pricing, rules, and a history log. Timestamps (createdAt, updatedAt) are automatically added.
The following diagram represents the Model entity.
Sources: APP/models/model.model.js:2-15
Schema Fields
| Field | Type | Required | Description |
|---|---|---|---|
id | String | Yes | A unique identifier for the model. |
name | String | Yes | The name of the model. |
age | Number | No | The age of the model. |
location | String | No | The location of the model. |
profile | String | Yes | A detailed profile description. |
pricing | String | Yes | Pricing information. |
dosAndDonts | String | Yes | A list of allowed and disallowed activities. |
extraTabs | Array | No | An array for additional information tabs. Defaults to []. |
history | Array | No | An array to log changes to the document. Defaults to []. |
Sources: APP/models/model.model.js:4-13, seed.js:4-75
A pre-save hook is used to automatically update the history array whenever a document is modified, tracking the timestamp, action, and modified fields.
Sources: APP/models/model.model.js:17-26