Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Created June 15, 2020 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coderofsalvation/7c731bc5055660322b6e085b3290854d to your computer and use it in GitHub Desktop.
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.
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 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