-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathTransforms.js
58 lines (54 loc) · 1.99 KB
/
Transforms.js
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
import firebase from 'https://cdn.skypack.dev/@firebase/app'
import 'https://cdn.skypack.dev/@firebase/database'
import * as util from '../src/utils.js'
import config from './Config.js'
export default class Transforms {
constructor(modelName, root = '') {
firebase.initializeApp(config)
this.database = firebase.database()
const modelsRoot = `${root}/agentscript/models`
this.transforms = {}
this.transformsRef = this.database.ref(
`${modelsRoot}/${modelName}/transforms`
)
this.transformsRef.once('value', ev => {
const initialDB = util.objectToString(ev.val())
console.log('Initial Database', initialDB)
})
this.transformsRef.on('child_added', ev => {
console.log('child_added', ev, ev.key, ev.val())
this.addTransform(ev.key, ev.val().function)
})
this.transformsRef.on('child_removed', ev => {
console.log('child_removed', ev, ev.key, ev.val())
this.removeTransform(ev.key)
// delete this.transforms[ev.key]
})
}
addTransform(name, fcnBody) {
const xfm = {}
xfm.function = new Function('model, util', fcnBody)
xfm.resultRef = this.transformsRef.child(name + '/result')
this.transforms[name] = xfm
}
removeTransform(name) {
this.transformsRef.child(name).remove()
delete this.transforms[name]
}
step(model) {
util.forLoop(this.transforms, (val, key) => {
const name = key
const fcn = this.transforms[name].function
const ref = this.transforms[name].resultRef
const result = fcn(model, util)
// If result is a object, this turns it into a string!
// Need ref.child() ?
try {
ref.set(result)
} catch (error) {
console.log(name, fcn, ref, result)
throw Error('ref.set error')
}
})
}
}