Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vue plugin to retrieve the server time
//+ 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