micro2 v1.6.2
Micro2 — Node.js based asynchronous micro-library (EXPERIMENTED)
Features
- Easy: Designed for usage with
async
andawait
- Middleware: Support middleware
- Logging: It has very low overhead logging method built. pino
Installation
Important: Right now Micro2
not ready for production application. For making micro2
a goal is to faster moduler application development. Make your application with moduler way.
npm install --save micro2
Usage
Create an index.js
file and export a function that accepts the standard http.IncomingMessage and http.ServerResponse objects:
module.exports = (req, res) => {
res.end('Welcome to Micro2')
}
or
module.exports = () => 'Welcome to Micro2'
async
& await
Micro2 is built for usage with async/await. You can read more about async / await.
const sleep = require('then-sleep')
module.exports = async (req, res) => {
await sleep(500)
return 'Ready!'
}
API
send(res, statusCode, data = null)
- Use
require('micro2').send
. statusCode
is aNumber
with the HTTP status code, and must always be supplied.- If
data
is supplied it is sent in the response. Different input types are processed appropriately, andContent-Type
andContent-Length
are automatically set. -string
:data
is written as-is. - If JSON serialization fails (for example, if a cyclical reference is found), a
400
error is thrown.
Sending a different status code
So far we have used return
to send data to the client. return 'Hello World'
is the equivalent of send(res, 200, 'Hello World')
.
const {send} = require('micro2')
module.exports = async (req, res) => {
const statusCode = 400
const data = { error: 'Custom error message' }
send(res, statusCode, data)
}
send(res, statusCode, data = null)
- Use
require('micro').send
. statusCode
is aNumber
with the HTTP status code, and must always be supplied.- If
data
is supplied it is sent in the response. Different input types are processed appropriately, andContent-Type
andContent-Length
are automatically set.Stream
:data
is piped as anoctet-stream
. Note: it is your responsibility to handle theerror
event in this case (usually, simply logging the error and aborting the response is enough).Buffer
:data
is written as anoctet-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.
Programmatic use
You can use Micro2 programmatically by requiring Micro2 directly:
const micro2 = require('micro2')
const sleep = require('then-sleep')
const server = micro2(async (req, res) => {
await sleep(500)
return 'Hello world'
})
server.listen(3000)
Middleware support
You can applied middleware with server.
server.use((req, res, next) => { // err, req, res
log.info('middleware 1')
next()
})
Logger
Micro2 uses pino for logging. You could enable logging conditionaly. process.env.NODE_ENV
const log = server.log({
enabled: true
})
micro2(fn)
- This function is exposed as the
default
export. - Use
require('micro2')
. - Returns a
http.createServer
that uses the providedfunction
as the request handler. - The supplied function is run with
await
. So it can beasync
.
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. - Stacks are printed out with
console.error
and during development (whenNODE_ENV
is set to'development'
) 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(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
setserror.originalError
which identifies the original error (if any).
Error Handling
Micro2 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 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:
const rateLimit = require('my-rate-limit')
module.exports = async (req, res) => {
await rateLimit(req)
// ... your code
}
Alternatively you can create the Error
object yourself
if (tooMany) {
const err = new Error('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 {
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 Micro2 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('micro2')
const handleErrors = fn => async (req, res) => {
try {
return await fn(req, res)
} catch (err) {
console.log(err.stack)
send(res, 500, 'My custom error!')
}
}
module.exports = handleErrors(async (req, res) => {
throw new Error('What happened here?')
})
Testing
TODO
Contributing
As always, you can run the Jest tests using: npm test
and ESLint lint using: npm run lint