Created
March 30, 2019 19:41
-
-
Save jonasraoni/48c00c34d5eec964a27070441f486d4c to your computer and use it in GitHub Desktop.
Vue plugin to retrieve the server time
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
//+ Jonas Raoni Soares Silva | |
//@ http://raoni.org | |
export default class ServerTime { | |
constructor ({http = new Error('http parameter is required'), url = new Error('url is required'), thresholdDelay = 300, autoSynchronizeProbes = 0}) { | |
Object.assign(this, { | |
http, | |
url, | |
thresholdDelay, | |
best: null | |
}); | |
for (let promise = Promise.resolve(), i = autoSynchronizeProbes; i-- > 0;) { | |
promise = promise.then(() => this.synchronize()).catch(error => { | |
console.error(error); | |
}); | |
} | |
} | |
synchronize () { | |
return new Promise(resolve => { | |
const start = +new Date(); | |
return this.http.get(this.url).then(response => { | |
const now = +new Date(); | |
const requestDelay = now - start; | |
if (!this.best || requestDelay < this.best.requestDelay) { | |
this.best = { | |
requestDelay, | |
delay: now - (requestDelay >> 1) - (+new Date(response.body) || +new Date(response.headers.get('Date'))) | |
}; | |
resolve(this); | |
} | |
}); | |
}); | |
} | |
getDate () { | |
if (!this.best || this.best.requestDelay > this.thresholdDelay) { | |
this.synchronize().catch(error => { | |
console.error(error); | |
}); | |
} | |
return new Date(+new Date() - (this.best ? this.best.delay : 0)); | |
} | |
toString () { | |
return this.getDate() + ''; | |
} | |
valueOf () { | |
return +this.getDate(); | |
} | |
[Symbol.toPrimitive] (hint) { | |
return hint === 'number' ? this.valueOf() : this.toString(); | |
} | |
static install (Vue, options) { | |
Vue.prototype.$serverTime = new ServerTime(options); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment