Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

mongo-modular-sample

A simple modular RESTful microservice built with Express, MongoDB, and the core-ts ecosystem.

This project demonstrates how to build clean, lightweight, and maintainable microservices without relying on heavy frameworks or decorators. It follows a layered architecture with clear separation between controllers, use cases, repositories, and models.

Unlike the more opinionated samples, this project keeps the request-processing flow explicit, making it an excellent starting point for learning how the Core TS libraries work together.


Features

  • Modular project structure
  • RESTful CRUD APIs
  • Configuration management
  • Structured logging
  • Health check endpoint
  • Localization support
  • Request validation
  • Generic CRUD services
  • Generic MongoDB repository
  • MongoDB support
  • Express 5 compatible

Available Scripts

npm start

Runs the app in the development mode.

npm run build

Builds the app for production to the dist folder.

npm run prod

Runs the app for production in the dist folder.

Build the Docker Image

docker build -t sql-simple-modular-sample .

Test the Docker Image

docker run -p 8080:8080 sql-simple-modular-sample

Deploy to Cloud Run

gcloud run deploy mongo-simple-service \
--image us-central1-docker.pkg.dev/<your-project-id>/node-repo/mongo-simple-modular-sample \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--port 8080 \

Architecture

Architecture

Business logic is independent of the MongoDB driver. Repositories depend on the generic DB abstraction provided by sql-core.

   HTTP Request
         │
         ▼
 Express Controller
         │
         ▼
   Service Layer
         │
         ▼
  Repository Layer
         │
         ▼
    mongodb-kit
         │
         ▼
      MongoDB

Technology Stack

  • TypeScript
  • Node.js
  • Express 5
  • MongoDB

Core TS libraries:


Project Structure

.
├── AGENTS.md                  # Instructions for AI coding agents
├── README.md                  # Human-facing project overview
├── docs/
│   ├── API.md                 # Implemented HTTP endpoints and observed behavior
│   ├── ARCHITECTURE.md        # Startup, dependency flow, and feature structure
│   ├── CODING_CONVENTIONS.md  # Naming, file layout, and implementation patterns
│   ├── DATABASE.md            # Actual MongoDB usage and supplied PostgreSQL schema
│   └── DEVELOPMENT.md        # Setup, scripts, configuration, and known caveats
└── src/
    ├── app.ts        # Application bootstrap
    ├── config.ts     # Application configuration
    ├── context.ts    # Dependency composition
    ├── route.ts      # Route registration
    ├── resources/    # Localization resources
    └── user/
        ├── user.ts
        ├── repository.ts
        ├── service.ts
        ├── controller.ts
        └── index.ts

Each business feature is organized into its own module, making the project easy to extend and maintain.


Layered Architecture

Controller

Controllers are responsible for:

  • Receiving HTTP requests
  • Parsing request parameters
  • Validating input
  • Calling business services
  • Returning HTTP responses

Business logic remains inside the use case layer.


Service

The service layer contains application business logic.

Most CRUD functionality is inherited from reusable generic implementations provided by onecore, allowing services to stay small and focused.

export class UserUseCase
    extends UseCase<User, string, UserFilter> implements UserService

Repository

Responsible for database access.

export class MongoUserRepository extends Repository<User, string, UserFilter> implements UserRepository {
  constructor(db: Db) {
    super(db, "users", userModel)
  }
}

Each repository extends reusable Repository implementations provided by mongodb-kit, requiring only:

  • Mongo Database
  • Collection name
  • Entity model

Everything else is inherited from mongodb-kit.

Custom queries can easily be added when needed.

This greatly reduces boilerplate while keeping the repository extensible for custom queries.


Model

Models define:

  • Entity structure
  • Validation rules
  • Metadata

Validation rules are centralized using validation-core, keeping controllers concise and consistent.


Dependency Composition

Dependencies are wired explicitly rather than using a dependency injection framework.

 MongoDB
    │
    ▼
Repository
    │
    ▼
 Service
    │
    ▼
Controller

All dependencies are created in context.ts, serving as the application's composition root.


Request Processing Flow

Unlike more abstract samples, this project keeps the HTTP flow explicit.

HTTP Request
      │
      ▼
 Controller
      │
      ▼
Parse Request
      │
      ▼
Validate Model
      │
      ▼
   Service
      │
      ▼
  Repository
      │
      ▼
   MongoDB
      │
      ▼
HTTP Response

This makes the project particularly useful for developers learning the Core TS ecosystem.


Localization

Validation and application messages support multiple languages.

const resource = getResource(req)

The project supports:

  • English
  • Vietnamese

Localization resources are located under:

src/resources/

Validation messages automatically use the selected language.

