links.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * JSON Schema link handler
  3. * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
  4. * Licensed under the MIT (MIT-LICENSE.txt) license.
  5. */
  6. ({define:typeof define!="undefined"?define:function(deps, factory){module.exports = factory();}}).
  7. define([], function(){
  8. var exports = {};
  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
  12. // for example:
  13. // getLink(
  14. // "brother",
  15. // {"brother_id":33},
  16. // {links:[{rel:"brother", href:"Brother/{brother_id}"}]}) ->
  17. // "Brother/33"
  18. var links = schema.__linkTemplates;
  19. if(!links){
  20. links = {};
  21. var schemaLinks = schema.links;
  22. if(schemaLinks && schemaLinks instanceof Array){
  23. schemaLinks.forEach(function(link){
  24. /* // TODO: allow for multiple same-name relations
  25. if(links[link.rel]){
  26. if(!(links[link.rel] instanceof Array)){
  27. links[link.rel] = [links[link.rel]];
  28. }
  29. }*/
  30. links[link.rel] = link.href;
  31. });
  32. }
  33. if(exports.cacheLinks){
  34. schema.__linkTemplates = links;
  35. }
  36. }
  37. var linkTemplate = links[relation];
  38. return linkTemplate && exports.substitute(linkTemplate, instance);
  39. };
  40. exports.substitute = function(linkTemplate, instance){
  41. return linkTemplate.replace(/\{([^\}]*)\}/g, function(t, property){
  42. var value = instance[decodeURIComponent(property)];
  43. if(value instanceof Array){
  44. // 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
  45. return '(' + value.join(',') + ')';
  46. }
  47. return value;
  48. });
  49. };
  50. return exports;
  51. });