2 * JSON Schema link handler
3 * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
4 * Licensed under the MIT (MIT-LICENSE.txt) license.
6 ({define:typeof define!="undefined"?define:function(deps, factory){module.exports = factory();}}).
9 exports.cacheLinks = true;
10 exports.getLink = function(relation, instance, schema){
11 // gets the URI of the link for the given relation based on the instance and schema
16 // {links:[{rel:"brother", href:"Brother/{brother_id}"}]}) ->
18 var links = schema.__linkTemplates;
21 var schemaLinks = schema.links;
22 if(schemaLinks && schemaLinks instanceof Array){
23 schemaLinks.forEach(function(link){
24 /* // TODO: allow for multiple same-name relations
26 if(!(links[link.rel] instanceof Array)){
27 links[link.rel] = [links[link.rel]];
30 links[link.rel] = link.href;
33 if(exports.cacheLinks){
34 schema.__linkTemplates = links;
37 var linkTemplate = links[relation];
38 return linkTemplate && exports.substitute(linkTemplate, instance);
41 exports.substitute = function(linkTemplate, instance){
42 return linkTemplate.replace(/\{([^\}]*)\}/g, function(t, property){
43 var value = instance[decodeURIComponent(property)];
44 if(value instanceof Array){
45 // 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
46 return '(' + value.join(',') + ')';