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

injestdb

v2.4.5

Published

A peer-to-peer database for dat:// applications.

Downloads

27

Readme

InjestDB

Renamed to IngestDB

A peer-to-peer database for dat:// applications. How it works

Example

Setup in the browser:

const Injest = require('injestdb')
var db = new Injest('social-profiles')

Setup in node:

const DatArchive = require('node-dat-archive')
const Injest = require('injestdb')
var db = new Injest('social-profiles', {DatArchive})

Define your schema:

db.schema({
  version: 1,
  broadcasts: {
    primaryKey: 'createdAt',
    index: [
      'createdAt',
      '_origin+createdAt' // compound index. '_origin' is an autogenerated attribute which represents the URL of the authoring archive
    ],
    validator: record => {
      assert(typeof record.text === 'string')
      assert(typeof record.createdAt === 'number')
      return record
    }
  },
  likes: {
    primaryKey: 'createdAt',
    index: 'targetUrl',
    validator: record => {
      assert(typeof record.targetUrl === 'string')
      return record
    }
  },
  profile: {
    singular: true,
    index: 'name',
    validator: record => {
      assert(typeof record.name === 'string')
      return {
        name: record.name,
        description: isString(record.description) ? record.description : '',
        avatarUrl: isString(record.avatarUrl) ? record.avatarUrl : ''
      }
    }
  }
})

Then open the DB:

await db.open()

Next we add source archives to be ingested (added ot the dataset). The source archives are persisted in IndexedDB, so this doesn't have to be done every run.

await db.addArchives([alicesUrl, bobsUrl, carlasDatArchive])

Now we can begin querying the database for records.

// get the first profile record where name === 'bob'
var bobProfile = await db.profiles.get('name', 'bob')

// get all profile records which match this query
var bobProfiles = await db.profiles
  .where('name')
  .equalsIgnoreCase('bob')
  .toArray()

// get the 30 latest broadcasts from all source archives
var recentBroadcasts = await db.broadcasts
  .orderBy('createdAt')
  .reverse() // most recent first
  .limit(30)
  .toArray()

// get the 30 latest broadcasts by a specific archive (bob)
// - this uses a compound index to filter by origin, and then sort by createdAt
var bobsRecentBroadcasts = await db.broadcasts
  .where('_origin+createdAt')
  .between([bobsUrl, ''], [bobsUrl, '\uffff'])
  .reverse() // most recent first
  .limit(30)
  .toArray()

// get the # of likes for a broadcast
var numLikes = await db.likes
  .where('targetUrl').equals(bobsRecentBroadcasts[0]._url) // _url is an autogenerated attribute which represents the URL of the record
  .count()

We can also use Injest to create, modify, and delete records (and their matching files).

// update bob's name
await db.profiles.update(bobsUrl, {name: 'robert'})

// publish a new broadcast for bob
var broadcastUrl = await db.broadcasts.add(bobsUrl, {
  text: 'Hello!',
  createdAt: Date.now()
})

// modify the broadcast
await db.broadcasts.update(broadcastUrl, {text: 'Hello world!'})

// like the broadcast
await db.likes.add(bobsUrl, {
  targetUrl: broadcastUrl,
  createdAt: Date.now()
})

// delete the broadcast
await db.broadcasts.delete(broadcastUrl)

// delete all likes on the broadcast (that we control)
await db.likes
  .where({targetUrl: broadcastUrl})
  .delete()

TODOs

Injest is still in development.

  • [x] Indexer
  • [x] Core query engine
  • [x] Persisted tables and table reindex on schema change
  • [x] Mutation methods (add/update/delete)
  • [ ] Events
  • [x] Multikey indexes
  • [ ] More efficient key queries (currently loads full record from disk - could just load the keys)
  • [ ] Validation: filename must match primaryKey on non-singular tables
  • [ ] Support for .or() queries
  • [ ] Complete documentation

API quick reference

var db = new InjestDB(name)
InjestDB.list() => Promise<Void>
InjestDB.delete(name) => Promise<Void>
db.open() => Promise<Void>
db.close() => Promise<Void>
db.schema(Object) => Promise<Void>
db.addArchive(url|DatArchive, {prepare: Boolean}) => Promise<Void>
db.addArchives(Array<url|DatArchive>, {prepare: Boolean}) => Promise<Void>
db.removeArchive(url|DatArchive) => Promise<Void>
db.prepareArchive(url|DatArchive)
db.listArchives() => Promise<url>
db 'open' ()
db 'open-failed' (error)
db 'versionchange' ()
db 'indexes-updated' (archive, archiveVersion)

db.{table} => InjestTable
InjestTable#add(archive, record) => Promise<url>
InjestTable#count() => Promise<Number>
InjestTable#delete(url) => Promise<url>
InjestTable#each(Function) => Promise<Void>
InjestTable#filter(Function) => InjestQuery
InjestTable#get(url) => Promise<Object>
InjestTable#get(archive) => Promise<Object>
InjestTable#get(archive, key) => Promise<Object>
InjestTable#get(index, value) => Promise<Object>
InjestTable#isRecordFile(String) => Boolean
InjestTable#limit(Number) => InjestQuery
InjestTable#listRecordFiles(Archive) => Promise<Object>
InjestTable#name => String
InjestTable#offset(Number) => InjestQuery
InjestTable#orderBy(index) => InjestQuery
InjestTable#put(url, record) => Promise<url>
InjestTable#query() => InjestQuery
InjestTable#reverse() => InjestQuery
InjestTable#schema => Object
InjestTable#toArray() => Promise<Array>
InjestTable#toCollection() => InjestQuery
InjestTable#update(record) => Promise<Number>
InjestTable#update(url, updates|function) => Promise<Number>
InjestTable#update(archive, updates|function) => Promise<Number>
InjestTable#update(archive, key, updates|function) => Promise<Number>
InjestTable#upsert(url|archive, record|function) => Promise<Void | url>
InjestTable#where(index) => InjestWhereClause
InjestTable 'index-updated' (archive, archiveVersion)

