Nebulous Program Mechanic
Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

iomicro

1.6.4 • Public • Published

iomicro

A microservice library for node.js

A simple, powerful way to create microservices in node.

npm install iomicro --save

I highly recommend automatically running npm update before starting your app as I frequently update this module.

Complete example

The real beauty behind this library is the ability to set up microservices very quickly, without having to redefine the redundant setup parts of the app.

const micro = require('iomicro');
 
micro.get('/', { private: true }, (req, res) => {
    res.render('home', { title: 'Home' });
});
 
micro.listen(3000, { appName: 'My App', hello: 'The app is now online.', ssl: { key: '/path/to/key.pem', cert: '/path/to/cert.pem', forceHTTPS: true } }); 

This tiny app will do all of the following:

  • Run an express app on port 3000
  • Use HTTPS with SSL certificate and key passed through
  • Log all requests and responses to the console and a log file asynchronously
  • Expose the URL only to users who pass an access key specified on startup
  • Render fast, dynamic pages using dotJS
  • JSONize POST request paramaters into req.body

Usage

Now I will detail in much more depth the specs of the API.

const micro = require('iomicro');

Options

No options are required, and can be omitted entirely as a parameter.

Global options

const options = {
    appName: 'Microservice', // The name of your app.
    hello: 'The app is now online.' // The message logged when the app starts up.
    ssl: {
        key: '/path/to/key.pem', // Path to your SSL key
        cert: '/path/to/cert.pem', // Path to your SSL cert
        forceHTTPS: true // Will auto-redirect all non-HTTPS requests to HTTPS.
    },
    logDir: 'logs', // The relative folder the logs are dumped to.
    viewDir: 'views', // The relative folder that res.render uses.
};
 
// Initialize options after iomicro is loaded without starting up a server.
micro.init(options)
 
// Initialize options when the server begins to listen.
micro.listen(3000, options).then(function() {
    console.log('Server is good to go!')
});
A note on HTTPS

If the ssl object is passed through with paths to a key and cert, an HTTPS server will automatically run instead of normal HTTP.

Additionally, if forceHTTPS is true, an HTTP server will automatically spin up on port 80 redirecting requests to the HTTPS server on the port you passed through.

Function-specific options

micro.get('/api/users', { private: true }, getUsers);

In order for private: true to work, pass through an access key on startup

node app.js "myreallyreallyreallyreallylonghashedkey"
node api.js "Bearer eylajs9x1m.wpz0jcmqo9askdmzioenosjhmdow22~o0cj"

This ensures that no keys will be immediately visible anywhere in your codebase.

For the endpoints that have private: true it will then attempt to match said key with

  • The Authorization HTTP header, AKA req.headers.authorization
  • User POST parameter authorization, AKA req.body.authorization
I'm aware this feature is limited, and will likely add support for multiple or elastic keys in the future.

Creating endpoints

micro.get('/api/users', { private: true }, (req, res) => {
    res.json([{ username: 'user1' }])
});
micro.post('apps/app', (req, res) => {
    res.send('You posted: '+req.body)
});

Expose files such as JS or CSS files

micro.static('/files', 'localDir')

Expose files at endpoint files with express static options

micro.static('/files', 'localDir', options)

Creating views

Pass through variables

Render the view login.dot in the <viewDir> folder

res.render('login', req.body);

login.dot (assuming req.body.username exists)

Welcome back, [[=model.username]].

Partials

res.render('master');

master.dot

Hello from master.dot!
 
[[= partial('slave.dot') ]]  

slave.dot

Hello from slave.dot

All-around HTML, CSS, and JS syntax apply in these views.

For more, read: express-dot-engine

Logging

All logs are logged to the console and saved to <logDir>/<YYYY>-<MM>-<DD>.log

The timestamps on each line use the timezone native to your system.

Automatic logs

On app startup

19:01:24.366 INFO  [<appName>] <hello>

On every user request

18:55:44.148 INFO  [<appName>] 200 GET / 127.0.0.1
18:56:24.506 INFO  [<appName>] 201 POST /register { "username": "foo", "password": "bar" } 127.0.0.1

Triggered logs

INFO logging

micro.log('Log this message please.');

ERROR logging

micro.error('Something bad happened :(');

Result in

19:01:24.366 INFO  [<appName>] Log this message please.
19:01:24.994 ERROR  [<appName>] Something bad happened :(

Bonus features

Run a websocket using ws
const socket = micro.socket({ port: 8080 })
 
socket.on('connection', function() {
    micro.log('User connected via websocket')
})
// Start a secure websocket using a global SSL certificate
micro.init({ ssl: { cert: '/path/to/cert.pem', key: '/path/to/key.pem' } })
const secureSocket = micro.socket({ port: 8080 }) 
// Start a secure websocket using a specific SSL certificate
const secureSocket = micro.socket({
    port: 8080,
    ssl: {
        cert: '/path/to/cert.pem',
        key: '/path/to/key.pem'
    }
})
Run bash commands
// Utilizing Promise resolve and rejects
micro.bash('echo "A bash command was run!"').then((bashRes) => {
    micro.log(bashRes);
}, (bashErr) => {
    micro.error(bashRes);
})
micro.bash('./runBackgroundProcess.sh');

Active libaries used

express (latest)
body-parser (latest)
express-dot-engine
simple-node-logger
request-ip

install

npm i iomicro

Downloadsweekly downloads

7

version

1.6.4

license

ISC

repository

githubgithub

last publish

collaborators

  • avatar