feat(api): user store decides if data is outdated based on the last update rather then last local changes.

This commit is contained in:
Ferdinand Thiessen 2021-12-05 20:57:57 +01:00
parent f27212f60e
commit b2c70a6657
1 changed files with 18 additions and 4 deletions

View File

@ -6,6 +6,16 @@ export function fixUser(u?: FG.User) {
return !u ? u : Object.assign(u, { birthday: u.birthday ? new Date(u.birthday) : undefined });
}
/**
* Check if state is outdated / dirty
* Value is considered outdated after 15 minutes
* @param updated Time of last updated (in milliseconds see Date.now())
* @returns True if outdated, false otherwise
*/
function isDirty(updated: number) {
return Date.now() - updated > 15 * 60 * 1000;
}
export const useUserStore = defineStore({
id: 'users',
@ -15,6 +25,8 @@ export const useUserStore = defineStore({
// list of all users, include deleted ones, use `users` getter for list of active ones
_users: [] as FG.User[],
// Internal flags for deciding if lists need to force-loaded
_dirty_users: 0,
_dirty_roles: 0,
}),
getters: {
@ -37,6 +49,7 @@ export const useUserStore = defineStore({
*/
async getUser(userid: string, force = false) {
const idx = this._users.findIndex((user) => user.userid === userid);
if (force || idx === -1 || isDirty(this._dirty_users)) {
try {
const { data } = await api.get<FG.User>(`/users/${userid}`);
fixUser(data);
@ -58,10 +71,11 @@ export const useUserStore = defineStore({
* @throws Probably an AxiosError if loading failed
*/
async getUsers(force = false) {
if (force || this._dirty_users) {
if (force || isDirty(this._dirty_users)) {
const { data } = await api.get<FG.User[]>('/users');
data.forEach(fixUser);
this._users = data;
this._dirty_users = Date.now();
}
return this._users;
},
@ -153,10 +167,10 @@ export const useUserStore = defineStore({
* @throws Probably an AxiosError if request failed
*/
async getRoles(force = false) {
if (force || this._dirty_roles) {
if (force || isDirty(this._dirty_roles)) {
const { data } = await api.get<FG.Role[]>('/roles');
this.roles = data;
this._dirty_roles = false;
this._dirty_roles = Date.now();
}
return this.roles;
},
@ -170,7 +184,7 @@ export const useUserStore = defineStore({
const idx = this.roles.findIndex((r) => r.id === role.id);
if (idx != -1) this.roles[idx] = role;
this._dirty_roles = true;
else this._dirty_roles = 0;
},
/** Create a new role