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

pgjson

v0.0.9

Published

Postgres as a simple JSON document store.

Downloads

24

Readme

PGJSON: start saving data to Postgres without thinking about schema

Welcome to PGJSON!

Build Status NPM Link

A simple, zero-config, API for saving and retrieving JSON documents in a Postgres database. Just import and start using.

Features

  • Support for PUT, POST, GET and DEL operations
  • Support for listing all docs and all _ids
  • Very basic querying API with filtering and ordering
  • You can start using this and later create indexes on specific JSON fields, write your own complex queries, create views or materialized views mixing the data in the pgjson.main table with other tables in the same database, or even export all data to other tables with formats and schemas, then forget about pgjson, Postgres is powerful and this library does not intend to stay between your data and all this power.

Example

var Promise = require('bluebird')
var db = new (require('pgjson'))('postgres:///db')

Promise.resolve().then(function () {
  return db.post({
    name: 'tomato',
    uses: ['tomato juice']
  })
})
.then(function (res) {
  console.log(res) /* {ok: true, id: 'xwkfi23syw'} */
  return db.get(res.id)
})
.then(function (doc) {
  console.log(doc) /* {_id: 'xwkfi23syw', name: 'tomato', uses: ['tomato juice']} */
  doc.uses.push('ketchup')
  doc.colour = 'red'
  return Promise.all([
    db.put(doc),
    db.post([{name: 'banana', colour: 'yellow'}, {name: 'strawberry', colour: 'red'}])
  ])
})
.then(function (res1, res2) {
  console.log(res1) /* {ok: true, id: 'xwkfi23syw'} */
  console.log(res2) /* {ok: true, ids: ['xios83bndf', 'dx83hsalpw']} */
  return db.query({
    filter: 'colour = "red"',
    orderby: 'name',
    descending: true
  })
})
.then(function (docs) {
  console.log(docs) /* [{_id: 'xwkfi23syw', name: 'tomato', uses: ['tomato juice', 'ketchup'], colour: 'red'},
                        {_id: 'dx83hsalpw', name: 'strawberry', colour: 'red'}] */
  return db.del(docs[0]._id)
})
.catch(console.log.bind(console))

In the meantime:

postgres=> SELECT * FROM pgjson.main;
     id     |                                doc
------------+-------------------------------------------------------------------
 xwkfi23syw | {"_id": "xwkfi23syw", "name": "tomato", "uses": ["tomato juice"]}
(1 row)
postgres=>
postgres=> select * from pgjson.main 
;
            id             |                                       doc                                        
---------------------------+----------------------------------------------------------------------------------
 xwkfi23syw | {"_id": "xwkfi23syw", "name": "tomato", "uses": ["tomato juice"]}
 xios83bndf | {"_id": "xios83bndf", "name": "banana", "colour": "yellow"}
 dx83hsalpw | {"_id": "dx83hsalpw", "name": "strawberry", "colour": "red"}
(3 rows)

Basically this.


API

new PGJSON(options): DB

options is anything pg can take: a connection string, a domain socket folder or a config object. See the link for more details.

DB.get(string or array): Promise -> doc

accepts the id, as string, of some document as a parameter, or an array of ids, and returns a promise for the raw stored JSON document. If passed an array of ids, the promise resolves to an array filled with the documents it could find, or null when it could not, in the correct order. If passed a single id and the target document is not found the promise resolves to null.

DB.post(object or array): Promise -> response

accepts an object or an array of objects corresponding to all the documents you intend to create. Saves them with a random ._id each and returns a promise for a response which will contain {ok: true, id: <the random id>}. If an array of objects was passed, instead returns {ok: true, ids: [<id>, <id>...]} with the ids in the correct order. If any passed object has an _id property this property will be discarded.

DB.put(document): Promise -> response

same as .post, but instead of creating a new document with a random id, this expects a complete document, which is to say an object with an _id property. Updates (or creates, if none is found) the document with the specified id.

DB.del(string or array): Promise -> response

accepts an id, as string, or an array of strings corresponding to all the keys you want to delete. The response is an object of format {ok: true}.

DB.query(query_params): Promise -> array

accepts an object with the following optional parameters:

  • filter: a string specifying a condition to match with the document. The left condition should be the path of the attribute in the document; and the right a valid JSON value. Examples:
    • '_id = "mellon"'
    • 'properties.age' = 23
    • 'children[2].name = "Jessica"'
  • orderby: a string with the path of the desired attribute in the document. Examples:
    • 'name'
    • 'items[0]'
    • 'billing.creditcard.visa.n'
  • descending: true or false -- default: false

DB.allIds(): Promise -> array

returns a promise to an array of ids (strings) of all documents stored in the database.

DB.count(): Promise -> integer

returns a promise to an integer with the count of all documents stored in the database.

DB.purgeAll(): Promise -> null

deletes everything: table, rows, schema. This isn't supposed to be used.

DB.init(): Promise -> null

creates a schema called pgjson, a table called main and a function called upsert. This is idempotent and is called automatically when the DB is instantiated.