1 |
|
2 |
|
3 |
|
4 |
|
5 | (function (root, factory) {
|
6 | if (typeof define === 'function' && define.amd) {
|
7 |
|
8 | define([], function () {
|
9 | return factory();
|
10 | });
|
11 | } else if (typeof module === 'object' && module.exports) {
|
12 |
|
13 |
|
14 |
|
15 | module.exports = factory();
|
16 | } else {
|
17 |
|
18 | root.jsonSchemaLinks = factory();
|
19 | }
|
20 | }(this, function () {
|
21 | var exports = {};
|
22 | exports.cacheLinks = true;
|
23 | exports.getLink = function(relation, instance, schema){
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
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 | |
38 |
|
39 |
|
40 |
|
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 |
|
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 |
|
59 | return '(' + value.join(',') + ')';
|
60 | }
|
61 | return value;
|
62 | });
|
63 | };
|
64 | return exports;
|
65 | })); |
\ | No newline at end of file |