Coder Social home page Coder Social logo

express_mongoose_demo's Introduction

Express Typescript Mongoose Boilerplate

travis Coverage Status PR
A boilerplate/starter project for quickly building RESTful APIs using Node.js, Express, and Mongoose.

The app comes with many built-in features, such as authentication using JWT, request validation, unit and integration tests, etc.

Quick Start

Clone project to create your project, simply run:

git clone https://github.com/MrBrown6210/nodejs-express-mongoose-typescript-boilerplate.git <project-name>

Set the environment variables: (You can see all environment keys at src/config/config)

cp .env.example .env

Start services

docker compose up

Feature

  • NoSQL database: MongoDB object data modeling using Mongoose
  • Authentication and authorization: using passport
  • Logging: using winston and morgan
  • Testing: unit and integration tests using Jest
  • Error handling: centralized error handling mechanism
  • Dependency management: with Yarn
  • Environment variables: using dotenv
  • Security: set security HTTP headers using helmet
  • Compression: gzip compression with compression
  • Git hooks: with husky and lint-staged
  • Linting: with ESLint and Prettier (fixing)
  • Editor config: consistent editor configuration using EditorConfig
  • API Documentation: auto-generate by Swagger

Commands

Running locally (require to setup database):

yarn dev

Running with docker-compose

docker compose up

Down the docker-compose services

docker compose down

building:

yarn build

Running production (require building step):

yarn start

Testing:

# run all unit tests
yarn test

# run all unit tests in watch mode
yarn test:watch

# run unit tests coverage
yarn test:coverage

# run all e2e tests
yarn test:e2e

# run all e2e tests in watch mode
yarn test:e2e:watch

Enviroment Variable

The environment variables can be found and modified in the .env file. They come with these default values:

# Port number
APP_PORT=9000

# Prefix app path
APP_PREFIX_PATH=/

# JWT
# JWT Secret
JWT_SECRET=somerandomkeyherena
# JWT Expire
JWT_EXPIRE=1y


# Database config
DB_SERVER=mongodb://root:example@localhost:27017
DB_NAME=core

Project Structure

This project don't have controllers and services folders because we want to minimalized. If you want them, you can create it

src\
 |--config\         # Environment variables and configuration related things
 |--middlewares\    # Custom express middlewares
 |--models\         # Mongoose models (data layer)
 |--routes\         # Routes
 |--utils\          # Utility classes and functions
 |--app.js          # Express app
 |--index.js        # App entry point

Error handling

The app has a centralized error handling mechanism.

Routes should try to catch the errors and forward them to the error handling middleware (by calling next(e)).

router.post('/login', async (req, res, next) => {
  try {
    const { email, password } = req.body
    const user = await User.findOne({ email })
    if (!user || !user.validPassword(password))
      throw new ApiError(httpStatus.UNPROCESSABLE_ENTITY, 'Invalid email or password')
    res.json(user.toAuthJSON())
  } catch (e) {
    next(e)
  }
})

The error handling middleware sends an error response, which has the following format:

{
  "code": 401,
  "message": "Invalid email or password"
}

When running in development mode, the error response also contains the error stack.

Authentication

To require authentication for certain routes, you can use the authenticate from passportjs

router.post('/', authenticate(['jwt'], { session: false }), async (req, res, next) => {
  try {
    const store = new Store(req.body.store)
    await store.save()
    res.json(store)
  } catch (e) {
    next(e)
  }
})

Logging

Import the logger from src/config/logger.ts. It is using the Winston logging library.

Logging should be done according to the following severity levels (ascending order from most important to least important):

import logger from '@/config/logger'

logger.error('message') // level 0
logger.warn('message') // level 1
logger.info('message') // level 2
logger.http('message') // level 3
logger.verbose('message') // level 4
logger.debug('message') // level 5

In production mode, only info, warn, and error logs will be printed to the console.

Linting

Linting is done using ESLint and Prettier.

In this app, ESLint is configured to follow the Airbnb JavaScript style guide with some modifications. It also extends eslint-config-prettier to turn off all rules that are unnecessary or might conflict with Prettier.

To modify the ESLint configuration, update the .eslintrc.json file. To modify the Prettier configuration, update the .prettierrc.json file.

To prevent a certain file or directory from being linted, add it to .eslintignore and .prettierignore.

To maintain a consistent coding style across different IDEs, the project contains .editorconfig

API Documentation

When running the server, you can visit at /api-docs (only dev environment)

Contributing

Contributions are welcome! Please check out the contributing guide.

Inspirations

License

MIT

express_mongoose_demo's People

Contributors

mrbrown6210 avatar mkmandar123 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.