Skip to content

About

A shipment tracking web app. This is done for the course Capstone 2.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

161 Commits

Folders and files

Repository files navigation

ShipmentTracking

This is a repository for a course called Capstone 2. In this project we are creating a shipment tracking web application. The idea is that you will be able to follow your shipments in real time through this application.

Installation and setup

Before continuing you need

  • PostgreSQL
  • npm
  • node.js

Backend

After cloning the repository to your local device you must run the following command in the backend folder of the project.

npm install

This will download all the needed modules to run the backend API. After this you must run the following command.

npm run db:create

This command runs a script that will create the database, which the API uses. The script also will create a .env file, which you need. The .env file is a private file that contains enviromental variables that the API uses, it contains secret information and you should not share with anyone. The .env file will look similar to this.

PORT=3001
DB_HOST=localhost
DB_PORT=5432
DB_NAME=shipmenttracking
DB_USER=postgres
DB_PASSWORD=YourPassword
JWT_SECRET=GeneratedSecret

You need to swap the DB_PASSWORD to your postgre password. If you do not have the .env file before running the install command the auto generate .env file will have a pre generated JWT_SECRET. If you created the .env file yourself you must generate your own secret. To run the backend API use the following command in the backend folder.

npm run dev

This will run the API in the development environment. This will also start up the MQTT listener service.

To run the API in production mode use

npm start

The API contains a health endpoint, which means that you can check the availability of the API by calling the health endpoint. This endpoint is located at /api/health/ready. You can use this to check that your backend is able to receive requests and is connected to the database.

Frontend

After cloning the repository to your local device and setting up the backend you must run the same install command again in the frontend folder of the project.

npm install

This will download all the needed modules to run the frontend. To start the frontend you must run the same run command in the frontend as you did in the backend.

npm run dev

The terminal will display where the frontend started running and you can open the link to start using the web app.

Frontend

Tech Stack

  • React.js 19 — UI framework
  • React compiler — build-time optimization tool
  • Vite — Build tool and dev server
  • Leaflet — library for building maps (picking destination location)
  • TypeScript

Backend

Tech Stack

Runtime and Web framework

  • Node.js — Javascript run time environment
  • Express.js — Node.js web application framework

Authentication / Security

  • jsonwebtoken.js — Module to implement JSON web tokens
  • bcrypt — Password hashing function
  • express-rate-limit — Basic limiter middleware for express.js

Database / Query Builder

  • PostgreSQL — Object-relational database management system
  • knex.js — SQL query builder

MQTT service

  • mqtt.js — MQTT client library

Testing

  • vitest — Testing framework
  • supertest — Node.js API testing library

Misc

  • dotenv — Loads enviromental variables
  • cross-env — Allows using environmental variables across multiple OSs
  • nodemon — Development tool for restarting application upon a code change
  • cookie-parser — Cookie parser library
  • yaml — support for reading YAML files
  • swagger-ui-express — Swagger ui for openapi documentation with express
  • zod — API endpoint validation middleware

Available API endpoints

Method Endpoint Description
GET /api/auth/me Retrieves current users info
POST /api/auth/register Registers a new user
POST /api/auth/login Logs in a user
POST /api/auth/refresh Refreshes the user's access token with a refresh token
POST /api/auth/logout Removes the user's refresh token, used when logging out
PATCH /api/auth/settings Updates the user's information and settings
PATCH /api/auth/settings/change-password Allows the user to change their password
DELETE /api/auth/settings/delete-account Deletes the account of the current user
GET /api/shipments/ Retrieves all shipments for the current user
GET /api/shipments/status/:status Retrieves all shipments for the current user by status
GET /api/shipments/shipment/:id Retrieves a specific status
POST /api/shipments/add-shipment Adds a shipment for the current user
PATCH /api/shipments/shipment/:id Updates a specific shipment's info
PATCH /api/shipments/shipment/status/:id Updates a specific shipment's status
DELETE /api/shipments/shipment/:id Deletes a specific shipment
GET /api/destinations/ Retrieves all destinations for the current user
GET /api/destinations/destination/:id Retrieves a specific destination
POST /api/destinations/add-destination Adds a destination for the current user
PATCH /api/destinations/destination/:id Updates a destination
DELETE /api/destinations/destination/:id Deletes a destination
GET /api/ships/ Retrieves all ships for the current user
GET /api/ships/:id Retrieves information of one ship
POST /api/ships/add-ship Adds a ship to the follow list of the user and adds the ship if it does not exist
DELETE /api/ships/unfollow/:id Deletes the link between the user and the chosen ship
GET /api/health/live From here you can check that the api can recieve requests
GET /api/health/ready From here you can check that the database is working
GET /api/docs Contains the swagger openapi documentation

Backend project structure

The backend API project follows a Controller-Service-Model pattern. Below you can see the whole project structure for the backend side of the application.

