kerwanp / express-starter

A simple application to begin an Express & Typescript project

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Express Starter

CI Badge


A simple application to begin an Express & Typescript project

Setup

$ git clone git@github.com:kerwanp/express-boilerplate.git && cd express-boilerplate
$ npm install
$ npm run serve

Features

Winston

Winston is a powerful logger for Javascript.

More informations https://github.com/winstonjs/winston

Usage:

app.logger.info(`Your message`)

Express Winston

Express Winston provide a configurable Express middleware to log every requests. You can find the configuration in the src/middlewares/logger.middleware.ts file.

More information: https://www.npmjs.com/package/express-winston

Express Async Handler

Express does not handle Promise errors catching. You can use express-async-handler to handle errors sent from promise when using async/await.

Usage:

import expressAsyncHandler = require("express-async-handler");

authRouter.get('/token', expressAsyncHandler(async (req, res) => {
    await req.services.authService.authenticate();
    res.send('Hello world')
}));

More information: https://www.npmjs.com/package/express-async-handler

Dotenv

You can manage the configuration of your application by adding or editing the src/.env file. Then, simply use them as environment variables process.env.DB_HOST.

File structure

Routers

Every routes are stored under the directory src/routers with the name *.router.ts. This file should export the router which is used by the server in src/routers/routers.ts.

Example:

// src/routers/users.router.ts
export const userRouter = express.Router();
userRouter.get('/hello', (req, res) => {
    res.send('Hello world')
});
// src/routers/routers.Ts
export function loadRouters(server) {
    server.use('/users', userRouter)
}

We have now the route GET /users/hello

Middleware

You can add your Middleware in the folder src/middleware with the name *.middleware.ts. Next, use it in the file src/middleware/middleware.ts.

Example:

// src/middleware/hello.middleware.ts
export function helloMiddleware(req, res, next) {
    console.log('HELLO WORLD !');
    next()
}
// src/middleware/hello.middleware.ts
export function loadPostMiddleware(server: express.Express) {
    server.use(helloMiddleware)
}

This will console 'HELLO WORLD' after using the routers.

Services

Services are stored in the folder src/services with the name *.service.ts. They must be named NameService and they are stored in the request req.services.name There is two types of services :

Request services

Every request, a new instance is created. You can store data and use the Request and the Response inside of it.

Example:

// src/services/auth.service.ts
export class AuthService {
  private token;
  constructor(request: Request, response: Response) {
    // As there is one instance by Request
    // you can store data and use the request (& response)
    // in your service.
    this.token = request.headers['X-Authorization']
  }
  
  async authenticate() { }
}
// src/services/services.ts
export const services = [
  AuthService
]

By default, a service is a request service

Response Services

Sometime, you will need services which needs to be singleton and have only on instance of it.

Example:

// src/services/discord.service.ts
@RuntimeService()
export class DiscordService {
  private client;
  constructor() {
    this.client = new Discord.Client()
    this.client.login()
  }
  
  getUserData() { }
}
export const services = [
  AuthService,
  DiscordService
]

You can now use theses services inside your routes:

 authRouter.get('/users/me', (req, res) => {
   await req.services.auth.authenticate()
   return res.send(
     req.services.discord.getUserData()
   )
 })

About

A simple application to begin an Express & Typescript project

License:MIT License


Languages

Language:TypeScript 83.9%Language:JavaScript 16.1%