import { Module , ActionContext } from 'vuex' ; import { RootState } from '@/store' ; import { axiosPost , errorMessage } from '@/common/util' ; import { DatasetInfo , DatasetState , DatasetCache , CachedDataset , GetDatasetOptions } from './types' ; const getDatasetFromCache = ( cache , key ) : CachedDataset | undefined => { return key in cache ? cache [ key ] : undefined ; } ; const initialState = { lastList : [ ] , cache : { } } ; const mutations = { cacheDataset ( state , { key , data } ) { const [ username , filename ] = key . split ( ',' ) ; state . cache [ key ] = { username , filename , data , fetchedAt : new Date ( ) } ; } } ; const actions = { getDataset ( context , options ) { const username = options . username || '' ; const key = options . username + ',' + options . filename ; const cached = getDatasetFromCache ( context . state . cache , key ) ; if ( cached ) { return new Promise ( resolve => { resolve ( cached . data ) ; } ) ; } return new Promise ( ( resolve , reject ) => { axiosPost < string > ( '/dataset/get' , options ) . then ( res => { context . commit ( 'cacheDataset' , { key , data : res . data } ) ; resolve ( res . data ) ; } ) . catch ( err => reject ( errorMessage ( err ) ) ) ; } ) ; } , deleteDataset ( context , filename ) { if ( ! context . rootState . user . username ) { return Promise . reject ( 'must login to delete dataset' ) ; } return new Promise ( ( resolve , reject ) => { axiosPost < void > ( '/dataset/delete' , { filename } ) . then ( ( ) => resolve ( ) ) . catch ( err => reject ( errorMessage ( err ) ) ) ; } ) ; } , listDataset ( context ) { return new Promise ( ( resolve , reject ) => { axiosPost < DatasetInfo [ ] > ( '/dataset/list' ) . then ( res => { context . state . lastList = res . data ; resolve ( res . data ) ; } ) . catch ( err => reject ( errorMessage ( err ) ) ) ; } ) ; } } ; const dataset = { namespaced : true , state : initialState , mutations , actions } ; export default dataset ;