Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added link helper

  • Loading branch information...
commit 8f138faff875a1b4ef53ffd5cb58d7da5a343577 1 parent 9020ff6
@kriszyp authored
Showing with 42 additions and 0 deletions.
  1. +42 −0 lib/json-schema.js
View
42 lib/json-schema.js
@@ -236,3 +236,45 @@ exports.mustBeValid = function(result){
}
*/
+exports.cacheLinks = true;
+exports.getLink = function(relation, instance, schema){
+ // gets the URI of the link for the given relation based on the instance and schema
+ // for example:
+ // getLink(
+ // "brother",
+ // {"brother_id":33},
+ // {links:[{rel:"brother", href:"Brother/{brother_id}"}]}) ->
+ // "Brother/33"
+ var links = schema.__linkTemplates;
+ if(!links){
+ links = {};
+ var schemaLinks = schema.links;
+ if(schemaLinks && schemaLinks instanceof Array){
+ schemaLinks.forEach(function(link){
+ /* // TODO: allow for multiple same-name relations
+ if(links[link.rel]){
+ if(!(links[link.rel] instanceof Array)){
+ links[link.rel] = [links[link.rel]];
+ }
+ }*/
+ links[link.rel] = link.href;
+ });
+ }
+ if(exports.cacheLinks){
+ schema.__linkTemplates = links;
+ }
+ }
+ var linkTemplate = links[relation];
+ return linkTemplate && exports.substitue(linkTemplate, instance);
+};
+
+exports.substitute = function(linkTemplate, instance){
+ return linkTemplate.replace(/\{([^\}]*)\}/g, function(t, property){
+ var value = instance[decodeURIComponent(property)];
+ if(value instanceof Array){
+ // 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
+ return '(' + value.join(',') + ')';
+ }
+ return value;
+ });
+};
Please sign in to comment.
Something went wrong with that request. Please try again.