-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfs.js
More file actions
36 lines (28 loc) · 1.1 KB
/
Copy pathconfs.js
File metadata and controls
36 lines (28 loc) · 1.1 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
const _ = require('lodash');
const EventEmitter = require('events');
const requireFromString = require('require-from-string');
const {streamToString} = require('./stream.js');
const s3 = require('./s3.js');
const {useLock} = require('./concurrent.js');
const {clearAndAppend} = require('./util.js');
const E = module.exports;
const confs = {};
const load = async (path, client)=>requireFromString(
await streamToString(s3.download(path, {client})));
E.get = key=>confs[key]?.data;
E.subscribe = (key, path)=>useLock(`confs.${key}`, async ()=>{
const data = await load(path);
const events = new EventEmitter();
confs[key] = {path, events, data};
process.nextTick(()=>events.emit('refresh', data));
});
E.unsubscribe = key=>delete confs[key];
E.refresh = async ()=>{
const client = s3.createClient();
await Promise.all(_.values(confs).map(async ({path, events, data})=>{
const loadedModule = await load(path, client);
clearAndAppend(data, loadedModule);
events.emit('refresh', loadedModule);
}));
};
E.onRefresh = (key, cb)=>confs[key].events.on('refresh', cb);