Example #1
0
        private Resource BuildPatch(object model)
        {
            var originalResource = ModelRegistry.GetResource(model);

            var modelRtlns    = ModelRegistry.GetRelationshipValues(model) ?? new Dictionary <string, Relationship>();
            var originalRtlns = originalResource.Relationships ?? new Dictionary <string, Relationship>();
            var patchRtlns    = modelRtlns.Where(modelRltn =>
            {
                originalRtlns.TryGetValue(modelRltn.Key, out var ogRtln);
                // JToken.DeepEquals does not work here
                return(!JsonComparer.Equals(ogRtln?.Data, modelRltn.Value?.Data));
            }).ToDictionary(x => x.Key, x => x.Value);

            var modelAttrs    = ModelRegistry.GetAttributeValues(model) ?? new JObject();
            var originalAttrs = originalResource.Attributes ?? new JObject();

            var modelMetas    = ModelRegistry.GetMetaValues(model) ?? new JObject();
            var originalMetas = originalResource.Meta ?? new JObject();
            // Links are not patched

            var patchAttrs = (JObject)JsonDiff.ReducePatch(originalAttrs, modelAttrs);
            var patchMetas = (JObject)JsonDiff.ReducePatch(originalMetas, modelMetas);

            if (patchAttrs == null &&
                !patchRtlns.Any() &&
                patchMetas == null)
            {
                // Nothing to update
                return(null);
            }
            return(new Resource
            {
                Id = originalResource.Id,
                Type = originalResource.Type,
                Attributes = patchAttrs,
                Relationships = patchRtlns.Any() ? patchRtlns : null,
                Meta = patchMetas
            });
        }