npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

merry

v5.5.2

Published

Modular http framework

Downloads

107

Readme


Merry is a little Node framework that helps you build performant applications with little effort. We don't think that "fast" and "cute" should be mutually exclusive. Out of the box we've included consistent logging, standardized error handling, a clean streams API and plenty of nuts, bolts and options to customize merry to fit your use case. We hope you have a good time using it. :v: -Team Merry

Features

  • fast: using Node streams, merry handles request like no other
  • fun: helps with boring stuff like error handling
  • communicative: standardized ndjson logs for everything
  • sincere: doesn't monkey patch Node's built-ins
  • linear: smooth sailing from tinkering to production
  • very cute: 🌊🌊⛵️🌊🌊

Table of Content

Usage

var merry = require('merry')

var app = merry()

app.route('GET', '/', function (req, res, ctx) {
  ctx.log.info('oh hey, a request here')
  ctx.send(200, { cute: 'butts' })
})

app.route('default', function (req, res, ctx) {
  ctx.log.info('Route doesnt exist')
  ctx.send(404, { message: 'nada butts here' })
})

app.listen(8080)
$ node index.js | merry

Logging

Merry uses the pino logger under the hood. When you create a new merry app, we enable a log forwarder that by default prints all logs to process.stdout.

There are different log levels that can be used. The possible log levels are:

  • debug: used for developer annotation only, should not be enable in production
  • info: used for transactional messages
  • warn: used for expected errors
  • error: used for unexpected errors
  • fatal: used for critical errors that should terminate the process
var merry = require('merry')
var app = merry()

app.route('GET', '/', function (req, res, ctx) {
  ctx.log.debug('it works!')
  ctx.log.info('hey')
  ctx.log.warn('oh')
  ctx.log.error('oh no!')
  ctx.log.fatal('send help')
})

The difference between an expected and unexpected error is that the first is generally caused by a user (e.g. wrong password) and the system knows how to respond, and the latter is caused by the system (e.g. there's no database) and the system doesn't know how to handle it.

Error handling

Error handling is different for each application. Errors come in different shapes, have different status codes, so we can't provide a one-size-fits-all solution. But we do think that having consistent error messages is useful, so Merry comes with a recommended pattern to handle errors.

// errors.js
exports.ENOTFOUND = function (req, res, ctx) {
  ctx.log.warn('ENOTFOUND')
  ctx.send(404, {
    type: 'invalid_request_error',
    message: 'Invalid request data'
  })
}

exports.EDBOFFLINE  = function (req, res, ctx) {
  ctx.log.error('EDBOFFLINE')
  ctx.send(500, {
    type: 'api_error',
    message: 'Internal server error'
  })
}
// index.js
var errors = require('./errors')
var merry = require('merry')
var db = require('my-cool-db')

var app = merry()

app.route('GET', '/', function (req, res, ctx) {
  db.get('some-key-from-request', function (err, data) {
    if (err) return errors.ENOTFOUND(req, res, ctx)
    ctx.send(200, data)
  })
})

app.listen(8080)

Configuration

Generally there are two ways of passing configuration into an application. Through files and through command line arguments. In practice it turns out passing environment variables can be done with less friction than using files. Especially in siloed environments such as Docker and Kubernetes where mounting volumes can at times be tricky, but passing environment variables is trivial.

Merry ships with an environment argument validator that checks the type of argument passed in, and optionally falls back to a default if no value is passed in. To set the (very common) $PORT variable to default to 8080 do:

var merry = require('merry')
var env = { PORT: 8080 }
var app = merry({ env: env })
app.listen(app.env.PORT)

And then from the CLI do:

node ./server.js
// => port: 8080

PORT=1234 node ./server.js
// => port: 1234

Routing

Merry uses server-router under the hood to create its routes. Routes are created using recursive arrays that are turned into an efficient trie structure under the hood. You don't need to worry about any of this though; all you need to know is that we've tested it and it's probably among the fastest methods out there. Routes look like this:

var merry = require('merry')
var app = merry()
app.route('GET', '/', handleIndex)
app.route('PUT', '/foo', handleFoo)
app.route('GET', '/foo/:bar', handleFoobarPartial)
app.listen()

Partial routes can be set using the ':' delimiter. Any route that's registered in this was will be passed to the ctx argument as a key. So given a route of /foo/:bar and we call it with /foo/hello, it will show up in ctx as { bar: 'hello' }.

Middleware

We do provide you with a way to access your route's ctx via app.use

var merry = require('merry')
var app = merry()
app.use(function (req, res, ctx) {
  ctx.foo = 'bar'
})

HTTP2

For http2 support you will need to provide a key and a cert to establish a secure connection. These can be passed as part of merry's opts. If http2 is not available, an error will be thrown to upgrade your node version to > v8.4.0.

var merry = require('merry')
var fs = require('fs')

var opts = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem')
}
var app = merry(opts)

app.listen(8080)

API

app = merry(opts)

Create a new instance of merry. Takes optional opts:

  • opts.logLevel: defaults to 'info'. Determine the cutoff point for logging
  • opts.logStream: defaults to process.stdout. Set the output writable stream to write logs to
  • opts.env: pass an object containing env var assertions
  • opts.key: key to create an http2 connection
  • opts.cert: cert to create an http2 connection

app.use(req, res, ctx)

Allows you to modify req, res and ctx objects prior to handling a route.

app.route(method|methods, route, handler)

Register a new handler for a route and HTTP method. Method can be either a single HTTP method, or an array of HTTP methods.

app.route('default', handler)

Register a new default handler that will be called if no other handlers match.

routes

Each route has a signature of (req, res, ctx):

  • req: the server's unmodified req object
  • res: the server's unmodified res object
  • ctx: an object that can contain values and methods

ctx.params

Parameters picked up from the router using the :route syntax in the route.

ctx.env

Environment variables passed into the choo({ env }) constructor.

ctx.log[loglevel]([…data])

Log data. Loglevel can be one of trace, debug, info, warn, error, fatal. Can be passed varying arguments.

ctx.send(statusCode, data, [headers])

Efficiently encode JSON, set the appropriate headers and end the request. Uses streams under the hood.

ctx.parse(jsonStream, callback(err, data))

Parse a stream of JSON into an object. Useful to decode a server's req stream with.

handler = app.start()

Create a handler that can be passed directly into an http server.

var merry = require('merry')
var http = require('http')

var app = merry()
app.route('GET', '/', handleRoute)

var handler = app.start()
var server = http.createServer(handler)
server.listen(8080)

function handleRoute (req, res, ctx, done) {
  done(null, 'hello planet')
}

app.listen(port)

Start the application directly and listen on a port:

var merry = require('merry')

var app = merry()
app.route('GET', '/', handleRoute)
app.listen(8080)

function handleRoute (req, res, ctx, done) {
  done(null, 'hello planet')
}

Installation

$ npm install merry

See Also

License

MIT