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

js-data-jsonapi-light

v1.0.0-beta.2

Published

JsonApi adapter serializer/dezerializer light.

Downloads

132

Readme

js-data-jsonapi-light

NPM CircleCI build CircleCI build develop Codecov Issues

Overview

JsonAPI Adapter based on js-data-http for js-data

This adapter just add a light serialize and deserialize layer over DSHttpAdapter.

Compatibility

| package | requirement | | ------------ | ------------- | | js-data | >= 3.0.0 | | js-data-http | >= 3.0.0 |

By design it is not compatible with JS-Data v2, for a full integration on v2, you should use: js-data-jsonapi.

Quick Start

First you need to install everything needed :

npm install --save js-data js-data-http js-data-jsonapi js-data-jsonapi-light

Load js-data-jsonapi-light.js last.

import { DataStore } from 'js-data'
// or `var DataStore = JSDate.DataStore`

import { JsonApiAdapter } from 'js-data-jsonapi-light'
// or `var JsonApiAdapter = JSDataJsonApiLight.JsonApiAdapter`

// Initialize our Store
const store = new DataStore();

// Initialize our Adapter
const jsonApiAdapter = new JsonApiAdapter({
  // Same options as DSHttpAdapter
  // However, you should use before/after deserialize/serialize instead of serialize/deserialize
});

// Register the Adapter as the default one in the store
store.registerAdapter('jsonApi', jsonApiAdapter, { default: true })

Exemples

Use case

  • You can find examples of Mapper Definitions in test/resources.
  • Fake JsonAPI responses corresponding to those mapper can be found in test/api
  • Bootstrap of JSData + JsonAPI could be found in test/ds
  • Exemple of use could be found in test/unit

Define your mappers

JSData works with mappers which define the communication part and the way your resources are linked together

const UserMapper = window.store.defineMapper('User',{
  endpoint: 'users', // optional, it will default to `User`
  relations: {
    hasOne: {
      'UserProfile': {
        localField: 'profile',
        foreignKey: 'userId'
      }
    },
    hasMany: {
      'Article': {
        localField: 'articles',
        foreignKey: 'authorId'
      }
    },
    belongsTo: {
      'UserGroup': {
        localField: 'group',
        localKey: 'groupId'
      }
    }
  }
})

Fetch your data

UserMapper.findAll({ include: 'profile' }).then((records) => {
  console.log(records);
})

Once some records has been loaded they are also cached in the DataStore, you can access them synchronously with :

records = store.getAll('User')

Hooks

Sometime you want to be able to do some custom additional serialization / deserialization.

By using the adapter

  const jsonApiAdapter = new JsonApiAdapter({
    beforeDeserialize: function(mapper, data, opts) { return data; }
    afterDeserialize: function(mapper, data, opts) { return data; }
    beforeSerialize: function(mapper, data, opts) { return data; }
    afterSerialize: function(mapper, data, opts) { return data; }
  });

By using the mapper

  const UserMapper = store.defineMapper('User', {
    beforeDeserialize: function(mapper, data, opts) { return data; }
    afterDeserialize: function(mapper, data, opts) { return data; }
    beforeSerialize: function(mapper, data, opts) { return data; }
    afterSerialize: function(mapper, data, opts) { return data; }
  });

When doing requests

  store.findAll('User', {}, {
    beforeDeserialize: function(mapper, data, opts) { return data; }
    afterDeserialize: function(mapper, data, opts) { return data; }
  });

  store.update('User', {}, {
    beforeSerialize: function(mapper, data, opts) { return data; }
    afterSerialize: function(mapper, data, opts) { return data; }
  });

Options

Adapter options

beforeDeserialize, afterDeserialize, beforeSerialize, afterSerialize

Deserialization and serialization hooks, see above.

CRUD methods options

raw: boolean

Send back raw response

Eg. To retrieve JSONApi Meta :

store.findAll('User', {}, {
  raw: true
}).then((response) => {
  console.log(response.data); // Return the Records
  console.log(response.meta); // Return the JSONApi Metas
  console.log(response.rawData); // Return the full response (should be discarded as soon as possible to save memory)
})
  • Compatible with: all

forceReplace: boolean(false)

On update, force all fields to be sent even if they haven't been changed. It will switch from default PATCH http verb to PUT.

If some properties are passed to the update, only those will be sent. Those who has not changed compared to the record original properties will not be sent. Be careful, because it means, once the update made, the server will return saved datas, and it will erased possible properties that were changed on the record but not given to the update. Nothing wrong with that, it's the correct behavior, but you should know about this logic.

  • Compatible with: update, save

forceRelationshipsInAttributes: boolean(false)

On update, force all relationships data to be sent using attributes structure instead of default relationships within the resource object. Note it is not JsonAPI compliant, it is a convenient option to support some specific backends.

  • See #23
  • Compatible with: update, save

beforeDeserialize, afterDeserialize, beforeSerialize, afterSerialize

Deserialization and serialization hooks, see above.

Development Status

What is done

  • Deserialization, supporting hasMany, hasOne, belongsTo relationships
  • Meta handling
  • Serialization
  • Custom hooks
  • By default update PATCH changes instead of PUT the record

What may work

  • Error handling (need intensive testing)

What is remaining

  • ManyToMany

License

The MIT Licence (MIT)

Copyright (c) 2017 WIKODIT SAS

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.