2020-05-26 19:17:35 +03:00
|
|
|
import Service from '@ember/service';
|
|
|
|
import {inject as service} from '@ember/service';
|
2020-05-28 13:03:33 +03:00
|
|
|
import {task} from 'ember-concurrency-decorators';
|
2020-05-26 19:17:35 +03:00
|
|
|
import {tracked} from '@glimmer/tracking';
|
|
|
|
|
|
|
|
export default class MembersStatsService extends Service {
|
|
|
|
@service ajax;
|
|
|
|
@service ghostPaths;
|
|
|
|
|
2020-06-01 17:48:46 +03:00
|
|
|
@tracked days = '30';
|
2020-05-26 19:17:35 +03:00
|
|
|
@tracked stats = null;
|
|
|
|
|
2020-06-01 17:48:46 +03:00
|
|
|
fetch() {
|
|
|
|
let daysChanged = this._lastFetchedDays !== this.days;
|
2020-05-27 18:12:13 +03:00
|
|
|
let staleData = this._lastFetched && this._lastFetched - new Date() > 1 * 60 * 1000;
|
2020-05-28 13:03:33 +03:00
|
|
|
|
|
|
|
// return an already in-progress promise unless params have changed
|
|
|
|
if (this._fetchTask.isRunning && !this._forceRefresh && !daysChanged) {
|
|
|
|
return this._fetchTask.last;
|
|
|
|
}
|
|
|
|
|
|
|
|
// return existing stats unless data is > 1 min old
|
2020-05-27 18:12:13 +03:00
|
|
|
if (this.stats && !this._forceRefresh && !daysChanged && !staleData) {
|
2020-05-26 19:17:35 +03:00
|
|
|
return Promise.resolve(this.stats);
|
|
|
|
}
|
|
|
|
|
2020-06-01 17:48:46 +03:00
|
|
|
return this._fetchTask.perform();
|
2020-05-26 19:17:35 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
invalidate() {
|
|
|
|
this._forceRefresh = true;
|
|
|
|
}
|
2020-05-28 13:03:33 +03:00
|
|
|
|
|
|
|
@task
|
2020-06-01 17:48:46 +03:00
|
|
|
*_fetchTask() {
|
|
|
|
let {days} = this;
|
|
|
|
|
|
|
|
this._lastFetchedDays = days;
|
2020-05-28 13:03:33 +03:00
|
|
|
this._lastFetched = new Date();
|
|
|
|
this._forceRefresh = false;
|
|
|
|
|
|
|
|
let statsUrl = this.ghostPaths.url.api('members/stats');
|
|
|
|
let stats = yield this.ajax.request(statsUrl, {data: {days}});
|
|
|
|
this.stats = stats;
|
|
|
|
return stats;
|
|
|
|
}
|
2020-05-26 19:17:35 +03:00
|
|
|
}
|