InjestWhereClause#above(lowerBound) => InjestQuery
InjestWhereClause#aboveOrEqual(lowerBound) => InjestQuery
InjestWhereClause#anyOf(Array|...args) => InjestQuery
InjestWhereClause#anyOfIgnoreCase(Array|...args) => InjestQuery
InjestWhereClause#below(upperBound) => InjestQuery
InjestWhereClause#belowOrEqual(upperBound) => InjestQuery
InjestWhereClause#between(lowerBound, upperBound, {includeUpper, includeLower}) => InjestQuery
InjestWhereClause#equals(value) => InjestQuery
InjestWhereClause#equalsIgnoreCase(value) => InjestQuery
InjestWhereClause#noneOf(Array|...args) => InjestQuery
InjestWhereClause#notEqual(value) => InjestQuery
InjestWhereClause#startsWith(value) => InjestQuery
InjestWhereClause#startsWithAnyOf(Array|...args) => InjestQuery
InjestWhereClause#startsWithAnyOfIgnoreCase(Array|...args) => InjestQuery
InjestWhereClause#startsWithIgnoreCase(value) => InjestQuery

InjestQuery#clone() => InjestQuery
InjestQuery#count() => Promise<Number>
InjestQuery#delete() => Promise<Number>
InjestQuery#each(Function) => Promise<Void>
InjestQuery#eachKey(Function) => Promise<Void>
InjestQuery#eachUrl(Function) => Promise<Void>
InjestQuery#filter(Function) => InjestQuery
InjestQuery#first() => Promise<Object>
InjestQuery#keys() => Promise<Array<String>>
InjestQuery#last() => Promise<Object>
InjestQuery#limit(Number) => InjestQuery
InjestQuery#offset(Number) => InjestQuery
InjestQuery#or(index) => InjestWhereClause
InjestQuery#orderBy(index) => InjestQuery
InjestQuery#put(Object) => Promise<Number>
InjestQuery#urls() => Promise<Array<String>>
InjestQuery#reverse() => InjestQuery
InjestQuery#toArray() => Promise<Array<Object>>
InjestQuery#uniqueKeys() => Promise<Array<String>>
InjestQuery#until(Function) => InjestQuery
InjestQuery#update(Object|Function) => Promise<Number>
InjestQuery#where(index) => InjestWhereClause

API

db.schema(definition)

{
  version: Number, // the version # of the schema, should increment by 1 on each change

  [tableName]: {
    // is there only one record-file per archive?
    // - if true, will look for the file at `/${tableName}.json`
    // - if false, will look for files at `/${tableName}/*.json`
    singular: Boolean,

    // attribute to build filenames for newly-created records
    // ie `/${tableName}/${record[primaryKey]}.json`
    // only required if !singular
    primaryKey: String, 

    // specify which fields are indexed for querying (optional)
    // each is a keypath, see https://www.w3.org/TR/IndexedDB/#dfn-key-path
    // can specify compound indexes with a + separator in the keypath
    // eg one index               - index: 'firstName' 
    // eg two indexes             - index: ['firstName', 'lastName']
    // eg add a compound index    - index: ['firstName', 'lastName', 'firstName+lastName']
    // eg index an array's values - index: ['firstName', '*favoriteFruits']
    index: String|Array<String>,

    // validator & sanitizer (optional)
    // takes the ingested file (must be valid json)
    // returns the record to be stored
    // returns falsy or throws to not store the record
    validator: Function(Object) => Object

    // file-creator (optional)
    // takes the record
    // returns the object to be stored to the file
    // returns falsy or throws to not write the file
    toFile: Function(Object) => Object
  }
}

About validator and toFile

The validator method is called any time Injest is given a record, either due to reading it from an archive, or because the application called add() or update() with new record data.

The toFile method is only called when the application calls add() or update() with new record data. It is called after validator. Its main purpose is to reduce the data saved to the file.

How it works

InjestDB abstracts over the DatArchive API to provide a simple database-like interface. It is inspired by Dexie.js and built using LevelDB. (In the browser, it runs on IndexedDB using level.js.

Injest works by scanning a set of source archives for files that match a path pattern. Those files are indexed ("ingested") so that they can be queried easily. Injest also provides a simple interface for adding, editing, and removing records on the archives that the local user owns.

Injest sits on top of Dat archives. It duplicates the data it's handling into IndexedDB, and that duplicated data acts as a throwaway cache -- it can be reconstructed at any time from the Dat archives.

Injest treats individual files in the Dat archive as individual records in a table. As a result, there's a direct mapping for each table to a folder of .json files. For instance, if you had a 'tweets' table, it would map to the /tweets/*.json files. Injest's mutators, such as put or add or update, simply write those json files. Injest's readers & query-ers, such as get() or where(), read from the IndexedDB cache.

Injest watches its source archives for changes to the json files. When they change, it reads them and updates IndexedDB, thus the query results stay up-to-date. The flow is, roughly: put() -> archive/tweets/12345.json -> indexer -> indexeddb -> get().