UNPKG

js-data-jsonapi

Version:
11 lines 28.3 kB
/*! * js-data-jsonapi * @version 0.0.0-alpha.21 - Homepage <https://github.com/BlairAllegroTech/js-data-jsonapi> * @author Blair Jacobs * @copyright (c) 2016-2017 Blair Jacobs * @license MIT <https://github.com/BlairAllegroTech/js-data-jsonapi/blob/master/LICENSE> * * @overview JsonApi adapter for js-data. */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("js-data"),require("js-data-http")):"function"==typeof define&&define.amd?define(["js-data","js-data-http"],t):"object"==typeof exports?exports.DSJsonApiAdapter=t(require("js-data"),require("js-data-http")):e.DSJsonApiAdapter=t(e.JSData,e.DSHttpAdapter)}(this,function(e,t){return function(e){function t(r){if(i[r])return i[r].exports;var n=i[r]={exports:{},id:r,loaded:!1};return e[r].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var i={};return t.m=e,t.c=i,t.p="",t(0)}([function(e,t,i){"use strict";function r(e){return o.MetaData.TryGetMetaData(e)}var n=i(1),a=i(2),o=i(3);t.JsonApi=i(4);var s=204,l=function(){function e(e){var t=this;if(this.DSUtils=n.DSUtils,this.serialize=this.SerializeJsonResponse,this.deserialize=this.DeSerializeJsonResponse,e&&e.adapter)this.adapter=e.adapter,this.DSUtils.deepMixIn(this.defaults,e);else{var i=a;this.adapter=new i(e)}this.defaults.jsonApi=e.jsonApi||{},this.DSUtils.deepMixIn(this.defaults.jsonApi,{usePATCH:!0,updateRelationships:!1}),this.DSUtils.deepMixIn(this.defaults.jsonApi,e.jsonApi),this.adapterGetPath=this.adapter.getPath,this.adapterHTTP=this.adapter.HTTP,this.adapter.getPath=function(e,i,r,n){return t.getPath(e,i,r,n)},this.adapter.HTTP=function(e){return t.HTTP(e)}}return Object.defineProperty(e.prototype,"defaults",{get:function(){return this.adapter.defaults},enumerable:!0,configurable:!0}),e.prototype.SerializeJsonResponse=function(e,t,i){var r=new o.SerializationOptions(e);return o.JsonApiHelper.Serialize(r,t,i)},e.prototype.DeSerializeJsonResponse=function(e,t){var i=this;if(o.JsonApiHelper.ContainsJsonApiContentTypeHeader(t.headers))if(t.data.errors)t.data=o.JsonApiHelper.FromJsonApiError(t.data);else{if(t.status!==s&&t.data.data)if(this.DSUtils.isArray(t.data.data))this.DSUtils.forEach(t.data.data,function(t){t.type!==e.name&&i.defaults.log&&(i.defaults.log("Warning: Json Api resource name missmatch, JsonApi:"+(t.type||"missing")+", js-data:",[e.name]),t.type=e.name)});else{var r=t.data.data;r.type!==e.name&&this.defaults.log&&(this.defaults.log("Warning: Json Api resource name missmatch, JsonApi:"+(t.data.data.type||"missing")+", js-data:",e.name),r.type=e.name)}var n=o.JsonApiHelper.DeSerialize(new o.SerializationOptions(e),t.data);t.data=n.data}return t},e.prototype.HandleError=function(e,t,i){return t.deserialize(e,i)},e.prototype.getPath=function(e,t,i,r){if(o.JsonApiHelper.ContainsJsonApiContentTypeHeader(this.DSUtils.get(r,"headers"))){var n;this.DSUtils._sn(i)?n=t.get(i):this.DSUtils._o(i)&&(n=i);var a=this.DSUtils.get(r,"jsonApi.jsonApiPath");if(a)r.params.__jsDataJsonapi&&delete r.params.__jsDataJsonapi;else if("update"===e){var s=o.MetaData.TryGetMetaData(n);s&&s.selfLink&&(a=s.selfLink)}var l=r.basePath||this.defaults.basePath||t.basePath;return a?l&&a.substr(0,l.length)===l?a:this.DSUtils.makePath(l,a):this.adapterGetPath.apply(this.adapter,[e,t,i,r])}return this.adapterGetPath.apply(this.adapter,[e,t,i,r])},e.prototype.configureSerializers=function(e,t){var i=this,r={};this.DSUtils.deepMixIn(r,this.DSUtils.copy(this.defaults)),this.DSUtils.deepMixIn(r,t),this.DSUtils.deepMixIn(r,e),r.headers=r.headers||{},o.JsonApiHelper.AddJsonApiAcceptHeader(r.headers),o.JsonApiHelper.AddJsonApiContentTypeHeader(r.headers);var n=r.serialize||this.defaults.serialize;n?r.serialize=function(e,t){return n(e,i.serialize(e,t,r))}:r.serialize=function(e,t){return i.serialize(e,t,r)};var a=r.deserialize||this.defaults.deserialize;return a?r.deserialize=function(e,t){return a(e,i.deserialize(e,t))}:r.deserialize=function(e,t){return i.deserialize(e,t)},r},e.prototype.HTTP=function(e){var t=this;return this.adapterHTTP.apply(this.adapter,[e]).then(function(i){return o.JsonApiHelper.ContainsJsonApiContentTypeHeader(t.DSUtils.get(e,"headers"))&&(i.status!==s||!e.method||"put"!==e.method&&"patch"!==e.method||e.data&&(i.status=200,i.statusText="Ok",i.headers=i.headers||{},o.JsonApiHelper.AddJsonApiContentTypeHeader(i.headers),i.data=e.data)),i})},e.prototype.create=function(e,t,i){var r=this,n=this.configureSerializers(i);return t[e.idAttribute]&&(t[e.idAttribute]=t[e.idAttribute].toString()),this.adapter.create(e,t,n).then(null,function(t){return r.defaults.log&&r.defaults.log("create Failure",t),r.DSUtils.Promise.reject(r.HandleError(e,n,t))})},e.prototype.destroy=function(e,t,i){var r=this,n=t.toString(),a=this.configureSerializers(i);return this.adapter.destroy(e,n,a).then(null,function(t){return r.DSUtils.Promise.reject(r.HandleError(e,a,t))})},e.prototype.destroyAll=function(e,t,i){var r=this,n=this.configureSerializers(i);return this.adapter.destroyAll(e,t,n).then(null,function(t){return r.DSUtils.Promise.reject(r.HandleError(e,n,t))})},e.prototype.find=function(e,t,i){var r=this,n=t.toString(),a=this.configureSerializers(i);return this.adapter.find(e,n,a).then(null,function(t){return r.DSUtils.Promise.reject(r.HandleError(e,a,t))})},e.prototype.findAll=function(e,t,i){var r=this,n=this.configureSerializers(i);return this.adapter.findAll(e,t,n).then(null,function(t){return r.DSUtils.Promise.reject(r.HandleError(e,n,t))})},e.prototype.update=function(e,t,i,r){var n=this,a=t.toString();if(i[e.idAttribute]){if(i[e.idAttribute].toString()!==a)throw new Error('Json Api update expected supplied id and the primary key attribute "'+e.idAttribute+'" to be the same, you may have called update on the wrong id?')}else i[e.idAttribute]=a;var o=this.configureSerializers(r);return o.jsonApi.usePATCH===!1?o.jsonApi.updateRelationships=void 0===o.jsonApi.updateRelationships?!0:o.jsonApi.updateRelationships:(o.method=o.method||"patch",o.changes=void 0===o.changes?!0:o.changes),this.adapter.update(e,a,i,o).then(null,function(t){return n.DSUtils.Promise.reject(n.HandleError(e,o,t))})},e.prototype.updateAll=function(e,t,i,r){var n=this,a=this.configureSerializers(r);return a.jsonApi.usePATCH===!1?a.jsonApi.updateRelationships=void 0===a.jsonApi.updateRelationships?!0:a.jsonApi.updateRelationships:(a.method=a.method||"patch",a.changes=void 0===a.changes?!0:a.changes),this.adapter.updateAll(e,t,i,a).then(null,function(t){return n.DSUtils.Promise.reject(n.HandleError(e,a,t))})},e}();t.JsonApiAdapter=l,t.TryGetMetaData=r,t.version={full:"<%= pkg.version %>",major:parseInt("<%= major %>",10),minor:parseInt("<%= minor %>",10),patch:parseInt("<%= patch %>",10),alpha:"<%= alpha %>",beta:"<%= beta %>"}},function(t,i){t.exports=e},function(e,i){e.exports=t},function(e,t,i){"use strict";function r(e,t){console&&console.log(e,t)}var n=i(1),a=i(4);t.JSONAPI_META="$_JSONAPIMETA_";var o="application/vnd.api+json";t.JSONAPI_RELATED_LINK="related",t.JSONAPI_PARENT_LINK="parent",t.JSONAPI_SELF_LINK="self";var s="belongsTo",l="hasMany",p="hasOne",u=n.DSUtils,h=function(){function e(e,t){this.type=e,this.url=t}return e}(),d=function(){function e(e){this.selfType=e,this.selfLink=null,this.isJsonApiReference=!0,this.relationships={},this.links={},this.referenceCount=0}return e.prototype.WithRelationshipLink=function(e,t,i,r){return this.relationships[e]=this.relationships[e]||{},this.relationships[e][t]=new h(i,r),this},e.prototype.WithLink=function(e,t,i){var r=new h(e,t);return r.meta=i,this.links[e]=r,this},e.prototype.getLinks=function(e){return this.links[e]},e.prototype.incrementReferenceCount=function(){return this.referenceCount++,this.referenceCount},e.prototype.getRelationshipLink=function(e,t){return this.relationships[e]?this.relationships[e][t]:void 0},e.TryGetMetaData=function(e){return e?u.get(e,t.JSONAPI_META):void 0},e}();t.MetaData=d;var f=function(){function e(e,t){if(this.type=e,this.id=t,!e||!t)throw new Error("Type or Id missing")}return e.prototype.WithForeignKey=function(e,t,i){return this.keyName=e,this.keyValue=t,this.keyType=i,this},e}(),c=function(){function e(e){this.resourceDef=e}return Object.defineProperty(e.prototype,"type",{get:function(){return this.resourceDef.name},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"idAttribute",{get:function(){return this.resourceDef.idAttribute},enumerable:!0,configurable:!0}),e.prototype.relationType=function(){return this.resourceDef.type},e.prototype.def=function(){return this.resourceDef},e.prototype.getResource=function(t){var i=this.resourceDef.getResource(t);return i?new e(i):null},e.prototype.getBelongsToRelation=function(e,t){return this.resourceDef.relations&&this.resourceDef.relations.belongsTo?t?this.resourceDef.relations.belongsTo[e]:this.resourceDef.relations.belongsTo[e]:null},e.prototype.getParentRelationByLocalKey=function(e){var t=null;if(this.resourceDef.relations&&this.resourceDef.relations.belongsTo)for(var i in this.resourceDef.relations.belongsTo)this.resourceDef.relations.belongsTo[i]&&u.forEach(this.resourceDef.relations.belongsTo[i],function(i){return i.localKey===e?(t=i,!1):void 0});return t},e.prototype.getParentRelationByLocalField=function(e){var t=null;if(this.resourceDef.relations&&this.resourceDef.relations.belongsTo)for(var i in this.resourceDef.relations.belongsTo)this.resourceDef.relations.belongsTo[i]&&u.forEach(this.resourceDef.relations.belongsTo[i],function(i){return i.localField===e?(t=i,!1):void 0});return t},e.prototype.getChildRelation=function(e){var t=this.getChildRelations(e);return t&&t[0]?t[0]:null},e.prototype.getChildRelationWithLocalField=function(e,t){var i=t.toLowerCase(),r=this.getChildRelations(e),n=null;return u.forEach(r,function(e){return e.localField===t||e.localField===i?(n=e,!1):void 0}),n},e.prototype.getChildRelationWithForeignKey=function(e,t){var i=t.toLowerCase(),r=this.getChildRelations(e),n=null;return u.forEach(r,function(e){return e.foreignKey===t||e.foreignKey===i?(n=e,!1):void 0}),n},e.prototype.enumerateAllChildRelations=function(e){u.forEach(this.resourceDef.relationList,function(t,i,r){return t.type===l||t.type===p?e(t,i,r):void 0})},e.prototype.enumerateAllParentRelations=function(e){u.forEach(this.resourceDef.relationList,function(t,i,r){return t.type===s?e(t,i,r):void 0})},e.prototype.enumerateRelations=function(e){u.forEach(this.resourceDef.relationList,function(t,i,r){return e(t,i,r)})},e.prototype.getChildRelations=function(e){if(this.resourceDef.relations){var t=e.toLowerCase(),i=[],n=this.resourceDef.relationList;return u.forEach(n,function(n){n.type!==l&&n.type!==p||(e===n.relation?i.push(n):t===n.relation&&(i.push(n),r("Relation Case Insensitive match made of "+e,i)))}),i}return null},e.prototype.getRelationByLocalField=function(e){var t=e.toLowerCase(),i=this.resourceDef.relationList,r=null;return u.forEach(i,function(i){return i.localField===e||i.localField===t?(r=i,!1):void 0}),r},e}();t.SerializationOptions=c;var y=function(){function e(e,t){this.data=e,this.response=t}return e}(),A=function(){function e(){}return e.MergeMetaData=function(e,t){if(e){var i=d.TryGetMetaData(t);if(!i)throw new Error("MergeMetaData failed, target object missing meta data Type:"+e.name);var r=t[e.idAttribute],n=e.get(r);if(n){var a=d.TryGetMetaData(n);a&&(i.isJsonApiReference=i.isJsonApiReference||a.isJsonApiReference)}}},e.ContainsHeader=function(e,t,i){if(e)for(var r in e)if(r.toLocaleLowerCase()===t.toLocaleLowerCase()){var n=e[r];if(n.toLocaleLowerCase().indexOf(i)>-1)return!0}return!1},e.ContainsJsonApiContentTypeHeader=function(t){return e.ContainsHeader(t,"Content-Type",o)},e.AddJsonApiContentTypeHeader=function(e){e["Content-Type"]=o},e.AddJsonApiAcceptHeader=function(e){e.Accept=o},e.FromJsonApiError=function(t){var i;return t.errors?(i=new a.JsonApiRequest,u.isArray(t.errors)?u.forEach(t.errors,function(e){i.WithError(u.deepMixIn(new a.JsonApiError,e))}):i.WithError(u.deepMixIn(new a.JsonApiError,t.errors))):i=e.CreateInvalidResponseError(t),i},e.Serialize=function(e,t,i){var r=this,n=new a.JsonApiRequest;return u.isArray(t)?(n.data=new Array,u.forEach(t,function(t){n.WithData(r.ObjectToJsonApiData(e,t,i))})):n.data=this.ObjectToJsonApiData(e,t,i),n},e.DeSerialize=function(i,r){var n=this;if(null===r.data)return new y([],null);if(u.isArray(r.data)&&0===r.data.length)return new y([],null);var o=new a.JsonApiRequest;if(r.data)if(u.isArray(r.included)&&u.forEach(r.included,function(e){n.NormaliseLinkFormat(e.links);for(var t in e.relationships)if(e.relationships[t]){n.NormaliseLinkFormat(e.relationships[t].links);var i=u.isArray(e.relationships[t].data);e.relationships[t]=u.deepMixIn(new a.JsonApiRelationship(i),e.relationships[t])}o.WithIncluded(u.deepMixIn(new a.JsonApiData("unknown"),e))}),u.isArray(r.data))u.forEach(r.data,function(e){n.NormaliseLinkFormat(e.links);for(var t in e.relationships)if(e.relationships[t]){n.NormaliseLinkFormat(e.relationships[t].links);var i=u.isArray(e.relationships[t].data);e.relationships[t]=u.deepMixIn(new a.JsonApiRelationship(i),e.relationships[t])}o.WithData(u.deepMixIn(new a.JsonApiData(""),e))});else{var l=r.data;this.NormaliseLinkFormat(l.links);for(var p in l.relationships)if(l.relationships[p]){this.NormaliseLinkFormat(l.relationships[p].links);var h=u.isArray(l.relationships[p].data);l.relationships[p]=u.deepMixIn(new a.JsonApiRelationship(h),l.relationships[p])}o.WithSingleData(u.deepMixIn(new a.JsonApiData(""),r.data))}if(r.links){this.NormaliseLinkFormat(r.links);for(var c in r.links)r.links[c]&&o.AddLink(c,r.links[c])}var A={},v={},g={};if(u.isArray(o.data))u.forEach(o.data,function(e){A[e.type]=A[e.type]||{},A[e.type][e.id]=n.DeserializeJsonApiData(i,e,g);var t=d.TryGetMetaData(A[e.type][e.id]);t.incrementReferenceCount()});else{var m=o.data;if(m){A[m.type]=A[m.type]||{},A[m.type][m.id]=this.DeserializeJsonApiData(i,m,g);var R=d.TryGetMetaData(A[m.type][m.id]);R.incrementReferenceCount()}}e.AssignLifeTimeEvents(i.def()),u.forEach(o.included,function(t){var r=i.getResource(t.type);v[t.type]=v[t.type]||{},v[t.type][t.id]=n.DeserializeJsonApiData(r,t,g),e.AssignLifeTimeEvents(r.def())});var D=function(e){var t=v[e.type]?v[e.type][e.id]:A[e.type]?A[e.type][e.id]:g[e.type]?g[e.type][e.id]:null;return t},w=function(r){if(r.constructor===f){var n=r,a=D(n);if(a){n.keyName&&(a[n.keyName]=n.keyValue);var o=d.TryGetMetaData(a);return 1===o.incrementReferenceCount()?a:void 0}var s={};n.keyName&&(s[n.keyName]=n.keyValue);var l=i.getResource(n.type),p=new d(n.type);return p.isJsonApiReference=!0,s[t.JSONAPI_META]=p,s[l.idAttribute]=n.id,e.AssignLifeTimeEvents(l.def()),s}return r},J=function(r,n,a){var o=r[n];if(o&&o.constructor===f){var l=o,p=D(l);if(p){var u=d.TryGetMetaData(p);if(1===u.incrementReferenceCount())return p;if(l.keyName)p[l.keyName]=l.keyValue;else{var h=a.getParentRelationByLocalField(n);h&&h.type===s&&(r[h.localKey]=l.id)}return}p={};var c=i.getResource(l.type);l.keyName&&(p[l.keyName]=l.keyValue);var y=new d(l.type);return y.isJsonApiReference=!0,p[t.JSONAPI_META]=y,p[c.idAttribute]=l.id,e.AssignLifeTimeEvents(c.def()),p}return r[n]};this.RelationshipVisitor(A,i,w,J),this.RelationshipVisitor(v,i,w,J),this.RelationshipVisitor(g,i,w,J);var E=function(t){var r=i.getResource(t);if(!r)throw new Error("Unknow type:"+t);e.AssignLifeTimeEvents(r.def())};if(this.DataTypeVisitor(A,E),this.DataTypeVisitor(v,E),this.DataTypeVisitor(g,E),A){var k=[];if(u.isArray(o.data))return u.forEach(o.data,function(e){A[e.type]&&A[e.type][e.id]&&k.push(A[e.type][e.id])}),new y(k,o);if(!o.data)return new y(null,o);var T=o.data;if(A[T.type]&&A[T.type][T.id])return new y(A[T.type][T.id],o)}},e.RelationshipVisitor=function(e,t,i,r){if(e)for(var n in e)if(e[n])for(var a in e[n])if(e[n][a]){var o=e[n][a];for(var s in o)if(u.isArray(o[s])){u.forEach(o[s],function(e,t,r){var n=i(e);r[t]=n});for(var l=o[s].length;l>=0;l--)o[s][l]||o[s].splice(l,1);0===o[s].length&&delete o[s]}else{var p=t.getResource(n),h=r(o,s,p);void 0!==h?o[s]=h:delete o[s]}}},e.DataTypeVisitor=function(e,t){for(var i in e)i&&t(i)},e.CreateInvalidResponseError=function(e){var t=new a.JsonApiRequest,i=new a.JsonApiError;return i.title="Invalid response",i.detail="Response is incorrectly formed: "+JSON.stringify(e),t.WithError(i),t},e.ObjectToJsonApiData=function(e,i,r){if(!e.type)throw new Error("Type required within options");var n=new a.JsonApiData(e.type);if(i[e.idAttribute]&&n.WithId(i[e.idAttribute]),r.changes&&i[e.idAttribute]){var o=i[e.idAttribute];if(e.def().hasChanges(o)){var s=e.def().changes(o);u.forOwn(s.added,function(i,r){r!==e.idAttribute&&r!==t.JSONAPI_META&&r.indexOf("$")<0&&n.WithAttribute(r,i)}),u.forOwn(s.changed,function(i,r){r!==e.idAttribute&&r!==t.JSONAPI_META&&r.indexOf("$")<0&&n.WithAttribute(r,i)}),u.forOwn(s.removed,function(i,r){r!==e.idAttribute&&r!==t.JSONAPI_META&&r.indexOf("$")<0&&n.WithAttribute(r,null)})}}else u.forOwn(i,function(i,r){r!==e.idAttribute&&r!==t.JSONAPI_META&&r.indexOf("$")<0&&n.WithAttribute(r,i)});return r.jsonApi.updateRelationships===!0&&e.enumerateAllChildRelations(function(t){var r=e.getResource(t.relation);if(t.type===l){var o=new a.JsonApiRelationship(!0),s=u.get(i,t.localField);s&&u.forEach(s,function(e){o.WithData(t.relation,e[r.idAttribute])}),n.WithRelationship(t.localField,o)}if(t.type===p){var o=null,h=u.get(i,t.localField);h&&(o=new a.JsonApiRelationship(!1).WithData(t.relation,h[r.idAttribute])),n.WithRelationship(t.localField,o)}return!0}),n.attributes&&e.enumerateRelations(function(e){var t=e.localKey||e.localKeys;return t&&u.get(n.attributes,t)&&delete n.attributes[t],!0}),n},e.DeserializeJsonApiData=function(i,r,n){if(!i)throw new Error("Missing Serialization Options, indicates possible missing jsData resource: "+r.type);var a=u.copy(r.attributes||{}),o=new d(r.type);if(o.isJsonApiReference=!1,o.selfLink=r.GetSelfLink(),!r.id)throw new Error('Missing required "id" property in JsonApi response');if(a[i.idAttribute]=r.id.toString(),!r.type)throw new Error('Missing required "type" property in JsonApi response');e.setParentIds(i,r,a,o);for(var s in r.relationships)if(r.relationships[s]){var h=r.relationships[s],c=i.getRelationByLocalField(s);if(!c)throw new Error("MISSING: Relationship definition on js-data resource, Name:"+i.type+", failed to load relationship named: "+s+". Your js-data store configuration does not match your jsonapi data structure");if(c.type===l||c.type===p){var y=h.FindLinkType(t.JSONAPI_RELATED_LINK);y&&o.WithRelationshipLink(c.localField,t.JSONAPI_RELATED_LINK,c.relation,y);var A=h.FindLinkType(t.JSONAPI_SELF_LINK);A&&o.WithRelationshipLink(c.localField,t.JSONAPI_SELF_LINK,c.relation,A);var v=h.data&&(!u.isArray(h.data)||u.isArray(h.data)&&h.data.length>0);if(v){var g=null,m=u.isArray(h.data)?h.data[0].type:h.data.type;if(c=i.getChildRelationWithLocalField(m,s),!c&&i.def().meta&&i.def().meta[s]){var R=i.def().meta[s],D=i.getResource(R.joinType);if(c=i.getChildRelationWithLocalField(R.joinType,s),c.type!==l)throw new Error("Expected relationship Named:"+s+"on type:"+i.type+" with many-to-many meta data to be a to many relationship.");var w=D.getBelongsToRelation(R.type);if(!w||!w[0])throw new Error('Expected Many-To-Many Joining table to have a "belongsTo" relation of type:'+R.type+" as defined in meta data of type:"+r.type);var J={idAttribute:D.idAttribute,type:D.type,dataLocalField:c.localField,dataForeignKey:c.foreignKey,joinTypeDef:D};g=function(e,i){var a=r.type>e.type?r.id+e.id:e.id+r.id;n[J.type]=n[J.type]||{};var o=J.joinTypeDef.getParentRelationByLocalKey(J.dataForeignKey);if(!o)throw new Error('No "BelongsTo" relationship found on joining table '+J.joinTypeDef.type+" with field name:"+J.dataForeignKey);if(n[J.type][a]){var s=n[J.type][a];s[o.localKey]=r.id,s[o.localField]=new f(r.type,r.id)}else{var l=new d(J.type);l.isJsonApiReference=!1;var p={};p[J.idAttribute]=a,p[o.localKey]=r.id,p[o.localField]=new f(r.type,r.id),l.selfLink=i+"/"+a,p[t.JSONAPI_META]=l,n[J.type][a]=p}return new f(J.type,a).WithForeignKey(J.dataForeignKey,r.id,r.type)}}if(!c)throw new Error("MISSING: Relationship definition on js-data resource, Name:"+i.type+", failed to load relationship named: "+s+". Your js-data store configuration does not match your jsonapi data structure");o.WithRelationshipLink(c.localField,t.JSONAPI_RELATED_LINK,c.relation,h.FindLinkType(t.JSONAPI_RELATED_LINK));var E=c.localField,k=c.foreignKey,T=c.type;if(!E)throw new Error("ERROR: Incorrect js-data, relationship definition on js-data resource, Name:"+i.type+"Relationship Name:"+c.relation+'relationship requires "localField" parameter to be configured');if(T===l){if(!k&&!c.localKeys)throw new Error("ERROR: Incorrect js-data, relationship definition on js-data resource, Name:"+i.type+"Relationship Name:"+c.relation+'A "hasMany" relationship requires either "foreignKey" or "localKeys" to be configured');if(k&&c.localKeys)throw new Error("ERROR: Ambiguous js-data, relationship definition on js-data resource, Name:"+i.type+"Relationship Name:"+c.relation+'A "hasMany" relationship has both localKeys and foreignKeys configured, use either "foreignKey" or "localKeys" but not BOTH')}else{if(!k&&!c.localKey)throw new Error("ERROR: Incorrect js-data, relationship definition on js-data resource, Name:"+i.type+"Relationship Name:"+c.relation+'A "hasOne" relationship requires either "foreignKey" or "localKey" to be configured');if(k&&c.localKey)throw new Error("ERROR: Ambiguous js-data, relationship definition on js-data resource, Name:"+i.type+"Relationship Name:"+c.relation+'A "hasOne" relationship has both localKey and foreignKey configured, use either "foreignKey" or "localKey" but not BOTH')}if(u.isArray(h.data)){var L=new Array,S=new Array;u.forEach(h.data,function(e){if(null==g){var t=e.id,i=e.type,n=new f(i,t);c.foreignKey?n.WithForeignKey(c.foreignKey,r.id,r.type):L.push(t),S.push(n)}else{var n=g(e,h.FindLinkType("self"));L.push(t),S.push(n)}}),c.localKeys&&(a[c.localKeys]=L),a[E]=S}else{var b=h.data,j=b.id,I=b.type,N=new f(I,j);c.foreignKey?N.WithForeignKey(c.foreignKey,r.id,r.type):a[c.localKey]=j,a[E]=N}}}}if(r.links){this.NormaliseLinkFormat(r.links);for(var P in r.links)if(r.links[P]){var M=r.links[P];o.WithLink(P,M.href,M.meta)}}return a[t.JSONAPI_META]=o,a},e.setParentIds=function(e,i,r,n){if(i.type&&i.GetSelfLink&&i.GetSelfLink()){var a=i.GetSelfLink().split("/");e.enumerateAllParentRelations(function(i){var o=e.getResource(i.relation),s=a.lastIndexOf(o.def().endpoint);if(s>=0&&i.localKey){r[i.localKey]=a[s+1];var l=a.slice(0,s+2).join("/");return n.WithRelationshipLink(i.localField,t.JSONAPI_PARENT_LINK,i.relation,l),!1}return!0})}},e.NormaliseLinkFormat=function(e){if(e)for(var t in e)if(e[t]){var i=e[t],r=new a.MetaLink(i.href||i.toString());r.meta=u.deepMixIn(new a.Meta,i.meta),e[t]=r}},e.onInjectJsonApiData=function(i,r){if(r){var n=new c(i);n.enumerateRelations(function(e){return"function"!=typeof e.load?(e.load=function(e,i,r,n){var a=d.TryGetMetaData(r);if(!a)return Promise.reject("DSJsonApiAdapter, Failed to load Relationship, no meta data");var o=a.getRelationshipLink(i.localField,i.type===s?t.JSONAPI_PARENT_LINK:t.JSONAPI_RELATED_LINK);if(o){var l=u.copy(n);l.jsonApi=l.jsonApi||{},l.jsonApi.jsonApiPath=l.jsonApi.jsonApiPath||o.url,l.bypassCache=l.bypassCache||!0;var h=e.getResource(i.relation);if(i.type===s||i.type===p){var f=l.jsonApi.jsonApiPath;return h.find(f,l).then(function(e){if(u.isArray(e)){if(e.length>1)throw new Error("DSJsonApiAdapter, Load Relations expected non array");e=null}i.localKey?r[i.localKey]=u.resolveId(h,e):i.foreignKey?e[i.foreignKey]=u.resolveId(h,r):l.error&&l.error("DSJsonApiAdapter, load relations, relation does not have a key correctly defined",[i])})}var c={__jsDataJsonapi:l.jsonApi.jsonApiPath};return h.findAll(c,l).then(function(t){if(!u.isArray(t))throw new Error("DSJsonApiAdapter, Load Relations expected array");if(i.localKeys){var n=[];u.forEach(t,function(e){n.push(u.resolveId(h,e))}),r[i.localKeys]=n}else if(i.foreignKey){var a=u.resolveId(e,r);u.forEach(t,function(e){e[i.foreignKey]=a})}else l.error&&l.error("DSJsonApiAdapter, load relations, onToMany relation does not have a keys correctly defined",[i])})}throw new Error("Failed to load Relationship, relationship does not exist.Check your call to loadRelations that the relationship name is correct, or that your resource configuration matches your jsonApi data")},!0):void 0});var a=u.isArray(r)?r:[r];u.forEach(a,function(r){if(e.MergeMetaData(i,r),void 0===r.IsJsonApiReference){var n={enumerable:!1,writeable:!1,get:function(){var e=d.TryGetMetaData(this);return e?e.isJsonApiReference:null}};Object.defineProperty(r,"IsJsonApiReference",n)}if(void 0===r.findRelated){var a=function(e,r){var n=!1,a=d.TryGetMetaData(this);if(!a||a.isJsonApiReference!==!1)throw Error("findRelated failed, this is a mode reference load via self link instead.");if(!this[e])throw new Error("findRelated failed, Relationship name:"+e+" does not exist.");if(u.isArray(this[e]))u.forEach(this[e],function(e){var t=d.TryGetMetaData(e);return t.isJsonApiReference===!0?(n=!0,!1):void 0});else{var o=this[e],s=d.TryGetMetaData(o);s.isJsonApiReference===!0&&(n=!0)}if(!(n===!0||void 0===this[e]||r&&r.bypassCache===!0))return u.Promise.resolve(this[e]);var l=a.getRelationshipLink(e,t.JSONAPI_RELATED_LINK);if(l){var p=new c(i),h=p.getChildRelationWithLocalField(l.type,e),f=p.getResource(h.relation),y={},A={bypassCache:!0,jsonApi:{jsonApiPath:l.url}};return f.def().findAll(y,A)}};r.findRelated=a}})}},e.beforeUpdateJsonApiData=function(t,i,r){var n=u.isArray(i)?i:[i];return u.forEach(n,function(i){e.MergeMetaData(t,i)}),r?void r(null,i):i},e.afterLoadRelations=function(e,t,i){return i?void i(null,t):t},e.AssignLifeTimeEvents=function(t){t.afterInject=e.onInjectJsonApiData,t.beforeUpdate=e.beforeUpdateJsonApiData},e}();t.JsonApiHelper=A},function(e,t){"use strict";var i=function(){function e(){}return e.prototype.WithError=function(e){return this.errors=this.errors||new Array,this.errors.push(e),this},e.prototype.WithData=function(e){var t=this.data||new Array;return t.push(e),this.data=t,this},e.prototype.WithSingleData=function(e){return this.data=e,this},e.prototype.WithIncluded=function(e){return this.included=this.included||new Array,this.included.push(e),this},e.prototype.WithLink=function(e,t){return this.links=this.links||{},this.links[e]=new a(t),this},e.prototype.AddLink=function(e,t){return this.links=this.links||{},this.links[e]=t,this},e.prototype.WithMeta=function(e,t){return this.meta=this.meta||new o,this.meta[e]=t,this},e}();t.JsonApiRequest=i;var r=function(){function e(e){this.id=void 0,this.type=e,this.attributes=void 0,this.links=void 0,this.relationships=void 0}return e.prototype.WithAttribute=function(e,t){return this.attributes=this.attributes||{},this.attributes[e]=t,this},e.prototype.AddLink=function(e,t){return this.links=this.links||{},this.links[e]=t,this},e.prototype.WithLink=function(e,t){return this.links=this.links||{},this.links[e]=new a(t),this},e.prototype.WithId=function(e){return this.id=e,this},e.prototype.WithRelationship=function(e,t){return this.relationships=this.relationships||{},this.relationships[e]=t,this},e.prototype.GetSelfLink=function(){return this.links&&this.links.self?this.links.self.href:null},e}();t.JsonApiData=r;var n=function(){function e(e){this.links={},e===!0?this.data=new Array:this.data=null}return e.prototype.WithData=function(e,t){if(e&&t)return this.data&&Array.isArray(this.data)?this.data.push(new r(e).WithId(t)):this.data=new r(e).WithId(t),this;throw new Error('Invalid call to "JsonApiRelationship.WithData" type and id required')},e.prototype.AddLink=function(e,t){return this.links[e]=t,this},e.prototype.WithLink=function(e,t){return this.links[e]=new a(t),this},e.prototype.FindLinkType=function(e){return this.links&&this.links[e]?this.links[e].href:null},e}();t.JsonApiRelationship=n;var a=function(){function e(e,t){this.href=e,this.meta=t||new o}return e}();t.MetaLink=a;var o=function(){function e(){this.fields=void 0}return e}();t.Meta=o;var s=function(){function e(){}return e.prototype.AddLink=function(e,t){return this.links[e]=t,this},e}();t.JsonApiError=s;var l=function(){function e(){}return e}();t.JsonApiVersion=l}])}); //# sourceMappingURL=dist/js-data-jsonapi.min.map