|
1 | 1 | 'use strict'; |
2 | 2 |
|
3 | | -function createInstance(defaultData) { |
| 3 | +async function processHyperData(dataManager, str) { |
| 4 | + const reg = /([\\]?){{\ *(?:\[([^{}]+)\]\ *)?([^{}]+)\ *}}/g; |
4 | 5 |
|
5 | | - const DATA = { |
6 | | - _: defaultData |
7 | | - } |
| 6 | + const ret = []; |
| 7 | + let match; |
| 8 | + let i = 0; |
| 9 | + while ((match = reg.exec(str)) !== null) { |
8 | 10 |
|
9 | | - async function getData(key) { |
| 11 | + const opr = match[1]; |
10 | 12 |
|
11 | | - if (key) { |
12 | | - if (DATA[key] == undefined) { |
13 | | - DATA[key] = fetch(key) |
14 | | - .then(r => r.json()); |
15 | | - } |
16 | | - return DATA[key]; |
| 13 | + ret.push(str.slice(i, match.index)); |
17 | 14 |
|
| 15 | + if (opr !== '\\') { |
| 16 | + const url = match[2]; |
| 17 | + const path = match[3]; |
| 18 | + try { |
| 19 | + ret.push(await dataManager.getValue(url, path)); |
| 20 | + } catch (error) { |
| 21 | + ret.push("[ERROR]"); |
| 22 | + } |
18 | 23 | } else { |
19 | | - return DATA['_']; |
| 24 | + ret.push((match[0] + "").slice(1)); |
20 | 25 | } |
21 | 26 |
|
| 27 | + i = reg.lastIndex; |
22 | 28 | } |
| 29 | + ret.push(str.slice(i)); |
23 | 30 |
|
24 | | - async function getValue(url, path) { |
25 | | - |
26 | | - const data = await getData(url); |
27 | | - const ret = path.split(".").reduce((acc, cur) => acc[(cur+"").trim()], data); |
28 | | - return ret; |
29 | | - } |
30 | | - |
31 | | - return { |
32 | | - replace: (str, mark) => { |
33 | | - return str.replace(/{{[^{}]+}}/g, mark); |
34 | | - }, |
35 | | - process: async str => { |
36 | | - |
37 | | - const reg = /([\\]?){{\ *(?:\[([^{}]+)\]\ *)?([^{}]+)\ *}}/g; |
38 | | - |
39 | | - const ret = []; |
40 | | - let match; |
41 | | - let i = 0; |
42 | | - while ((match = reg.exec(str)) !== null) { |
43 | | - |
44 | | - const opr = match[1]; |
45 | | - |
46 | | - ret.push(str.slice(i, match.index)); |
47 | | - |
48 | | - if (opr !== '\\') { |
49 | | - const url = match[2]; |
50 | | - const path = match[3]; |
51 | | - try { |
52 | | - ret.push(await getValue(url, path)); |
53 | | - } catch (error) { |
54 | | - ret.push("[ERROR]"); |
55 | | - } |
56 | | - } else { |
57 | | - ret.push((match[0] + "").slice(1)); |
58 | | - } |
59 | | - |
60 | | - i = reg.lastIndex; |
61 | | - } |
62 | | - ret.push(str.slice(i)); |
63 | | - |
64 | | - return ret.join(""); |
65 | | - } |
66 | | - } |
| 31 | + return ret.join(""); |
67 | 32 | } |
68 | 33 |
|
69 | | -module.exports = createInstance; |
70 | | - |
| 34 | +module.exports = processHyperData; |
0 commit comments