async & await

Micro is built for usage with async/await. You can read more about async / await here

constsleep=require('then-sleep')

module.exports=async(req,res)=>{

awaitsleep(500)

return'Ready!'

}

Transpilation

The package takes advantage of native support for async and await, which is always as of Node.js 8.0.0! In turn, we suggest either using at least this version both in development and production (if possible), or transpiling the code using async-to-gen, if you can't use the latest Node.js version.

In order to do that, you firstly need to install it:

npm install -g async-to-gen

And then add the transpilation command to the scripts.build property inside package.json:

{

"scripts":{

"build":"async-to-gen input.js > output.js"

}

}

Once these two steps are done, you can transpile the code by running this command:

npm run build

That's all it takes to transpile by yourself. But just to be clear: Only do this if you can't use Node.js 8.0.0! If you can, async and await will just work right out of the box.

Port Based on Environment Variable

When you want to set the port using an environment variable you can use:

micro -p $PORT

Optionally you can add a default if it suits your use case:

micro -p ${PORT:-3000}

${PORT:-3000} will allow a fallback to port 3000 when $PORT is not defined.

createError(code, msg, orig)

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: Error stacks will be printed as console.error and during development mode (if the env variable NODE_ENV is 'development'), they will also be 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:

constrateLimit=require('my-rate-limit')

module.exports=async(req,res)=>{

awaitrateLimit(req)

// ... your code

}

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

if(tooMany){

throwcreateError(429,'Rate limit exceeded')

}

Alternatively you can create the Error object yourself

if(tooMany){

consterr=newError('Rate limit exceeded')

err.statusCode=429

throw err

}

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

try{

awaitrateLimit(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:

const{send}=require('micro')

consthandleErrors=fn=>async(req,res)=>{

try{

returnawaitfn(req, res)

}catch(err){

console.log(err.stack)

send(res,500,'My custom error!')

}

}

module.exports=handleErrors(async(req,res)=>{

thrownewError('What happened here?')

})

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:

constmicro=require('micro')

consttest=require('ava')

constlisten=require('test-listen')

constrequest=require('request-promise')

test('my endpoint',asynct=>{

constservice=micro(async(req,res)=>{

micro.send(res,200,{

test:'woot'

})

})

consturl=awaitlisten(service)

constbody=awaitrequest(url)

t.deepEqual(JSON.parse(body).test,'woot')

service.close()

})

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

Contributing

Fork this repository to your own GitHub account and then clone it to your local device

Link the package to the global module directory: npm link

Transpile the source code and watch for changes: npm start

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!