This is a nice feature that many samples omit.

New languages can be added without changing business logic.


Validation

Validation is handled by validation-core, with rules defined in the model.

const resource = getResource(req)

const errors = validate<User>(user, userModel, resource)

Validation rules are defined alongside the entity model rather than inside controllers.

Examples include:

  • Required fields
  • Email validation
  • Length constraints
  • Pattern validation
  • Primary key validation

Type validation is also integrated into routing through:

const checkUser = check(userModel)

and reinforced in controller methods. This shows both middleware-based and controller-level validation approaches.


Logging

The application uses MiddlewareLogger from middleware-logging together with logger-core for structured request logging. This provides a consistent logging strategy across the application.

The sample uses structured request logging through middleware-logging.

Middleware logging is configurable:

  • HTTP method
  • Request URL
  • Request
  • Response
  • Status code
  • Response size
  • Execution time

It also propagates:

  • Request ID
  • Correlation ID

which is useful in distributed systems.

Sensitive request and response data can be masked before logging.


Health Check

The sample includes a health endpoint suitable for containerized deployments.

The endpoint checks:

  • MongoDB connectivity

They can easily be extended to include additional infrastructure services.

Example response

{
  "status": "UP",
  "details": {
    "mongodb": {
      "status": "UP"
    }
  }
}

Configuration

Configuration is managed using config-plus, merging:

          Default Configuration
                   │
                   ▼
Environment Configuration (SIT, UAT, PRD)
                   │
                   ▼
   Environment Variables (process.env)
                   │
                   ▼
          Final Configuration

Typical configuration includes:

  • HTTP server
  • MongoDB connection
  • Logging
  • Localization
  • Application settings

Environment variables can override default values for different deployment environments.


Adding a New Module

Each business module follows the same structure.

customer/
    controller.ts
    service.ts
    repository.ts
    customer.ts
    index.ts

To add a new module:

  1. Define the entity model.
  2. Create the repository.
  3. Create the use case.
  4. Create the controller.
  5. Register routes.
  6. Add the controller to the application context.

This consistent approach keeps the application modular and easy to maintain.


Why This Sample?

This project is designed to be the simplest SQL sample in the Core TS ecosystem.

It demonstrates:

  • Explicit request processing
  • Layered architecture
  • Structured logging
  • Request validation
  • Reusable CRUD services
  • Generic repositories
  • MongoDB integration

without introducing unnecessary complexity.

It is an excellent starting point for developers who want to understand how the ecosystem works before adopting more advanced abstractions.


Ecosystem Integration

This sample demonstrates how several core-ts libraries work together.

Library Purpose
express-web-kit Express utilities and REST helpers
middleware-logging HTTP request and response logging
validation-core High-performance validation library
onecore Generic CRUD use cases and common abstractions
mongodb-kit Generic MongoDB repositories
logger-core Structured logging
config-plus Configuration management

Each library focuses on a single responsibility.

That demonstrates the intended layering very well.


Related Samples

These samples share the same architecture, allowing developers to switch databases while keeping the application structure consistent.


Design Goals

  • Simple
  • Lightweight
  • Modular
  • Database-independent
  • Enterprise-friendly
  • Production-ready
  • Explicit
  • Testable

Strengths

The project stands out for several reasons:

  • Very explicit flow from HTTP request to database.
  • Clear layered architecture with well-defined responsibilities.
  • Minimal boilerplate thanks to generic repositories and use cases.
  • Database abstraction through mongodb-kit.
  • Good observability with structured logging and health checks.
  • Simple dependency composition without a DI container.

API Design

health check

To check if the service is available

Request: GET /health

Response:

{
  "status": "UP",
  "details": {
    "mongodb": {
      "status": "UP"
    }
  }
}

Search users: Support both GET and POST

POST /users/search

Request: POST /users/search

In the below sample, search users with these criteria:

  • get users of page "1", with page size "20"
  • email="tony": get users with email starting with "tony"
  • dateOfBirth between "min" and "max" (between 1953-11-16 and 1976-11-16)
  • sort by phone ascending, id descending
{
  "page": 1,
  "limit": 20,
  "sort": "phone,-id",
  "email": "tony",
  "dateOfBirth": {
    "min": "1953-11-16T00:00:00+07:00",
    "max": "1976-11-16T00:00:00+07:00"
  }
}
GET /users/search?page=1&limit=2&email=tony&dateOfBirth.min=1953-11-16T00:00:00+07:00&dateOfBirth.max=1976-11-16T00:00:00+07:00&sort=phone,-id

