Final Project — University of Greenwich
- Student: Vũ Trần Quang Minh
- Student ID: GCS220006
- Email: [email protected]
- Academic Year: 2024–2025
Deblog Backend is a RESTful API built with Express.js and TypeScript, using MongoDB (Mongoose) as the database. It provides endpoints to manage posts, comments, and reactions. Authentication is performed by delegating token verification to an external Auth Service via AUTH_SERVICE_BASE.
Key capabilities:
- Posts CRUD with author attribution and keyword validation
- Comments CRUD linked to posts
- Reactions (like/dislike) for posts and comments, including toggle and summary
- Standardized JSON responses and a
/healthendpoint
- Node.js 20+, Express 4
- TypeScript 5 +
tscbuild (CommonJS output) - MongoDB + Mongoose 8
- PM2 for process management (production)
- GitHub Actions + SSH for deployment
This project leverages modern web development technologies and tools to build a scalable, maintainable backend API. Key technologies include:
- Runtime Environment: Node.js provides the server-side JavaScript runtime, enabling asynchronous I/O operations and high concurrency.
- Build Tools: TypeScript compiler (
tsc) for type-checking and compilation to CommonJS, ensuring type safety and compatibility. - Process Management: PM2 for production deployment, offering process monitoring, clustering, and automatic restarts.
- CI/CD Pipeline: GitHub Actions for automated testing, building, and deployment via SSH to remote servers.
- API Documentation: Swagger/OpenAPI for interactive API documentation and testing.
- Development Tools: tsx for hot-reloading during development, providing a smooth development experience.
- TypeScript: The primary programming language used throughout the project. TypeScript adds static typing to JavaScript, improving code reliability, maintainability, and developer productivity. It compiles to JavaScript for execution in the Node.js runtime.
The project utilizes several key libraries for various functionalities:
- express: Web framework for Node.js, providing robust routing, middleware support, and HTTP utilities.
- mongoose: ODM (Object Data Modeling) library for MongoDB, simplifying database interactions with schema validation and middleware.
- cors: Middleware for enabling Cross-Origin Resource Sharing, allowing the API to be consumed by web applications from different domains.
- dotenv: Loads environment variables from a
.envfile, keeping sensitive configuration separate from code. - axios: HTTP client for making requests to external services, such as the authentication service.
- swagger-jsdoc and swagger-ui-express: Generate and serve interactive API documentation based on JSDoc comments.
- Express.js: The core web application framework, providing a minimal and flexible Node.js web application framework with a robust set of features for web and mobile applications.
- Mongoose: While primarily a library, it functions as a framework for MongoDB data modeling, providing schema definitions, validation, and query building.
Development and operational tools include:
- TypeScript Compiler (tsc): Compiles TypeScript code to JavaScript, with configuration managed via
tsconfig.json. - tsx: A TypeScript execution environment with hot-reloading for development.
- Jest: Testing framework configured for unit and integration tests (though tests are not yet implemented in this project).
- PM2: Advanced process manager for Node.js applications in production.
- GitHub Actions: CI/CD platform for automating build, test, and deployment workflows.
- SSH Deployment Tools:
appleboy/ssh-actionfor secure deployment to remote servers. - MongoDB Drivers: Built-in MongoDB Node.js driver via Mongoose for database connectivity.
- Database: MongoDB, a NoSQL document database that provides flexibility in data modeling and horizontal scalability.
- ODM: Mongoose serves as the Object Document Mapper, providing schema definitions, data validation, middleware hooks, and query building capabilities.
- Connection Management: Custom database utility (
src/utils/database.ts) handles MongoDB connections with appropriate timeouts and indexing settings. - Data Models: Schemas for Posts, Comments, Reactions, and Users, with indexes optimized for common query patterns (e.g., by author, post, creation time).
- Indexing Strategy: Automatic indexing in development (via Mongoose
autoIndex), with recommendations for manual index management in production for performance.
This is a backend API project focused on providing RESTful endpoints for a blogging platform. As such, it does not include frontend user interface development. The API is designed to be consumed by:
- Web applications (e.g., React, Vue.js, Angular)
- Mobile applications (iOS, Android)
- Other backend services
The API documentation is provided via Swagger UI at /api-docs, which serves as an interactive interface for developers to explore and test the available endpoints. Standardized JSON responses ensure consistent integration across different client applications.
jest.config.js
package.json
tsconfig.json
src/
app.ts
controllers/
comments.controller.ts
posts.controller.ts
reactions.controller.ts
interfaces/
comments.interface.ts
posts.interface.ts
reactions.interfaceterface.ts
middleware/
auth.ts
models/
Comment.ts
Post.ts
Reaction.ts
User.ts
routes/
comments.ts
posts.ts
reactions.ts
services/
comments.service.ts
posts.service.ts
reactions.service.ts
users.service.ts
types/
index.ts
uploads/
utils/
database.ts
response.ts
.github/workflows/main.yaml
- Node.js v20+ (LTS recommended)
- MongoDB connection (local or Atlas)
- Git
Create a .env file at the repository root:
# Server
PORT=4000
# Database
MONGODB_URI=mongodb+srv://<user>:<pass>@<cluster-url>/
MONGODB_DB_BLOG=deblog
# External Auth Service
AUTH_SERVICE_BASE=https://your-auth-service.example.com
Notes:
- The Auth middleware expects requests to include
Authorization: Bearer <token>and the headerX-Fingerprint-Hashed.
Install dependencies:
npm installDevelopment (hot reload via tsx):
npm run devBuild (compile TypeScript with tsc):
npm run buildStart (run compiled CommonJS from dist/):
npm startBase URL: http://<host>:<port>
-
Health
GET /health→{ ok: true }
-
Posts (
/api/posts)GET /get/allGET /get/:idPOST /post— admin only (requires valid auth)PUT /put/:id— author/admin (requires auth)DELETE /delete/:id— author/admin (requires auth)
-
Comments (
/api/comments)GET /get/allGET /get/:postId— comments by postPOST /post— requires authPUT /put/:id— author (requires auth)DELETE /delete/:id— author (requires auth)
-
Reactions (
/api/reactions)GET /get/:postId— summary for a postPOST /post/:postId— create/update like/dislike (requires auth)PUT /put/:postId— toggle like↔dislike (requires auth)DELETE /delete/:reactionId— remove your reaction (requires auth)
Authorization: Bearer <access_token>
X-Fingerprint-Hashed: <sha-256>
Success:
{
"success": true,
"statusCode": 200,
"message": "...",
"data": {}
}Error:
{
"success": false,
"statusCode": 400,
"message": "...",
"error": "..."
}Post:title,content,keywords[],author, timestampsComment:post(ObjectId),content,author, timestampsReaction:postId, optionalcommentId,author,type: 'like'|'dislike', timestampsUser:authId,username,display_name,avatar_ipfs_hash
Basic PM2 commands:
# build and start
npm ci
npm run build
pm2 start dist/app.js --name deblog-backend
pm2 save
# view logs
pm2 logs deblog-backend --lines 100
# restart/stop
pm2 restart deblog-backend
pm2 stop deblog-backendWorkflow: .github/workflows/main.yaml
- Triggers on push to
main. - SSH to target server using repository secrets:
SSH_HOST,SSH_USER,SSH_PRIVATE_KEY
- Actions performed on server:
- Clone/update repo to
/var/www/deblog-backend - Install Node 20 if needed
npm ci→npm run build→npm prune --omit=dev- Start/Restart with
pm2usingdist/app.js
- Clone/update repo to
Ensure server has the required .env file (or export env vars in PM2) before the first deploy.
- "Dynamic require of 'fs' is not supported": occurs when bundling ESM with esbuild but running in CJS. This project compiles with
tscto CommonJS to avoid that. Ensure you rundist/app.js. - "Unauthorized": verify
AuthorizationandX-Fingerprint-Hashedheaders and thatAUTH_SERVICE_BASEis reachable. - MongoDB connection errors: check
MONGODB_URI,MONGODB_DB_BLOG, network ACLs, and SRV DNS.
This repository is part of an academic project. All rights reserved by the author unless explicitly stated otherwise.
- Student: Vũ Trần Quang Minh
- Student ID: GCS220006
- Email: [email protected]