jsonapi-serializer icon indicating copy to clipboard operation
jsonapi-serializer copied to clipboard

Empty relationship objects still being made when data is null

Open dhenson02 opened this issue 1 year ago • 0 comments

Returned data in a dataset comes back as null but the relationship object is still being created.

Examples:

// when data exists, this works:
      "relationships": {
        "notes": {
          "data": [
            {
              "type": "notes",
              "id": "01929cc3-37f9-7461-8661-a76256691082"
            }
          ]
        }

// when data is null, this is what is returned:
      "relationships": {
        "notes": { "data": null }
      }

The second one will fail validation and needs to be removed entirely if nothing in the relationship in order to pass.

Suggestions on how to do this with this library are welcome. I am currently just manually removing them with the following:

function fixRelationships ( serializedResponse ) {
    const withoutEmptyRelationships = serializedResponse.data.map(d => {
        if ( "relationships" in d ) {
            const newRel = Object.keys(d.relationships).reduce(( obj, key ) => {
                const rel = d.relationships[ key ];
                if ( rel.data || rel.links || rel.meta ) {
                    obj[ key ] = rel;
                }
                return obj;
            }, {});
            if ( Object.keys(newRel).length > 0 ) {
                d.relationships = newRel;
            }
            else {
                delete d.relationships;
            }
        }
        return d;
    });

    return {
        ...serializedResponse,
        data: withoutEmptyRelationships,
    };
}

dhenson02 avatar Oct 24 '24 14:10 dhenson02