links.js 2.0 KB

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