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

contextdb

v0.2.0

Published

Use json-context with leveldb. Contexts are automatically generated from matchers, and provides ability to watch matchers for realtime notifications.

Downloads

12

Readme

ContextDB - JSON Context for LevelDB

This module creates instances of JsonContext from a leveldb database using levelup. Datasources are automatically generated from matchers and watch for realtime changes.

Installation

$ npm install contextdb

API

require('level-json-context')(db, options)

Pass in an instance of a levelup database and specify matchers. Ensure the database has encoding: 'json'. Returns an instance of contextDB

Options:

  • matchers: Route changes into the correct places, and provide building blocks for page contexts. In addition to the matcher options on JSON Context, you need to specify matcher.ref as well. Use ref to refer to this matcher later when building contexts. Placeholders can be specified anywhere in the matcher filter by using {$param: 'queryToGetData'}
  • primaryKey: Choose the object key to use as the primary index. Defaults to 'id'.
  • incrementingKey: (defaults to '_seq') Add an incrementing ID to objects
  • timestamps: (defaults to true) whether to automatically add timestamps to edited objects created_at, updated_at, deleted_at. Required if using datasource.emitChangesSince.
var LevelDB = require('levelup')
var ContextDB = require('contextdb')

var db = LevelDB(__dirname + '/test-db', {
  encoding: 'json'
})

var contextDB = ContextDB(db, {
  matchers: [
    { ref: 'items_for_parent',
      item: 'items[id={.id}]',
      collection: 'items',
      match: {
        parent_id: {$param: 'parent_id'},
        type: 'comment'
      },
      allow: {
        change: true
      }
    },
    { ref: 'current_user',
      item: 'user',
      match: {
        type: 'user',
        id: 'user_123'
      }
    }
  ],
  primaryKey: 'id'
})

contextDB.applyChange(object)

Push objects into the database. This will also notify all relevant datasources listening.

All changes will be accepted so this should only be triggered by trusted sources.

var newObject = {
  id: 1,
  parent_id: 'site',
  name: "Home",
  type: 'page'
}

contextDB.applyChange(newObject)

contextDB.generate(options, callback(err, datasource))

Returns a datasource (instance of JSON Context) prepopulated with the relevent data as chosen by matchers and starting data.

It will recieve live events from the database for all specified matchers until datasource.destroy() is called.

Changes pushed in using datasource.pushChange will be checked against matchers and if pass, applied to the database.

Options:

  • data: The starting point for the datasource. Matchers can use $query to hook into the specified attributes.
  • matcherRefs: An array of refs from the matchers specified when creating the contextDB. This option is order sensitive as matchers can refer to the result of another matcher.

datasource.emitChangesSince(timestamp)

Will cause the datasource to emit all changes to any listeners that have occured since the given timestamp (including deletions)

Example

var params = {parent_id: 1, user_id: 'user_123', token: 'some_unique_random_string'}
var matcherRefs = ['current_user', 'items_for_parent']

var userDatasources = {}

contextDB.generate(params, matcherRefs, function(err, datasource){

  // save the context for connecting to later
  // in production we'd want to auto destroy if no connection recieved
  userDatasources[params.token] = datasource

  // using realtime-templates
  renderer.render('page', datasource, function(err, html){
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html)
  })
})

And handle the realtime connections:

var Shoe = require('shoe')

Shoe(function (stream) {
  var datasource = null

  stream.once('data', function(data){
    var token = data.toString().trim()
    datasource = userDatasources[token]
    console.log('LOGGING IN:', token)
    if (datasource){
      stream.pipe(datasource.changeStream()).pipe(stream)
    } else {
      stream.close()
    }
  })

  stream.once('end', function () {
    if (datasource){
      console.log("CLOSING:", datasource.data.token)
      datasource.destroy()
      userDatasources[datasource.data.token] = null
    }
  })

}).install(server, '/contexts')

And on the client:

var stream = Shoe('http://localhost:9999/contexts')
stream.write(datasource.data.token + '\n') //log in
stream.pipe(datasource.changeStream({verifiedChange: true})).pipe(stream)