In this sample, search users with these criteria:

  • get users of page "1", with page size "20"
  • email="tony": get users with email starting with "tony"
  • dateOfBirth between "min" and "max" (between 1953-11-16 and 1976-11-16)
  • sort by phone ascending, id descending

Response:

  • total: total of users, which is used to calculate numbers of pages at client
  • list: list of users
{
  "list": [
    {
      "id": "ironman",
      "username": "tony.stark",
      "email": "tony.stark@gmail.com",
      "phone": "0987654321",
      "dateOfBirth": "1963-03-24T17:00:00Z"
    }
  ],
  "total": 1
}

Get all users

Request: GET /users

Response:

[
  {
    "id": "spiderman",
    "username": "peter.parker",
    "email": "peter.parker@gmail.com",
    "phone": "0987654321",
    "dateOfBirth": "1962-08-25T16:59:59.999Z"
  },
  {
    "id": "wolverine",
    "username": "james.howlett",
    "email": "james.howlett@gmail.com",
    "phone": "0987654321",
    "dateOfBirth": "1974-11-16T16:59:59.999Z"
  }
]

Get one user by id

Request: GET /users/:id

GET /users/wolverine

Response:

{
  "id": "wolverine",
  "username": "james.howlett",
  "email": "james.howlett@gmail.com",
  "phone": "0987654321",
  "dateOfBirth": "1974-11-16T16:59:59.999Z"
}

Create a new user

Request: POST /users

{
  "id": "wolverine",
  "username": "james.howlett",
  "email": "james.howlett@gmail.com",
  "phone": "0987654321",
  "dateOfBirth": "1974-11-16T16:59:59.999Z"
}

Response:

  • status: configurable; 1: success, 0: duplicate key, 4: error
{
  "status": 1,
  "value": {
    "id": "wolverine",
    "username": "james.howlett",
    "email": "james.howlett@gmail.com",
    "phone": "0987654321",
    "dateOfBirth": "1974-11-16T00:00:00+07:00"
  }
}

Fail case sample:

  • Request:
{
  "id": "wolverine",
  "username": "james.howlett",
  "email": "james.howlett",
  "phone": "0987654321a",
  "dateOfBirth": "1974-11-16T16:59:59.999Z"
}
  • Response: in this below sample, email and phone are not valid
{
  "status": 4,
  "errors": [
    {
      "field": "email",
      "code": "email"
    },
    {
      "field": "phone",
      "code": "phone"
    }
  ]
}

Update one user by id

Request: PUT /users/:id

PUT /users/wolverine
{
  "username": "james.howlett",
  "email": "james.howlett@gmail.com",
  "phone": "0987654321",
  "dateOfBirth": "1974-11-16T16:59:59.999Z"
}

Response:

  • status: configurable; 1: success, 0: duplicate key, 2: version error, 4: error
{
  "status": 1,
  "value": {
    "id": "wolverine",
    "username": "james.howlett",
    "email": "james.howlett@gmail.com",
    "phone": "0987654321",
    "dateOfBirth": "1974-11-16T00:00:00+07:00"
  }
}

Patch one user by id

Perform a partial update of user. For example, if you want to update 2 fields: email and phone, you can send the request body of below.

Request: PATCH /users/:id

PATCH /users/wolverine
{
  "email": "james.howlett@gmail.com",
  "phone": "0987654321"
}

Response:

  • status: configurable; 1: success, 0: duplicate key, 2: version error, 4: error
{
  "status": 1,
  "value": {
    "email": "james.howlett@gmail.com",
    "phone": "0987654321"
  }
}

Delete a new user by id

Request: DELETE /users/:id

DELETE /users/wolverine

Response: 1: success, 0: not found, -1: error

1

How to build and run

npm start

Runs the app in the development mode.

npm run build

Builds the app for production to the dist folder.

npm run prod

Runs the app for production in the dist folder.


License

MIT

Mongo Simple Modular Sample

A small TypeScript application demonstrating a modular Express API with a MongoDB-backed user feature. It uses a controller / use-case / repository separation and shared libraries from the core-ts ecosystem.

Database clarification: The checked-in source currently uses MongoDB (mongodb and mongodb-kit). The PostgreSQL DDL supplied alongside this project is documented in docs/DATABASE.md, but it is not implemented by the current application. Do not assume that the SQL tables are available through the current repository layer.

What is implemented

  • Express application startup and middleware setup.
  • MongoDB connection and health check.
  • Request/correlation ID propagation into the logging context.
  • Request/response masking for top-level phone and email fields in the logging middleware hooks.
  • Runtime log and middleware configuration endpoints.
  • English and Vietnamese validation resources.
  • User search, load, create, update, patch, and delete endpoints.

