Giter VIP home page Giter VIP logo

jsonapi-parse's Introduction

JSONAPI Parse

This library is currently complies and works with JSON API v1.0.

Install

npm install jsonapi-parse

API Reference

jsonapi.parse(input)

Option Description Default
input A JSON string or JavaScript object undefined

Parses the input provided if it follows the JSON API specification (v1.0). This library currently creates a new object for every nested resource object rather than pointing to the reference of the object form the included collection. This is in an effort to reduce difficult to trace bugs.

Currently it prevents circular references by keeping track of the "lineage" as it populates every new resource objects relationships. It will not set anything besides type and id for the related object.

Returns a new object with at least a data and jsonapi property. The data property should be the parsed version of the object graph included, and the jsonapi object should have an indicator for if it has been parsed and any other information the object contained previously.

Passing anything that is not a JSON string or JavaScript object will be returned as it was called with. Passing anything that does not conform to JSON API specification will also be returned as called with.

Example Usage

// JSON API structured object
var input = {
        data: [
            {
                id: '12klj',
                type: 'primary',
                attributes: { key: 'value', property: true }
            }
        ]
    },
    // JSON string of previous object
    stringified = JSON.stringify(input);

// Parsing a normal Javascript Object
window.jsonapi.parse(input);


// Parsing a JSON string
window.jsonapi.parse(stringified);

// Returns
// {
//     data: [ 
//         { id: '12klj', type: 'primary', key: 'value', property: true }
//     ],
//     jsonapi: { parsed: true }
// }

Build

gulp build

This task currently concatenates, compresses (uglify), and moves the source files into the dist directory.

TODO

  • Add tests for the output of the parse method
  • Setup Travis CI for running the tests
  • Add npm package for parsing with Node

jsonapi-parse's People

Contributors

grahamlyus avatar mrkmiller avatar pjfreeze avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

jsonapi-parse's Issues

Please don't bind to global

I haven't seen a package that binds to window in a long time. Better to make this a proper JS module, and let us do the binding ourself. It's 2021. We have great bundler tools now.

Unable to getMatchingRecord if record is related to multiple entities

Hi there, thanks for putting this together! From my initial tests this thing is very fast. Loving it. I've been looking to integrate this with some of the work we're doing and ran into an issue. I'm hoping you can provide some advice.

The method getMatchingRecord has logic to determine if a relationship has been marked as a parent (already populated with data). If it has, rather than populating it's related fields again and returning that, it returns the relationship itself. I see why the logic is written this way. It prevents an infinite loop. Especially handy for potentially infinitely nested relationships.

The issue that I've run into is, I've got multiple examples where a relationship could be related to multiple things. So the first time it goes through this, it returns the populated relationship, but subsequent times it returns the plain relationship. For example:

Say you have a group that can have any number of users. And say you can have many groups. Users may belong to more than one group. Now let's say you have a user and this user has a relationship (like an avatar, or whatever else).

If this user is a member of multiple groups, the first group gets the user populated (and at that time marked as a parent, since they have relationships). But when we run through the second group the method will return the relationship when it runs into the same user again. Looking for any advice you can give on how to handle a situation like this. Thank you!

Missing `links` property on top level parsed result

The optional links object on the top level of the response is missing from the parsed result. The links object should be added to the parsed result, but not modified in any way from the original version.

A pre-parsed object

{
  "links": {
    "next": "https://example.com?page=2"
  },
  "data": [
    { "id": "1", "type": "person", "attributes": { "name": "Person 1" } }
  ],
  "included": [],
  "meta": {}
}

Should look like this when parsed

{
  "links": {
    "next": "https://example.com?page=2"
  },
  "data": [
    { "id": "1", "type": "person", "name": "Person 1" }
  ],
  "included": [],
  "meta": {}
}

Missing `type` property from parsed objects

After parsing, I'm missing the type property on my entities. I'm wondering if all the non-attributes should be attached at something like meta so they're not completely lost, but don't collide with the attributes.

e.g.

{
  "data": [
    {
      "id": 1,
      "type": "person",
      "links": {},
      "attributes": {
        "name": "fred"
      }
    }
  ]
}

becomes

{
  "data": [
    {
      "id": 1,
      "name": "fred",
      "meta": {
        "type": "person",
        "links": {}
       }
    },
  ]
}

All `attributes.id` & `attributes.type` will be overridden by `id` & `type`

This is a very useful module but I have a JSONAPI response have data like this:

    "type": "articles",
    "id": "sf4379f1-bd3b-414d-8a17-191e17619d11",
    "attributes": {
      "id": "a_test_article_id"
    },

Then what I get will be:

    "type": "articles",
    "id": "sf4379f1-bd3b-414d-8a17-191e17619d11"

The attributes id is gone. That is caused by flatten function https://github.com/mysidewalk/jsonapi-parse/blob/master/src/jsonapi.js#L171

        return extend(
            {},
            { links: record.links, meta: meta },
            record.attributes,
            { id: record.id, type: record.type }
        );

That extend function merged all values by removing duplicated keys.
One question, do we really need to flatten the data object? What is the purpose?
In my case, there is a id field inside attributes but I can't get it after flatten.

Or if we have to flatten it, what about add attributes_id & attributes_type if there are such field inside attributes? Simply can be fixed by below:

    function flatten(record, extraMeta) {
        var meta = extend({}, record.meta, extraMeta)

       // Add this
        if (record.attributes.id) {
            record.attributes.attributes_id = record.attributes.id
        }

        if (record.attributes.type) {
            record.attributes.attributes_type = record.attributes.type
        }
       // End

        return extend(
            {},
            { links: record.links, meta: meta },
            record.attributes,
            { id: record.id, type: record.type }
        );
    }

So the attributes.id & attributes.type gets preserved.
Thanks.

Fetching included entity without attributes error

Our data model has a middle table without any exposed attributes. e.g. order_item -> reservation -> serial
I need the serial number, but loading the serial entity as included entity, results in an error.

jsonapi.js (line 125)
Tries to add field on undefined:
record.attributes[property] = getMatchingRecord whereas attributes of record reservation is undefined. The only field ist the serial reference, which is not an attribute.

Preserve data from relationships

I have a relationship which returns some data in it. This data is not preserved and merged with the data from the resulting "includes".

"relationships": {
  "field_primary_image": {
    "data": {
      "type": "file--file",
      "id": "1234",
      "meta": {
        "alt": "My alt text",
        "title": "",
        "width": "1920",
        "height": "1080"
      }
    }
  }
}

The resulting field_primary_image contains the file/image data from the "includes" but does not have the meta data from the original relationships object with my alt text.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.