Can't get related resource using JsonApiFramework

211 views Asked by At

Using the https://github.com/scott-mcdonald/JsonApiFramework framework

I'm sending the following PATCH from my UI:

{"data":{"id":"4221fe2f-ca7b-425d-b45a-a09f4936a22b","attributes":{"contact-trade-name":"asdad","contact-name":"aasd","contact-phone":"asdad","contact-email":"[email protected]","created-date":"2016-12-19T14:07:59.833","status":"AwaitingBillData"},"relationships":{"share-user":{"data":{"type":"users","id":"5078b2ee-2348-44f5-95a0-3c14c2ad2b1d"}}},"type":"jobs"}}

And on my server i am doing the following:

using (var documentContext = new DocumentContext(HttpContext.Current.Request.Url, document)) { var job = documentContext.GetResource<Job>(); var relationships = documentContext.GetResourceRelationships(job); var shareUserRel = relationships["share-user"]; var shareUser = documentContext.GetRelatedResource<Data.ServiceModel.User>(shareUserRel); }

however shareUser is always null

shareUserRel has the following when i inspect it:

{ResourceIdentifier [type=users id=5078b2ee-2348-44f5-95a0-3c14c2ad2b1d]}

if that helps.

Is there anything glaringly obvious that i might be doing wrong?

1

There are 1 answers

0
Scott McDonald On BEST ANSWER

To format the json:api document for readability, it looks like this:

{
  "data": {
    "type": "jobs"
    "id": "4221fe2f-ca7b-425d-b45a-a09f4936a22b",
    "attributes": {
      "contact-trade-name": "asdad",
      "contact-name": "aasd",
      "contact-phone": "asdad",
      "contact-email": "[email protected]",
      "created-date": "2016-12-19T14:07:59.833",
      "status": "AwaitingBillData"
    },
    "relationships": {
      "share-user": {
        "data": {
          "type": "users",
          "id": "5078b2ee-2348-44f5-95a0-3c14c2ad2b1d"
        }
      }
    }
  }
}

The reason GetRelatedResource is returning null is you are asking the document context to return the actual included user resource in the document which doesn't exist in the document.

When a client sends this type of json:api document in a PATCH you are instructing the server to update the job resource with the given attributes and associate this job resource to an existing user resource which is specified in the to-one resource linkage.

Something more correct once you have the relationship object in your example is the following:

if (shareUserRel.IsResourceLinkageNullOrEmpty())
{
  // Clear any linkage between the job resource and any current user
  ...
}
else
{
  var shareUserResourceIdentifier = shareUserRel.GetToOneResourceLinkage();
  // Create linkage between the job resource and existing user identified
  // by shareUserResourceIdentifier
  ...
}

Now how you handle the '...' depends on your data layer.