-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path1-metaprogramming.js
More file actions
77 lines (67 loc) · 1.95 KB
/
1-metaprogramming.js
File metadata and controls
77 lines (67 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
const fs = require('fs');
const http = require('http');
// Parse duration to seconds
// Example: duration('1d 10h 7m 13s')
const duration = (s) => {
if (typeof s === 'number') return s;
let result = 0;
if (typeof s === 'string') {
const days = s.match(/(\d+)\s*d/);
const hours = s.match(/(\d+)\s*h/);
const minutes = s.match(/(\d+)\s*m/);
const seconds = s.match(/(\d+)\s*s/);
if (days) result += parseInt(days[1]) * 86400;
if (hours) result += parseInt(hours[1]) * 3600;
if (minutes) result += parseInt(minutes[1]) * 60;
if (seconds) result += parseInt(seconds[1]);
return result * 1000;
}
};
// Transports
// TODO: stub to be implemented
const transport = {
get: http.get,
post: () => {},
put: () => {},
};
// Metadata
const tasks = [
{ interval: 5000,
get: 'http://127.0.0.1/api/method1.json',
save: 'file1.json' },
{ interval: '8s',
get: 'http://127.0.0.1/api/method2.json',
put: 'http://127.0.0.1/api/method4.json',
save: 'file2.json' },
{ interval: '7s',
get: 'http://127.0.0.1/api/method3.json',
post: 'http://127.0.0.1/api/method5.json' },
{ interval: '4s',
load: 'file1.json',
put: 'http://127.0.0.1/api/method6.json' },
{ interval: '9s',
load: 'file2.json',
post: 'http://127.0.0.1/api/method7.json',
save: 'file1.json' },
{ interval: '3s',
load: 'file1.json',
save: 'file3.json' }
];
// Metaprogram
const iterate = (tasks) => {
const closureTask = (task) => () => {
console.dir(task);
let source;
if (task.get) source = transport.get(task.get);
if (task.load) source = fs.createReadStream(task.load);
if (task.save) source.pipe(fs.createWriteStream(task.save));
if (task.post) source.pipe(transport.post(task.post));
if (task.put) source.pipe(transport.put(task.put));
};
for (const task of tasks) {
setInterval(closureTask(task), duration(task.interval));
}
};
// Usage
iterate(tasks);