Skip to content

Decode-Labs-Web3/deblog-backend

Repository files navigation

Deblog Backend (Express + TypeScript)

Final Project — University of Greenwich

  • Student: Vũ Trần Quang Minh
  • Student ID: GCS220006
  • Email: [email protected]
  • Academic Year: 2024–2025

Overview

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 /health endpoint

Tech Stack

  • Node.js 20+, Express 4
  • TypeScript 5 + tsc build (CommonJS output)
  • MongoDB + Mongoose 8
  • PM2 for process management (production)
  • GitHub Actions + SSH for deployment

Technology and Tools

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.

Programming Languages

  • 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.

Library List

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 .env file, 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.

Frameworks List

  • 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.

Tool List

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-action for secure deployment to remote servers.
  • MongoDB Drivers: Built-in MongoDB Node.js driver via Mongoose for database connectivity.

Data Storage and Management

  • 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.

User Interface Development

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.

Project Structure

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

Requirements

  • Node.js v20+ (LTS recommended)
  • MongoDB connection (local or Atlas)
  • Git

Environment Variables

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 header X-Fingerprint-Hashed.

Install & Run

Install dependencies:

npm install

Development (hot reload via tsx):

npm run dev

Build (compile TypeScript with tsc):

npm run build

Start (run compiled CommonJS from dist/):

npm start

API Summary

Base URL: http://<host>:<port>

  • Health

    • GET /health{ ok: true }
  • Posts (/api/posts)

    • GET /get/all
    • GET /get/:id
    • POST /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/all
    • GET /get/:postId — comments by post
    • POST /post — requires auth
    • PUT /put/:id — author (requires auth)
    • DELETE /delete/:id — author (requires auth)
  • Reactions (/api/reactions)

    • GET /get/:postId — summary for a post
    • POST /post/:postId — create/update like/dislike (requires auth)
    • PUT /put/:postId — toggle like↔dislike (requires auth)
    • DELETE /delete/:reactionId — remove your reaction (requires auth)

Auth Headers Required (for protected routes)

Authorization: Bearer <access_token>
X-Fingerprint-Hashed: <sha-256>

Response Format

Success:

{
  "success": true,
  "statusCode": 200,
  "message": "...",
  "data": {}
}

Error:

{
  "success": false,
  "statusCode": 400,
  "message": "...",
  "error": "..."
}

Database Models (brief)

  • Post: title, content, keywords[], author, timestamps
  • Comment: post (ObjectId), content, author, timestamps
  • Reaction: postId, optional commentId, author, type: 'like'|'dislike', timestamps
  • User: authId, username, display_name, avatar_ipfs_hash

Production (PM2)

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-backend

CI/CD (GitHub Actions → SSH Deploy)

Workflow: .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:
    1. Clone/update repo to /var/www/deblog-backend
    2. Install Node 20 if needed
    3. npm cinpm run buildnpm prune --omit=dev
    4. Start/Restart with pm2 using dist/app.js

Ensure server has the required .env file (or export env vars in PM2) before the first deploy.

Troubleshooting

  • "Dynamic require of 'fs' is not supported": occurs when bundling ESM with esbuild but running in CJS. This project compiles with tsc to CommonJS to avoid that. Ensure you run dist/app.js.
  • "Unauthorized": verify Authorization and X-Fingerprint-Hashed headers and that AUTH_SERVICE_BASE is reachable.
  • MongoDB connection errors: check MONGODB_URI, MONGODB_DB_BLOG, network ACLs, and SRV DNS.

License

This repository is part of an academic project. All rights reserved by the author unless explicitly stated otherwise.

Contact

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published