Skip to content

goodsmith/ts-express-mongo

Repository files navigation

Brief Explanation

This project sets up a TypeScript-based REST API using Express, with MongoDB as the primary database accessed via official drivers.

It enforces robust validation and documentation by leveraging Zod for schema validation and auto-generating OpenAPI docs, while ensuring maintainability through ESLint, Prettier, and path aliases.

The structure follows the Controller–Service–Repository pattern, where controllers handle requests, services manage business logic, and repositories encapsulate database access, making the system cleanly layered and scalable.

Requirements

  • Create a GET endpoint at /users/:id
    • Endpoint created, along with an endpoint to create a user
  • Bonus: Gracefully handle invalid ObjectId errors
    • Middleware for zod schema validation created, example of a response for a incorrect request:
    {
      "message": "Validation failed. Following errors were encountered:\n{\n  \"params\": \"✖ Too small: expected string to have >=24 characters\\n  → at id\\n✖ Invalid ObjectId\\n  → at id\"\n}"
    }```
  • Unique twist: Only return users where the age is greater than 21
    • API will only allow users over 21 to be created, and mongoose will only create user records over 21

Detailed Explanation

Features

  • Express 5 for building REST APIs
  • TypeScript for type safety
  • MongoDB as the database, accessed via official drivers
  • Zod for schema validation
  • OpenAPI docs auto-generated from Zod schemas
  • ESLint and Prettier for code quality and formatting
  • Path aliases (@/*) for cleaner imports
  • Nodemon + ts-node for live-reloading during development
  • Environment variable management with dotenv and dotenv-expand

MongoDB

  • MongoDB is used as the primary database.
  • The project connects to MongoDB using the official Node.js driver.
  • You can run a local MongoDB instance using Docker Compose (see below).

Folder Structure

src/
  app.ts                # Entry point
  lib/                  # App and router setup
  config/               # Environment, OpenAPI, Zod config
  controllers/          # Route controllers
  middlewares/          # Express middlewares
  models/               # Data models
  repositories/         # Data access logic
  routes/               # Route definitions
  services/             # Business logic

Scripts

  • pnpm dev — Start development server with live reload (nodemon + ts-node + path aliases)
  • pnpm build — Compile TypeScript to JavaScript in dist/
  • pnpm start — Run compiled server from dist/
  • pnpm lint — Run ESLint

TypeScript Setup

  • Uses tsconfig.json for main config and tsconfig.build.json for builds.
  • Path aliases (@/*) are enabled via "paths" in tsconfig.json.
  • For runtime support of aliases, tsconfig-paths is used in the dev script.

ESLint & Prettier

  • ESLint is configured for TypeScript and includes stylistic and import sorting rules.
  • Prettier can be used for formatting (see .prettierrc).
  • Trailing spaces and unused imports are checked.

API Docs

  • Zod schemas are used to generate OpenAPI docs.
  • Docs are served at /docs via swagger-ui-express.

Environment Variables

  • Managed via .env files and validated with Zod.
  • Before running the project, make sure to fill out the .env file with the required environment variables (e.g., MONGODB_URI, PORT, etc.).

How to Run

Development

  1. Install dependencies:
    pnpm install

  2. Start MongoDB using Docker Compose:
    docker compose up -d

  3. Fill out the .env file:
    Edit .env and provide all required values.

  4. Start development server:
    pnpm dev

Production

  1. Install dependencies:
    pnpm install

  2. (Optional) Start MongoDB using Docker Compose:
    docker compose up -d Alternatively, you can connect to an existing MongoDB instance by updating the MONGODB_URI in your .env file.

  3. Ensure required environment variables are set

  4. Build for production:
    pnpm build

  5. Run production build:
    pnpm start

Notes

  • Use @/* for importing from src/ (e.g., import { registry } from '@/config/openapi').
  • For new routes, add controllers and route definitions in src/routes/.
  • API documentation is auto-generated and available

About

This project sets up a TypeScript-based REST API using Express, with MongoDB as the primary database accessed via official drivers.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors