2 * JSON Schema link handler
\r
3 * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
\r
4 * Licensed under the MIT (MIT-LICENSE.txt) license.
\r
6 (function (root, factory) {
\r
7 if (typeof define === 'function' && define.amd) {
\r
8 // AMD. Register as an anonymous module.
\r
9 define([], function () {
\r
12 } else if (typeof module === 'object' && module.exports) {
\r
13 // Node. Does not work with strict CommonJS, but
\r
14 // only CommonJS-like environments that support module.exports,
\r
16 module.exports = factory();
\r
19 root.jsonSchemaLinks = factory();
\r
21 }(this, function () {// setup primitive classes to be JSON Schema types
\r
23 exports.cacheLinks = true;
\r
24 exports.getLink = function(relation, instance, schema){
\r
25 // gets the URI of the link for the given relation based on the instance and schema
\r
29 // {"brother_id":33},
\r
30 // {links:[{rel:"brother", href:"Brother/{brother_id}"}]}) ->
\r
32 var links = schema.__linkTemplates;
\r
35 var schemaLinks = schema.links;
\r
36 if(schemaLinks && schemaLinks instanceof Array){
\r
37 schemaLinks.forEach(function(link){
\r
38 /* // TODO: allow for multiple same-name relations
\r
39 if(links[link.rel]){
\r
40 if(!(links[link.rel] instanceof Array)){
\r
41 links[link.rel] = [links[link.rel]];
\r
44 links[link.rel] = link.href;
\r
47 if(exports.cacheLinks){
\r
48 schema.__linkTemplates = links;
\r
51 var linkTemplate = links[relation];
\r
52 return linkTemplate && exports.substitute(linkTemplate, instance);
\r
55 exports.substitute = function(linkTemplate, instance){
\r
56 return linkTemplate.replace(/\{([^\}]*)\}/g, function(t, property){
\r
57 var value = instance[decodeURIComponent(property)];
\r
58 if(value instanceof Array){
\r
59 // 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
\r
60 return '(' + value.join(',') + ')';
\r