Giter VIP home page Giter VIP logo

tse's Introduction

picture alt

Minimalist express/typescript clean boilerplate - inspired from Laravel framework

What this includes?

  • TypeScript compiler
  • Express
  • Nodemon watcher (hot reload)
  • Active sourcemap for debugging
  • TS-lint
  • ES6 support
  • Mongoose ORM
  • MongoDB connection
  • Multiple env
  • Standard API response
  • Middleware configurations
  • Basic CRUD

How to start?

  1. Clone the repo git clone https://github.com/binaryk/node-ts-boilerplate.git
  2. cd to the working directory
  3. Run yarn or npm install
  4. Run npm install -g tsc (to install globally typescript transpiler)
  5. Install MongoDB and run it (mongod)
  6. Run npm watch - to watch your file updates
  7. Open postman and try GET: http://127.0.0.1:3000/sample, you will receive: picture alt
  8. Add your MongoDB configuration in src/config/database.ts
  9. Add your own routes in src/routes
  10. Add your own controllers in src/controllers
  11. Add your own models in src/models
  12. Enjoy development

Config

Database

  • config/database.ts is the configuration file for the database - Default mongo arguments are stored there

Core

  • You can leave the black box of the core to configure your application, based on your defined routes and middlewares from the config/middlewares.ts - middleware object, or, you can do this manually in the app.ts:
      this.core = new Core(this.app, {
          /**
           * Activate global middlewares from the `config/middeware.ts`
           */
          globalMiddleware: false
      });
      this.core.use(bodyParser.json());
      // this.core.use(/* other middleware function */)
      /*!important, init routes*/
      this.core.initRoutes();

Standard Response object

  • API has a customizable monkey patching, which extends the default res express object with a new function respond. This is useful to have a Standard API Response with the format:
          data: data,
          message: message,
          responseCode: responseCode
  • To use this standard it's enough to write:
        this.router.get('sample', (req, res, next) => {
            res.respond({
                foo: 'Standard data from API',
            }, `Standard message from API`, 201 )
        });
  • Response from the server: picture alt

    Group routes and define middleware

    • For CRUD contact instance you can use the group wrapper
    • Add prefix with middleware keys to the routes group like this:
        this.router.group({
            prefix: 'contact',
            middleware: ['session', 'auth:admin']
        }, (router) => {
            router.post('', this.contactController.store);
            router.get(':contactId', this.contactController.getContactWithID);
            router.get('', this.contactController.getContacts);
            router.post('', this.contactController.store);
            router.put(':contactId', this.contactController.updateContact);
            router.delete(':contactId', this.contactController.deleteContact);
        })

Add custom middleware

I. You have two options to define a middleware:

  • to declare callback function directly:
    foo: (req, res, next) => {
        console.log('First middle');
        next();
    },
  • Add your file with middleware in /src/http/middleware*
  • Bellow we have an example of an empty middleware:
export class Authenticate {
    constructor () {
    }

    public handle(req, res, next) {
        console.log('Authenticate middleware - check if is authenticated');
        next();
    }
}

| โŒ˜ | The handle method is required!

II. Declare it in src/config/middleware.ts

export const routesMiddleware = {
    auth: Authenticate,
    session: (req, res, next) => {
        console.log('Local definition');
        next();
    }
};

III. In the Route definition, just add the key of the middleware, like this:

     this.router.group({
            middleware: 'auth'
        }, (router) => {

Array of middlewares:

middleware: ['auth', 'session']

IV. Define these two middlewares in a middleware group:

export const groupsMiddleware = {
    web: [
        StartSession,
        Authenticate
    ]
};

And use it like:

       prefix: 'group',
       middleware: 'web'
 }, r => {

V. Send arguments to the middleware functions from the definition:

 this.router.group({
            prefix: 'group',
            middleware: 'auth:admin,user'
        }, 
  • Now I can get my arguments as an array like: ['admin', 'user'] in the auth middleware, BUT, there you should implement handle function, which returns an middelware signature
    public handle(args) {
        return (req, res, next) => {
            console.log(args, 'Encapsuleted arguments from the route');
            next();
        };
    }

Add global middlewares

  • In config/middlewares.ts we have an object for global middleware definitions, allowed format are:
  1. Class with an handle function
  2. Simple callback function
  3. Array of callback functions
export const middleware = {
   bodyParser: [
       bodyParser.json(),
       bodyParser.urlencoded({ extended: false })
   ],
   application: Application,
   foo: [(req, res, next) => {
       console.log('First middle');
       next();
   }, (req, res, next) => {
       console.log('Second middle');
       next();
   }]
};

Use express router as default

 this.router.get('/sample', (req, res, next) => {
            res.json({
                'data': 'test'
            });
        });

Exceptions

  • Framework will expose the class Exception for error handling and HttpErrors catch:
router.get('/funny-page', (req, res, next) => {
    throw new Exception('not-implemented', 501, {
        data: 'foo'
    });
})

Questions

The issue list of this repo is exclusively for bug reports and feature requests. Feel free to open a PR of issue.

Colaborators

  • Props to Dale Guyen for this article, this project was started based on it arhitecture

Stay In Touch

License

MIT

Copyright (c) 2018-present, Binaryk (Eduard) Lupacescu

tse's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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