UNPKG

2.21 kBtext/coffeescriptView Raw
1debug = require('debug')('christacheio');
2_ = require 'lodash'
3{deepGet,deepSet} = require 'lodash-deep'
4escapeStringRegexp = require 'escape-string-regexp'
5
6regexMatches = (regexString, string) ->
7 regex = new RegExp regexString, 'g'
8
9 matches = []
10 while match = regex.exec string
11 matches.push match[1]
12 return matches;
13
14christacheio = (jsonString, obj, tags, transformation) ->
15 tags ?= ['{{', '}}']
16 transformation ?= (data) -> data
17 regexStr = "#{tags[0]}(.*?)#{tags[1]}"
18 map = {}
19
20 newJsonString = _.clone jsonString
21
22 _.each regexMatches(regexStr, jsonString), (key) ->
23 map[key] = transformation deepGet(obj, key)
24 map[key] ?= null
25
26 _.each map, (value, key) ->
27 escapedKey = escapeStringRegexp key
28 regex = new RegExp tags[0] + escapedKey + tags[1], 'g'
29 newJsonString = newJsonString.replace regex, map[key]
30
31 return newJsonString
32
33module.exports = christacheio
34
35
36###
37var _ = require('lodash');
38var debug = require('debug')('christacheio');
39var deepGet = require('lodash-deep').deepGet;
40var deepSet = require('lodash-deep').deepSet;
41var escapeStringRegexp = require('escape-string-regexp');
42//
43var christacheio = function(tags, jsonString, obj, transformation) {
44 var regexStr, map, newJsonString;
45 transformation = transformation || function(data) { return data; }
46 tags = tags || ['{{', '}}'];
47 regexStr = tags[0] + '(.*?)' + tags[1];
48 map = {};
49 newJsonString = _.clone(jsonString);
50//
51 function regexMatches(regexString, string){
52 var regex, matches, match;
53 regex = new RegExp(regexString, 'g');
54 matches = [];
55 while(match = regex.exec(string)){
56 matches.push(match[1]);
57 }
58 return matches;
59 };
60//
61 _.each(regexMatches(regexStr, jsonString), function(key) {
62 var value = deepGet(obj, key);
63 value = transformation(value);
64 map[key] = value || null;
65 });
66//
67 _.each(map, function(value, key){
68 var escapedKey = escapeStringRegexp(key);
69 var regex = new RegExp(tags[0] + escapedKey + tags[1], 'g');
70 newJsonString = newJsonString.replace(regex, map[key]);
71 });
72//
73 return newJsonString;
74}
75//
76module.exports = christacheio;
77###