From b2c70a66573caafb21a530b2a4aa40b559969e6b Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Sun, 5 Dec 2021 20:57:57 +0100 Subject: [PATCH] feat(api): user store decides if data is outdated based on the last update rather then last local changes. --- api/src/stores/user.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/api/src/stores/user.ts b/api/src/stores/user.ts index 96d1d4b..abe5283 100644 --- a/api/src/stores/user.ts +++ b/api/src/stores/user.ts @@ -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(`/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('/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('/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