links.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. (function (root, factory) {
  7. if (typeof define === 'function' && define.amd) {
  8. // AMD. Register as an anonymous module.
  9. define([], function () {
  10. return factory();
  11. });
  12. } else if (typeof module === 'object' && module.exports) {
  13. // Node. Does not work with strict CommonJS, but
  14. // only CommonJS-like environments that support module.exports,
  15. // like Node.
  16. module.exports = factory();
  17. } else {
  18. // Browser globals
  19. root.jsonSchemaLinks = factory();
  20. }
  21. }(this, function () {// setup primitive classes to be JSON Schema types
  22. var exports = {};
  23. exports.cacheLinks = true;
  24. exports.getLink = function(relation, instance, schema){
  25. // gets the URI of the link for the given relation based on the instance and schema
  26. // for example:
  27. // getLink(
  28. // "brother",
  29. // {"brother_id":33},
  30. // {links:[{rel:"brother", href:"Brother/{brother_id}"}]}) ->
  31. // "Brother/33"
  32. var links = schema.__linkTemplates;
  33. if(!links){
  34. links = {};
  35. var schemaLinks = schema.links;
  36. if(schemaLinks && schemaLinks instanceof Array){
  37. schemaLinks.forEach(function(link){
  38. /* // TODO: allow for multiple same-name relations
  39. if(links[link.rel]){
  40. if(!(links[link.rel] instanceof Array)){
  41. links[link.rel] = [links[link.rel]];
  42. }
  43. }*/
  44. links[link.rel] = link.href;
  45. });
  46. }
  47. if(exports.cacheLinks){
  48. schema.__linkTemplates = links;
  49. }
  50. }
  51. var linkTemplate = links[relation];
  52. return linkTemplate && exports.substitute(linkTemplate, instance);
  53. };
  54. exports.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. };
  64. return exports;
  65. }));