backend/
├── app.js                                          # Backend main entry point
├── index.js                                        # Boots up the server and loads app.js
├── knexfile.js                                     # Contains configurations for knex
├── package.json
├── vitset.config.js                                # Configuration file for vitest
├── .env                                            # Secret environmental variable file
├── controllers/                                    # Controllers expose endpoints for clients to call
│   ├── destinationsController.js
│   ├── healthController.js
│   ├── shipmentsController.js
│   ├── shipsController.js
│   ├── usersController.js
│   └── README.md
├── db/
│   ├── migrations/                                 # Migrations setup the database structure and apply changes to it
│   │   └── ...
│   ├── seeds/                                      # Seeds populate the database with predefined data
│   │   └── demo.js                                 # A seed to populate database with presentation ready data
│   └── db.js                                       # Contains the primary database instance used in the models
├── docs/                                           # Swagger documentation related files
│   ├── openapi.yaml                                # Yaml file that contains the openapi style documentation
│   └── swagger.js                                  # Contains the docs router with the code that reads the doc spec
├── models/                                         # Models interact with the database
│   ├── destination.js
│   ├── refreshToken.js
│   ├── ship.js
│   ├── shipment.js
│   ├── user_ships.js
│   ├── user.js
│   └── README.md
├── mqtt/
│   ├── mqtt.client.js                              # Creates the MQTT client
│   ├── mqtt.index.js                               # Starts the MQTT worker
│   ├── mqtt.messageHandler.js                      # Handles recieved MQTT messages
│   └── mqtt.subscriptionManager.js                 # Handles MQTT topic subscription
├── scripts/
│   ├── createDatabase.js                           # Creates the database during project setup if it does not exist
│   └── createTestDatabase.js                       # Creates two temporary test databases when running tests
├── services/                                       # Services are used to house business logic
│   ├── destinationService.js
│   ├── refreshTokenService.js
│   ├── shipmentService.js
│   ├── shipService.js
│   ├── userService.js
│   └── README.md
├── tests/
│   ├── helpers/
│   │   └── authHelper.js                           # A helper used in integration tests to avoid authentication issues
│   ├── integration/                                # A folder containing all integration tests
│   │   ├── destinationsIntegrations.test.js
│   │   ├── shipmentsIntegration.test.js
│   │   ├── shipsIntegration.test.js
│   │   └── usersIntegrations.test.js
│   ├── setup/
│   │   ├── env.js                                  # Overwrites .env variables with values needed in testing
│   │   ├── globalSetup.integration.js              # Glonal setup for integration tests
│   │   └── globalSetup.unit.js                     # Global setup for unit tests
│   ├── unit/                                       # A folder containing all unit tests by type
│   │   ├── controllers/                            # Controller unit tests
│   │   │   ├── destinationsControllerUnit.test.js
│   │   │   ├── healthControllerUnit.test.js
│   │   │   ├── shipmentsControllerUnit.test.js
│   │   │   ├── shipsControllerUnit.test.js
│   │   │   └── usersControllerUnit.test.js
│   │   ├── models/                                 # Model unit tests
│   │   │   ├── destinationUnit.test.js
│   │   │   ├── refreshTokenUnit.test.js
│   │   │   ├── shipmentUnit.test.js
│   │   │   ├── shipUnit.test.js
│   │   │   ├── user_shipUnit.test.js
│   │   │   └── usersUnit.test.js
│   │   └── services/                               # Service unit tests
│   │       ├── destinationServiceUnit.test.js
│   │       ├── refreshTokenServiceUnit.test.js
│   │       ├── shipmentsServiceUnit.test.js
│   │       ├── shipServiceUnit.test.js
│   │       └── userServiceUnit.test.js
│   └── README.md
├── utils/                                          # Misc utilities
│   ├── ApiError.js                                 # Defined API error
│   ├── auth.js                                     # Authentication middleware
│   ├── config.js                                   # Configuration file
│   ├── logger.js                                   # Logger middleware
│   ├── LoginLimiter.js                             # Login limiter middleware
│   ├── middleware.js                               # Contains error handler
│   ├── tokens.js                                   # Token related methods
│   └── validate.js                                 # Zod validation middleware
└── README.md

Backend testing instructions and details

The backend API has a comprehensive automated testing environment built with the Vitest testing framework. The backend testing suites cover all of the different important backend components. Tested areas are: controllers, services and models.

Important commands to know:

npm run test                # Runs all integration and unit test suites

npm run test:unit           # Runs all unit test suites

npm run test:integration    # Runs all integration test suites

Integration tests test a whole part of the system by calling an endpoint and checking that it returns the correct values. Unit tests on the other hand test specific parts of the code, such as specific controller, service or model actions. Most of the unit tests mock the services or models they need to use to isolate the tested part. Model unit tests use the temporary unit test database.

Backend seeds

The backend contains seed file that allows you to populate the database with predefined values. The seed file is called demo.js and can be found under the seeds folder in the db folder. In the development environment you can run the file with the following command.

DEMO_PASSWORD='TestPass' npx knex seed:run --specific=demo.js

Replace the "TestPass" with your own password if you wish. It will give the given password to the created demo account. In the production environment there is an extra check that the user actually wants to run the specific seed. To confirm that you want to run it in the production environment you will need to specify ALLOW_DEMO_SEED=true in your .env file.

Backend CI pipeline

For this project we have made a simple backend CI pipeline that is used for testing. When backend code is pushed to the repository the CI pipeline runs all of the unit and integration test suites against the uploaded version of the codebase. Changes made to the frontend side of the project do not trigger the CI pipeline. The pipeline was created using Github Actions. The pipeline makes sure that the uploaded code actually works in the intended manner.

Backend swagger openapi documentation

The API contains swagger style openapi documentation. The documentation contains detailed information about the endpoints that the API exposes. From the documentation you are able to try to use the endpoints and make requests to the endpoint to see how they respond. You can access the swagger openapi documentation by running the API in development mode and going to the following address: http://localhost:3001/api/docs. To use the authentication required endpoints you will have to login first and set the received token in the authentication scheme. To access them you will have to click the lock icon in the UI.


About

A shipment tracking web app. This is done for the course Capstone 2.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages