深入挖掘前端基础服务&中间件设计-用户信息

69 阅读1分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

前言:

这一章也比较简单,主要是对系统的用户信息获取做统一管理

使用统一的API进行用户的相关信息获取。

设计思路:

graph TD
登录 --> 用户信息 --> 注册个人中心

API

标题
updateUserInfo更新用户信息
updateAppInfo更新系统信息
updateSystemConfig更新个人配置
updateUserHabit更新个人特性化配置
updateLoginStatus更新登录状态
updateSystemTimeDiff系统时间更新

上述更新操作,是在用户登录,获取到用户信息后,调用相关API进行更新。 更新后数据存储sessionstoragelocalstorage

应用:

获取登录状态

import { BaseStore } from '@basic-library'

const { loginStatus } = BaseStore.app

获取用户信息

import { BaseStore } from '@basic-library'

const { userInfo } = BaseStore.app

更新用户信息

import { BaseStore } from '@basic-library'
...
BaseStore.app.updateUserInfo(returnObj)

实践代码:

import {  cache } from '@basic-utils'
class app {
    constructor() {
        this.updateTime = 0;
    }

    userInfo = cache.getCache('userInfo', 'session') || {};
    appInfo = cache.getCache('appInfo', 'session') || {};
    systemConfig = cache.getCache('systemConfig', 'session') || {};
    userHabit = cache.getCache('userHabit', 'session') || 'normal';
    loginStatus = cache.getCache('loginStatus', 'local') || false;
    currentMenuKeys = cache.getCache('currentMenuKeys', 'session') || [];
    systemTimeDiff = 0;
    store = {};
    themeStyle = {};


    get isLogin() {
        return this.loginStatus;
    }
    /**
      * 获取系统服务器时间
      */
    get systemTime() {
        return Date.now() - this.systemTimeDiff;
    }

    updateUserInfo(userInfo) {
        this.userInfo = userInfo;
        cache.setCache('userInfo', userInfo, 'session');
    }

    updateAppInfo(appInfo) {
        this.appInfo = appInfo;
        cache.setCache('appInfo', appInfo, 'session');
    }

    updateSystemConfig(systemConfig) {
        this.systemConfig = systemConfig;
        cache.setCache('systemConfig', systemConfig, 'session');
    }

    updateUserHabit(userHabit) {
        this.userHabit = userHabit;
        cache.setCache('userHabit', userHabit, 'session');
    }

    updateLoginStatus(flag) {
        this.loginStatus = flag;
        cache.setCache('loginStatus', flag, 'local');
    }
    updateCurrentMenuKeys(keys = []) {
        this.currentMenuKeys = keys;
        cache.setCache('currentMenuKeys', keys, 'session');
    }
    updateSystemTimeDiff(num) {
        this.systemTimeDiff = num;
    }

    updateStoreData(store) {
        Object.keys(store).forEach((k) => {
            this.store[k] = store[k];
        });
    }
}
export default new app();

总结:

这个设计主要是统一规整用户信息,获取时统一方式,减少编码的认知。

简单的事情简单做。 老铁们,我们一起关注系列设计:

深入挖掘前端基础服务&中间件设计-basic-library
深入挖掘前端基础服务&中间件设计-字典设计
深入挖掘前端基础服务&中间件设计-配置设计