Created
June 15, 2020 11:31
-
-
Save coderofsalvation/7c731bc5055660322b6e085b3290854d to your computer and use it in GitHub Desktop.
parse-server analytics alternative, which simply add `.metric(key,value)` function to Parse Objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var id = '2m9fUAIFN3' | |
new Parse.Query("MyClass") | |
.get(id) | |
.then( (o) => { | |
o.metric( 'impressions', 1) // updates metric | |
o.metric( 'impressions', 1) // but does not | |
o.metric( 'impressions', 1) // save immediately | |
o.metric( 'impressions', 1) // to prevent race conditions | |
}) | |
setTimeout( () => { | |
new Parse.Query("MyClass") | |
.get(id) | |
.then( (o) => { | |
console.log("get current value") | |
console.log( o.get('impressions') ) | |
}) | |
},5000) | |
// output: | |
// lazy save | |
// 4 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* this adds metric(key,amount) function | |
* which allows ParseObjects to increment numbers | |
* in a parallel way, with a lazy (deferred) save to db | |
*/ | |
let metricize = function(ParseObject,ttl){ | |
Parse.Object.extend( ParseObject, { | |
metricTTL: ttl, | |
metric: function(key, amount){ | |
this._queue = this._queue || [] | |
clearTimeout( this._queue.to ) | |
this._queue.push({key, amount}) | |
this._queue.to = setTimeout( async () => { | |
this._queue.map( (o) => { | |
console.dir({ | |
key: o.key, | |
value: this.get(o.key), | |
amount: o.amount | |
}) | |
this.set(o.key, ( this.get(o.key) || 0 ) + o.amount ) | |
}) | |
console.log("lazy save") | |
await this.save() | |
}, this.metricTTL ) | |
} | |
}) | |
} | |
metricize("MyClass",2000) // adds MyClass.metric() function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment