Code Monkey home page Code Monkey logo

w-srvr's Introduction

W-SRVR

NPM Version

A simple web server configurator for Expressjs

It makes the process of setting up a web server less verbose, by wrapping an Expressjs server inside a fluent interface configurator, so method calls can be chained for better readability.



Table of contents



Installation

This module is available on npm, so you could just:

$ npm install w-srvr



Configurators

The main Configurator object gives you access to some settings as well as the inner configurators: StaticConfigurator with server.static, and APIConfigurator with server.api.

Here is an example:

const Configurator = require('w-srvr');

const server = new Configurator();

server
   // *Setting the port:
   .port(3000)

   // *Configuring the API:
   .api
      .get('/api/users',     (req, res, next) => res.end())
      .get('/api/users/:id', (req, res, next) => res.end())
      .post('/api/users',    (req, res, next) => res.end())
      .done()

   // *Configuring the static resources:
   .static
      .add('/static/js',  '../src/js')
      .add('/static/css', '../src/css')
      .index('../src/index.html')
      .done()

   // *Starting the server:
   .start()
   .then(output => console.log('Server started at ' + output.address.href))
   .catch(err => console.error(err));



Other examples

Website

Lets say your website content is located under the /src folder:

├── main.js
└── src
    ├── css
    ├── js
    ├── imgs
    └── index.html

How we can serve all the /src folder content under the /static route, and setup the index page?

A simple way to do it would be:

main.js

server
   // *Setting up the server port:
   .port(3000)

   // *Setting up the static content, and the index page:
   .static
      .add('/static/css', './src/css')
      .add('/static/js',  './src/js')
      .add('/static/img', './src/img')
      .index('./src/index.html')
      .done()

   // *Starting the server:
   .start()
   // *Logging the server address:
   .then(output => console.log('Server started at ' + output.address.href))
   // *Logging errors:
   .catch(err => console.error(err));

See:



Web service

Is easy to build a simple web service with some routes:

server
   // *Setting up the server port:
   .port(3000)

   // *Setting up the server routes:
   .api
      .get('/ping', function(req, res, next){
         res.status(200)
            .send('pong')
            .end();
      })
      .done()

   // *Starting the server:
   .start()
   // *Logging the server address:
   .then(output => console.log('Server started at ' + output.address.href))
   // *Logging errors:
   .catch(err => console.error(err));

As your server starts to grow and gets more complex, you may want to organize your routes in separate files, so lets say you have the following project structure:

├── main.js
└── routes
    └── users.js

Considering that users.js exports some Expressjs middleware functions, we could build a CRUD web service this way:

main.js

// *Getting the users middleware routes module:
const users = require('./routes/users.js');

server
   // *Setting up the server port:
   .port(3000)

   // *Setting up the web service routes:
   .api
      .get('/api/v1/users',        users.getAll)
      .get('/api/v1/users/:id',    users.getOne)
      .post('/api/v1/users',       users.insert)
      .put('/api/v1/users/:id',    users.update)
      .delete('/api/v1/users/:id', users.remove)
      .done()

   // *Starting the server:
   .start()
   // *Logging the server address:
   .then(output => console.log('Server started at ' + output.address.href))
   // *Logging errors:
   .catch(err => console.error(err));

See:



HTTPS

It's simple to configure an HTTPS server using a key and certificate:

server
   .https({
      key: './my-key.key',
      cert: './my-cert.crt'
   }, true)
   // ...

or using a PFX file:

server
   .https({
      pfx: './my-pfx.pfx',
      passphrase: './my-pass.txt'
   }, true)
   // ...

See:



CORS

The advanced configurator helps you to setup CORS responses correctly:

server.api
   .most('/api/v1/*')
      .advanced
      .allowedOrigins('*')
      .allowedMethods('GET', 'POST')
      .allowedHeaders('Content-Type')
      .done()
   .get(...)
   .post(...)
   // ...

Now, every origin can make GET and POST requests (with a JSON body for example, see Body parsing) to routes inside /api/v1/ without being rejected by cross-origin policies.

You can get further information on CORS here (MDN).



Body parsing

The advanced configurator can also enable request body parsing:

server.api
   .post(...)
      .advanced
      .parseJSON({limit: '400kb'})
      .parseURLEncoded()
      .done()
   .get(...)

See:




Testing

If you would like to run the tests, you can do it with the test command:

$ npm test

Make sure you have installed the dev-dependencies, as the tests will need them:

$ npm install --only=dev



Feedback

If you want a feature to be added or give some other feedback, feel free to open an issue.



License

MIT

w-srvr's People

Contributors

potentii avatar

Stargazers

 avatar  avatar

Watchers

 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.