Giter Club home page Giter Club logo

micro's Introduction

Micro — Async ES6 HTTP microservices

Build Status Slack Channel XO code style

Features

  • Easy. Designed for usage with async and await (more)
  • Fast. Ultra-high performance (even JSON parsing is opt-in).
  • Micro. The whole project is ~100 lines of code.
  • Agile. Super easy deployment and containerization.
  • Simple. Oriented for single purpose modules (function).
  • Explicit. No middleware. Modules declare all dependencies.
  • Standard. Just HTTP!
  • Lightweight. The package is small and the async transpilation fast and transparent

Example

The following example sleep.js will wait before responding (without blocking!)

const { send } = require('micro');
const sleep = require('then-sleep');
module.exports = async function (req, res) {
  await sleep(500);
  send(res, 200, 'Ready!');
}

To run the microservice on port 3000, use the micro command:

$ micro -p 3000 sleep.js

To run the microservice on port 3000 and localhost instead of listening on every interface, use the micro command:

$ micro -p 3000 -H localhost sleep.js

Documentation

Installation

Note: micro requires Node 6.0.0 or later

Install from NPM:

$ npm init
$ npm install micro --save

Then in your package.json:

"main": "index.js",
"scripts": {
  "start": "micro -p 3000"
}

Then write your index.js (see above for an example). To run your app and make it listen on http://localhost:3000 run:

$ npm start

API

micro

micro(fn)

  • This function is exposed as the default export.

  • Use require('micro').

  • Returns a http.Server that uses the provided fn as the request handler.

  • The supplied function is run with await. It can be async!

  • Example:

    const micro = require('micro');
    const sleep = require('then-sleep');
    const srv = micro(async function (req, res) {
      await sleep(500);
      res.writeHead(200);
      res.end('woot');
    });
    srv.listen(3000);

json

json(req, { limit = '1mb' })

  • Use require('micro').json.

  • Buffers and parses the incoming body and returns it.

  • Exposes an async function that can be run with await.

  • limit is how much data is aggregated before parsing at max. Otherwise, an Error is thrown with statusCode set to 413 (see Error Handling). It can be a Number of bytes or a string like '1mb'.

  • If JSON parsing fails, an Error is thrown with statusCode set to 400 (see Error Handling)

  • Example:

    const { json, send } = require('micro');
    module.exports = async function (req, res) {
      const data = await json(req);
      console.log(data.price);
      send(res, 200);
    }

send

send(res, statusCode, data = null)

  • Use require('micro').send.

  • statusCode is a Number with the HTTP error code, and must always be supplied.

  • If data is supplied it is sent in the response. Different input types are processed appropriately, and Content-Type and Content-Length are automatically set.

    • Stream: data is piped as an octet-stream. Note: it is your responsibility to handle the error event in this case (usually, simply logging the error and aborting the response is enough).
    • Buffer: data is written as an octet-stream.
    • object: data is serialized as JSON.
    • string: data is written as-is.
  • If JSON serialization fails (for example, if a cyclical reference is found), a 400 error is thrown. See Error Handling.

  • Example

    const { send } = require('micro')
    module.exports = async function (req, res) {
      send(res, 400, { error: 'Please use a valid email' });
    }

return

return val;

  • Returning val from your function is shorthand for: send(res, 200, val).

  • Example

    module.exports = function (req, res) {
      return {message: 'Hello!'};
    }
  • Returning a promise works as well!

  • Example

    const sleep = require('then-sleep')
    module.exports = async function (req, res) {
      return new Promise(async (resolve) => {
        await sleep(100);
        resolve('I Promised');
      });
    }

sendError

sendError(req, res, error)

  • Use require('micro').sendError.
  • Used as the default handler for errors thrown.
  • Automatically sets the status code of the response based on error.statusCode.
  • Sends the error.message as the body.
  • During development (when NODE_ENV is set to 'development'), stacks are printed out with console.error and also sent in responses.
  • Usually, you don't need to invoke this method yourself, as you can use the built-in error handling flow with throw.

createError

createError(code, msg, orig)

  • Use require('micro').createError.
  • Creates an error object with a statusCode.
  • Useful for easily throwing errors with HTTP status codes, which are interpreted by the built-in error handling.
  • orig sets error.originalError which identifies the original error (if any).

Error handling

Micro allows you to write robust microservices. This is accomplished primarily by bringing sanity back to error handling and avoiding callback soup.

If an error is thrown and not caught by you, the response will automatically be 500. Important: during development mode (if the env variable NODE_ENV is 'development'), error stacks will be printed as console.error and included in the responses.

If the Error object that's thrown contains a statusCode property, that's used as the HTTP code to be sent. Let's say you want to write a rate limiting module:

const rateLimit = require('my-rate-limit')
module.exports = async function (req, res) {
  await rateLimit(req);
  // … your code
}

If the API endpoint is abused, it can throw an error like so:

if (tooMany) {
  const err = new Error('Rate limit exceeded');
  err.statusCode = 429;
  throw err;
}

Alternatively you can use createError as described above.

if (tooMany) {
  throw createError(429, 'Rate limit exceeded')
}

The nice thing about this model is that the statusCode is merely a suggestion. The user can override it:

try {
  await rateLimit(req);
} catch (err) {
  if (429 == err.statusCode) {
    // perhaps send 500 instead?
    send(res, 500);
  }
}

If the error is based on another error that Micro caught, like a JSON.parse exception, then originalError will point to it.

If a generic error is caught, the status will be set to 500.

In order to set up your own error handling mechanism, you can use composition in your handler:

module.exports = handleErrors(async (req, res) => {
  throw new Error('What happened here?');
});

function handleErrors (fn) {
  return async function (req, res) {
    try {
      return await fn(req, res);
    } catch (err) {
      console.log(err.stack);
      send(res, 500, 'My custom error!');
    }
  }
}

Testing

Micro makes tests compact and a pleasure to read and write. We recommend ava, a highly parallel micro test framework with built-in support for async tests:

const test = require('ava');
const listen = require('./listen');
const send = require('micro').send;
const request = require('request-promise');

test('my endpoint', async t => {
  const fn = async function (req, res) {
    send(res, 200, { test: 'woot' });
  };
  const url = await listen(fn);
  const body = await request(url);
  t.same(body.test, 'woot');
});

Look at the test-listen for a function that returns a URL with an ephemeral port every time it's called.

Transpilation

We now use async-to-gen, so that the only transformation that happens is converting async and await to generators.

If you want to do it manually, you can! micro(1) is idempotent and should not interfere.

micro exclusively supports Node 6+ to avoid a big transpilation pipeline. async-to-gen is fast and can be distributed with the main micro package due to its small size.

Deployment

You can use the micro CLI for npm start:

{
  "name": "my-microservice",
  "dependencies": {
    "micro": "x.y.z"
  },
  "main": "microservice.js",
  "scripts": {
    "start": "micro -p 3000"
  }
}

Then simply run npm start!

Contribute

  1. Fork this repository to your own GitHub account and then clone it to your local device
  2. Link the package to the global module directory: npm link
  3. Transpile the source code and watch for changes: npm start
  4. Within the module you want to test your local development instance of micro, just link it to the dependencies: npm link micro. Instead of the default one from npm, node will now use your clone of micro!

Credits

Thanks Tom Yandell and Richard Hodgson for donating the micro npm name.

micro's People

Contributors

albinekb avatar allain avatar amio avatar domachine avatar greenkeeperio-bot avatar kevin-roark avatar leebyron avatar leo avatar matheuss avatar nkzawa avatar onbjerg avatar rauchg 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.