Only the user feature has an application module in the supplied source. Company ratings, jobs, articles, follows, saved items, and the other SQL domains are present only in the supplied database design; no corresponding TypeScript feature modules were found.

Technology

  • TypeScript 6, strict mode
  • Node.js and Express 5
  • MongoDB Node.js driver 7 and mongodb-kit
  • onecore for generic use-case and model types
  • validation-core for model validation
  • express-web-kit and middleware-logging for HTTP helpers and middleware
  • Webpack for production bundling

Versions above reflect the supplied package.json / lockfile, not a compatibility guarantee for other environments.

Project layout

.
├── AGENTS.md                  # Instructions for AI coding agents
├── README.md                  # Human-facing project overview
├── docs/
│   ├── API.md                 # Implemented HTTP endpoints and observed behavior
│   ├── ARCHITECTURE.md        # Startup, dependency flow, and feature structure
│   ├── CODING_CONVENTIONS.md  # Naming, file layout, and implementation patterns
│   ├── DATABASE.md            # Actual MongoDB usage and supplied PostgreSQL schema
│   └── DEVELOPMENT.md        # Setup, scripts, configuration, and known caveats
└── src/
    ├── app.ts        # Application bootstrap
    ├── config.ts     # Application configuration
    ├── context.ts    # Dependency composition
    ├── route.ts      # Route registration
    ├── resources/    # Localization resources
    └── user/
        ├── user.ts
        ├── repository.ts
        ├── service.ts
        ├── controller.ts
        └── index.ts

Run locally

Requirements

  • A Node.js runtime compatible with the dependencies in package-lock.json.
  • Access to a MongoDB instance.

Configure environment

Create a local .env file in the project root. Do not commit credentials.

MONGO_URI=mongodb://localhost:27017
MONGO_DB=masterdata
ENV=sit

MONGO_URI and MONGO_DB are read through the environment merge in src/app.ts. ENV is used to select a profile from the env object in src/config.ts; the source currently defines sit and prd profiles. Review config-plus merge semantics before changing profile precedence.

The checked-in src/config.ts also contains a hard-coded MongoDB connection fallback. Replace that value with an environment-only configuration before using the project outside a disposable/demo environment. Never copy credentials from the source or .env into documentation, logs, examples, or commits.

Install and start

npm ci
npm run dev

The application connects to MongoDB before registering routes and starting the HTTP listener. The default configured port is 8080.

Build and run the bundled app

npm run build
npm run prod

Webpack targets Node.js and writes dist/app.js. The prod script starts dist/app after the build.

Available scripts

Script Command Purpose
start nodemon --exec ts-node-dev src/app Development-style startup
dev nodemon --exec ts-node-dev src/app Development startup with restart support
build webpack --config webpack.config.js Bundle the server application
prod node dist/app Run the built application
test placeholder command No test suite is configured in the supplied project

Implemented HTTP endpoints

Method Path Purpose
GET /health Health check, including MongoDB checker
PATCH /log Configure logging through LogController
PATCH /middleware Configure request middleware logging
GET, POST /users/search Search users
GET /users/:id Load one user
POST /users Create a user
PUT /users/:id Replace/update a user
PATCH /users/:id Partially update a user
DELETE /users/:id Delete a user

See docs/API.md for the behavior visible in the controllers, including status-code choices.

How a feature is structured

The existing user feature is the reference implementation:

  1. user.ts declares domain interfaces, repository/service contracts, and the validation model.
  2. repository.ts adapts MongoDB through mongodb-kit.
  3. service.ts extends the generic UseCase from onecore.
  4. controller.ts handles Express requests, validation, status codes, and errors.
  5. index.ts constructs and exports the feature controller.
  6. context.ts adds the controller to ApplicationContext.
  7. route.ts maps HTTP methods and paths to controller methods.

Read AGENTS.md before asking an AI agent to change or extend the project. The detailed patterns are in docs/ARCHITECTURE.md and docs/CODING_CONVENTIONS.md.

Database design supplied with this project

The supplied SQL describes a PostgreSQL-oriented product domain covering users, profiles, follows, skills/interests, categories/content, jobs, articles, saved items, and company/article ratings. It is catalogued in docs/DATABASE.md.

That design and the current implementation are not interchangeable:

  • Runtime connection: MongoDB.
  • Implemented persistence adapter: MongoUserRepository for the users collection.
  • Supplied relational design: PostgreSQL DDL / seed statements, not connected to the current code.
  • The current User TypeScript interface is much smaller than the SQL users table.

Before implementing a feature against the supplied SQL tables, decide explicitly whether the application is being migrated to PostgreSQL or whether the schema is reference/domain documentation while MongoDB remains the target. Do not silently mix the two approaches.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages