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

json-api-resource

v0.8.0

Published

Query, transform and persist datasets based on JSON API specification.

Downloads

4,133

Readme

JSON api resource

Build Status NPM Status

Query and transform datasets based on JSON API specification. Lightweight library that runs both in browser and server environment. Weighs less than 3KB.

Visit documentation site.

Although JSON api specification provides elegant and standard way of representing resources with JSON - consuming those datasets oftentimes can be cumbersome.

Nested relation data is especially tricky to transform to format better suited for common templating or state management patterns. This library provides simple yet powerful query engine to transform JSON api dataset to format of your liking.

By utilizing library model and collection classes you can easily query and manipulate datasets. Models can be altered and easily synchronized with server (with use of http mixin loaded separately).


Features

  • query and alter dataset attribute and relation values
  • normalize data to custom schema format
  • manipulate and create resources with extend-able model and collection utilities

Features with http mixin enabled

  • retrieve JSON api models and collections from server
  • persist new, changed and deleted models
  • update subset of resource attribute or relation data
  • handle file uploads alongside JSON data payload

Basic usage

// install via npm
npm install json-api-resource --save
// require module
var Model = require('json-api-resource').Model;

// create dataset model
const model = new Model(jsonApiData);

// get attribute
model.get('title');

// get attribute from related entity
model.get('author.firstName');

Examples and api

Example JSON api formatted dataset for "article" resource is shown bellow.

const articleData = {
    data: {
        type: 'article',
        id: '1',
        attributes: {
            title: 'Test article',
            body: 'The shortest article. Ever.'
        },
        relationships: {
            author: {data: {id: '42', type: 'user'}},
            publisher: {data: {id: '24', type: 'user'}},
            tags: {data: [
                {id: '1', 'type': 'tag'},
                {id: '2', 'type': 'tag'}
            ]}
        }
    },
    included: [{
        type: 'user',
        id: '42',
        attributes: {
            firstName: 'John',
            lastName: 'Doe',
        },
        relationships: {
            boss: {'data': {'id': '42', 'type': 'user'}},
        }
    }, {
        type: 'tag',
        id: '1',
        attributes: {
            name: 'tag 1'
        }
    }, {
        type: 'tag',
        id: '2',
        attributes: {
            name: 'tag 2'
        }
    }]
};

Query and normalize data

Retrive simple data like so:

new Model(articleData).get('title');
// will return 'Test article

Model.create(articleData).get('author.firstName');
// will output 'John'

Model.create(articleData).get(['id', 'title', 'body']);
// will return
{
     id: '1',
     title: 'Test article',
     body: 'The shortest article. Ever.'
}

Normalize dataset to more complex schema:

Model.create(articleData).get([
    'id',
    'title',
    ['titleCaps', article => article.get('title').toUpperCase()],
    'body',
    ['author', [
        'firstName',
        'lastName',
        ['boss', [
            'firstName',
            'lastName',
        ]],
    ]],
    ['tags', [
        'id',
        'name'
    ]]
]);

// will return
{
    id: '1',
    title: 'Test article',
    titleCaps: 'TEST ARTICLE',
    body: 'The shortest article. Ever.',
    author: {
        id: '42',
        firstName: 'John',
        lastName: 'Doe',
        boss: {
            firstName: 'John',
            lastName: 'Doe'
        }
    },
    tags: [{
        id: '1',
        name: 'tag 1'
    }, {
        id: '2',
        name: 'tag 2'
    }]
};

Working with collections

Collections can be normalized to schema via identical api. Standard array methods ('forEach', 'map', 'filter', 'reduce', 'slice') are implemented on all collection objects.

// import collection
var Collection = require('json-api-resource').Collection
var collection = new Collection(articleData);

collection.get('title');
// will return ['Test article']

collection.get(['title']);
// will return [{title: 'Test article'}]

collection.get(['id', 'title', 'body']);
// will return
[{
     id: '1',
     title: 'Test article',
     body: 'The shortest article. Ever.'
}]

collection.map(model => model.get('title'));
// will return ['Test article']

collection.where({title: 'Test article'});
// returns array of models which satisfy query above

collection.findWhere({id: '1'});
// returns first found model

collection.add(articleModel);
// add model to collection

collection.remove(articleModel);
// remove model to collection

HTTP mixin

Http mixin gives your models and collections a way to talk to your server. Using straightforward api models and collections can be conveniently retrieved from and persisted to server.

Any http library (axios, $.ajax or something else) can be used for server communication. Example mixin configuration for jQuery is shown bellow:

var Model = require('json-api-resource').Model;
var Collection = require('json-api-resource').Collection;
var httpMixin = require('json-api-resource/lib/httpMixin');

httpMixin({
    Model: Model,
    Collection: Collection,
    baseUrl: '/api/',
    http: params => {
        return new Promise((resolve, reject) => {

            $.ajax($.extend({
                dataType: 'json',
                processData: false,
                contentType: 'application/vnd.api+json'
            }, params)).then((data, textStatus, jqXHR) => {
                resolve({data: data});
            }, jqXHR => {
                reject(jqXHR);
            });

        });
    }
});

Retrieving models

// Using callback api
Model.getFromApi({type: 'article', id: '1'}, function(model) {
    // do something with model instance
});

// Using promises api
Model.getFromApi({type: 'article', id: '1'}).then(function(model) {
    // do something with model instance
});

// other ways
Model.extend({type: 'tag'}).getFromApi('1');
Model.getFromApi({url: '/api/article/1'});

Retrieving collections

// Using callback api
Collection.getFromApi('article', function(collection) {
    // do something with collection
});

// Using promises api
Collection.getFromApi('article').then(function(collection) {
    // do something with collection
});

Installation

Library can be used in browser and node server environment.

// install via npm
npm install json-api-resource --save

// if using bundler or node server
var resource = require('json-api-resource');
var Model = resource.Model;
var Collection = resource.Collection;

// or just using browser globals
var resource = window.jsonApiResource;