mtfosbot_web/src/store/actions.js

90 lines
2.0 KiB
JavaScript

import axios from 'axios'
import {
apiUrl,
chkObject,
toInt
} from '@/tools'
const client = axios.create({
baseURL: apiUrl,
withCredentials: true
})
const errorCatch = function (err, act) {
let msg = ''
if ('response' in err && 'data' in err.response && 'message' in err.response.data) {
msg = err.response.data.message
} else {
msg = 'unknown error'
}
this('addDialog', {
msg,
act
})
}
export default {
async checkSession ({commit}, cb = null) {
commit('toggleLoading', true)
let flag = false
try {
let result = await client({
method: 'get',
url: '/api/session'
})
if ('data' in result) {
commit('setUserInfo', {
name: result.data.user.name || '',
type: result.data.user.type || ''
})
}
flag = true
} catch (err) {
flag = false
}
if (typeof cb === 'function') cb(flag)
commit('toggleLoading', false)
},
async sendLogin ({commit}, {account, password, cb = null}) {
let chk = chkObject.bind({body: {account, password}})
if (!chk('account', 'string') || !chk('password', 'string')) {
commit('addDialog', {
msg: '帳號密碼不能留空'
})
return
}
let data = {
account,
password
}
commit('toggleLoading', true)
try {
await client({
method: 'post',
url: '/api/login',
data
})
if (typeof cb === 'function') cb()
} catch (err) {
errorCatch.apply(commit, [err])
}
commit('toggleLoading', false)
},
async getChannelList ({commit}, cb = null) {
commit('toggleLoading', true)
try {
let result = await client({
method: 'get',
url: '/api/twitch/channels'
})
let list = []
if ('data' in result && 'list' in result.data && Array.isArray(result.data.list)) list = result.data.list
commit('setChannels', list)
if (typeof cb === 'function') cb()
} catch (err) {
errorCatch.apply(commit, [err])
}
commit('toggleLoading', false)
}
}