index.js 1.63 KB
import { getStorage, setStorage } from '../../../libs/utils'
import { APP } from '../../../config'
import { findAddr, findAddrVersion } from '../../../api/site'

export default {
    state: {
        data: []
    },
    reducers: {
        save(_, data) {
            return { data }
        },
        update(_, data) {
            return { data }
        }
    },
    effects: {
        async init(_, rootState) {
            const data = rootState.site.data
            if (data.length !== 0) return

            // 查询缓存库
            const cacheList = await getStorage(APP.siteCacheName) || []
            if (cacheList.length !== 0) { // 缓存存在数组
                this.save(cacheList)
                findAddrVersion()
                    .then(async resVersion => {
                        const version = await getStorage(APP.siteVersionName)
                        if (version != resVersion) this.httpGet(resVersion)
                    })
                    .catch(err => {})
            }
            else // 网络获取
                this.httpGet()
            
        },
        async httpGet(version) {
            findAddr()
                    .then(async res => {
                        if (version === undefined) { // 网络获取版本号
                            findAddrVersion()
                                .then(res => setStorage(APP.siteVersionName, res))
                                .catch(err => {})
                        } 
                        setStorage(APP.siteCacheName, res)
                        this.update(res)
                    })
                    .catch(err => {})
        }
    }
}