fcc-core
Version:
Fusion communication center.
122 lines (114 loc) • 2.93 kB
JavaScript
import moment from 'moment'
/**
*DB构造函数
* @param params
* @constructor
*/
function DB (params) {
this.db = null
this.databasename = params.databasename
this.version = params.version || ''
this.tablename = params.tablename
this.init()
}
DB.prototype = {
constructor: DB,
createIndexdb,
addLog,
itratorDB,
init () {
this.createIndexdb().then((db) => {
this.db = db
})
}
}
/**
* 打开 indexdb连接
* @param params
* @returns {Promise<any>}
*/
function createIndexdb () {
const self = this
return new Promise(function (resolve, reject) {
const request = indexedDB.open(self.databasename, self.vesion)
let flag = false
request.onsuccess = (event) => {
if (!flag) {
resolve(event.target.result)
}
flag = true
}
request.onerror = (event) => {
reject(event)
console.error(event)
}
request.onupgradeneeded = (event) => {
const db = event.target.result
if (!flag) {
resolve(db)
}
flag = true
if (!db.objectStoreNames.contains(self.tablename)) {
db.createObjectStore(self.tablename, { autoIncrement: true })
}
}
})
}
/**
* 写日志至打开的对象仓库
* @param params = {
* action //行为动作
* interface调用接口
* params 接口参数
* time 时间
* usercode 坐席编号
* state 坐席状态
* }
*/
function addLog (params) {
if (!params) {
return
}
if (!this.db) {
return
}
const defaults = {
time: moment().format('YYYY/MM/DD hh:mm:ss')
}
const request = this.db.transaction([this.tablename], 'readwrite')
.objectStore(this.tablename).add(Object.assign(defaults, params))
request.onsuccess = (event) => {
}
request.onerror = (event) => {
console.error(event)
}
}
/**
* 遍历数据并将数据整合成文件上传至服务器
*/
function itratorDB (tablename) {
let str = []
if (!tablename) {
return
}
const objectStore = this.db.transaction(tablename).objectStore(tablename)
objectStore.openCursor().onsuccess = (event) => {
const cursor = event.target.result
if (cursor) {
let o = cursor.value
str.push(`时间:${o.time} 动作:${o.action} 接口:${o.interface}` +
`参数:${JSON.stringify(o.params)} 操作人:${o.usercode},状态:${o.state}\n`)
cursor.continue()
} else {
const type = 'text/plain,charset=utf-8'
const blob = new Blob(str, { type })
const file = new File([blob], `${moment().format('YYYYMMDD')}-${123}`, { type, lastModified: new Date() })
/* const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = 'xwlog.log'
a.click() */
// 上传文件至服务器
}
}
}
export default DB