1/** 2 * JSON Schema link handler 3 * Licensed under AFL-2.1 OR BSD-3-Clause 4 */ 5(function (root, factory) { 6 if (typeof define === 'function' && define.amd) { 7 // AMD. Register as an anonymous module. 8 define([], function () { 9 return factory(); 10 }); 11 } else if (typeof module === 'object' && module.exports) { 12 // Node. Does not work with strict CommonJS, but 13 // only CommonJS-like environments that support module.exports, 14 // like Node. 15 module.exports = factory(); 16 } else { 17 // Browser globals 18 root.jsonSchemaLinks = factory(); 19 } 20}(this, function () {// setup primitive classes to be JSON Schema types 21var exports = {}; 22exports.cacheLinks = true; 23exports.getLink = function(relation, instance, schema){ 24 // gets the URI of the link for the given relation based on the instance and schema 25 // for example: 26 // getLink( 27 // "brother", 28 // {"brother_id":33}, 29 // {links:[{rel:"brother", href:"Brother/{brother_id}"}]}) -> 30 // "Brother/33" 31 var links = schema.__linkTemplates; 32 if(!links){ 33 links = {}; 34 var schemaLinks = schema.links; 35 if(schemaLinks && schemaLinks instanceof Array){ 36 schemaLinks.forEach(function(link){ 37 /* // TODO: allow for multiple same-name relations 38 if(links[link.rel]){ 39 if(!(links[link.rel] instanceof Array)){ 40 links[link.rel] = [links[link.rel]]; 41 } 42 }*/ 43 links[link.rel] = link.href; 44 }); 45 } 46 if(exports.cacheLinks){ 47 schema.__linkTemplates = links; 48 } 49 } 50 var linkTemplate = links[relation]; 51 return linkTemplate && exports.substitute(linkTemplate, instance); 52}; 53 54exports.substitute = function(linkTemplate, instance){ 55 return linkTemplate.replace(/\{([^\}]*)\}/g, function(t, property){ 56 var value = instance[decodeURIComponent(property)]; 57 if(value instanceof Array){ 58 // the value is an array, it should produce a URI like /Table/(4,5,8) and store.get() should handle that as an array of values 59 return '(' + value.join(',') + ')'; 60 } 61 return value; 62 }); 63}; 64return exports; 65}));