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

sleepify

v1.1.1

Published

A library for quickly prototyping relational REST apis

Downloads

4

Readme

status version

sleepify

An unobtrusive, easy to use library to quickly prototype relational REST apis in Express.

Install

npm i -S sleepify

Changes (v1.1.0)

  • Plugin now accepts an express app or router as a first parameter. This was necessary to drop the express dependency.
//Previous behaviour
//let usersRouter = sleepify(userPlugin)

//Current behaviour
let usersRouter = express.Router()
sleepify(usersRouter, userPlugin)

//Equivalent
let usersRouter = sleepify(express.Router(), userPlugin)
//usersRouter points to the same router passed to it
Usage (TL;DR):
let express = require('express')
let bodyParser = require('body-parser')
let {sleepify, sleepymem} = require('sleepify')

let app = express()

app.use(bodyParser.json())

module.exports = app

//Dummy memorystore
let memDB = {}
memDB.cars = [
    {id: '0', name: 'Suzuki'},
    {id: '1', name: 'Honda'},
    {id: '2', name: 'BMW'},
    {id: '3', name: 'MX5'}
]
memDB.users = [
  {
    id: '0',
    name: 'Foo',
    cars: memDB.cars.slice(0, 2)
  },
  {
    id: '1',
    name: 'Bar',
    cars: memDB.cars.slice(2, 3)
  }
]

//sleepymem is a basic in-memory plugin
let userPlugin = sleepymem({
  name: 'user',
  model: memDB.users
})
    .pre((req, res, next) => {
      console.log(req.method + ' ' + req.originalUrl)
      next()
    })
    .pre([ACTIONS.CREATE, ACTIONS.UPDATE, ACTIONS.DELETE], (req, res, next) => {
      console.log(`Simulating authentication middleware`)
      next()
    })
    .rel(sleepymem({
      name: 'car',
      model: memDB.cars,
      expose: [ACTIONS.GET, ACTIONS.LIST, ACTIONS.REPLACE]
    }).pre((req, res, next) => {
      console.log('Cars middleware only!')
      next()
    }).pre(ACTIONS.CREATE, (req, res, next) => {
      console.log('Before car creation')
      next()
    })
    )
    .post((req, res, next) => {
      console.log(`Done ${req.method + ' ' + req.originalUrl}`)
      next()
    })

// This router will point to the following endpoints:
// GET /users
// GET /users/:userId
// POST /users
// PATCH /users/:userId
// DELETE /users/:userId
// GET /users/:userId/cars
// GET /users/:userId/cars/:carId
// PUT /users/:userId/cars/:carId
let usersRouter = express.Router()
sleepify(usersRouter, userPlugin)

let apiRouter = express.Router()
apiRouter.use(usersRouter)
app.use('/api/v1', apiRouter)

Plugin methods:

plugin.pre(action, middleware) / plugin.post(action, middleware):
  • action: The action the middleware should be applied to. One of the actions from ACTIONS.
  • middleware: function (req, res, next) / Array - An express middleware or an array of them.

action can be replaced by middleware. This is equivalent to plugin.pre(ACTIONS.ALL, middleware) or plugin.post(ACTIONS.ALL, middleware) respectively.

plugin.rel(plugin):
  • plugin: An instance of a plugin to be nested. Much like a nested router.

Plugins

Plugins are a way to define how an action should be performed. A plugin takes an options object:

options:
  • name: String (required) - The prefix for these routes (for example 'user').
  • plural: String (optional, default: name + 's') - The prefix for these routes (for example 'facilities').
  • model: AnyObject (optional, default: undefined) - An object representing the model to be interacted with. This is available later in req.slp.model
  • expose: Array (optional, default: ACTIONS.ALL) - The endpoints to expose.
  • methods: Object (required, default: noop object) - An object containing at least one of the actions defined in ACTIONS as a key with a value of function (req, done) describing the implementation of this specific method. Callback: done(statusCode / Error, responseObject).
Example:
{
    name: 'facility',
    plural: 'facilities',
    model: mongoose.model('Facility'),
    expose: [ACTIONS.GET, ACTIONS.LIST],
    methods: {
        get: (req, done) => {
            req.slp.model.findById(req.slp.id)
                .then(facility => {
                    if(!facility) return done(404)
                    done(200, facility)
                }).catch(done)
        },
        list: (req, done) => {
            req.slp.model.find({...})
                .then(facilities => done(200, facilities))
                .catch(done)
        }
    }
}

Extending plugins

An example implementation is available here.

MongoosePlugin will be available soon in a different repo.

TODO

  • [ ] Add support for collection delete.
  • [x] Allow expose endpoint selection in Plugins.
  • [ ] Add support for other node-based frameworks (koa, restify...).

Development

Install dependencies: npm i

Run tests: npm test