mirror of
https://github.com/lana-k/sqliteviz.git
synced 2025-12-07 02:28:54 +08:00
refactor import function
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { nanoid } from 'nanoid'
|
||||
import fu from '@/fileUtils'
|
||||
|
||||
export default {
|
||||
getStoredQueries () {
|
||||
@@ -65,54 +66,29 @@ export default {
|
||||
return JSON.stringify(preparedData, null, 4)
|
||||
},
|
||||
|
||||
/**
|
||||
* It calls onSuccess with imported queries as argument when
|
||||
* file read. We can't use Promises here because we can't
|
||||
* catch the Cancel event when a user choose a file.
|
||||
*/
|
||||
importQueries (onSuccess) {
|
||||
let uploader = document.getElementById('file-uploader')
|
||||
|
||||
// Create uploader if it doesn't exists
|
||||
if (!uploader) {
|
||||
uploader = document.createElement('input')
|
||||
uploader.id = 'file-uploader'
|
||||
uploader.type = 'file'
|
||||
uploader.accept = '.json'
|
||||
uploader.hidden = true
|
||||
|
||||
uploader.addEventListener('change', () => {
|
||||
const file = uploader.files[0]
|
||||
const reader = new FileReader()
|
||||
reader.onload = (e) => {
|
||||
// Parse data
|
||||
let importedQueries = JSON.parse(e.target.result)
|
||||
|
||||
// Turn data into array if they are not
|
||||
if (!Array.isArray(importedQueries)) {
|
||||
importedQueries = [importedQueries]
|
||||
}
|
||||
|
||||
// Generate new ids if they are the same as existing queries
|
||||
importedQueries.forEach(query => {
|
||||
const allQueriesIds = this.getStoredQueries().map(query => query.id)
|
||||
if (new Set(allQueriesIds).has(query.id)) {
|
||||
query.id = nanoid()
|
||||
}
|
||||
})
|
||||
|
||||
// Clear uploader
|
||||
uploader.value = null
|
||||
|
||||
// Call callback
|
||||
onSuccess(importedQueries)
|
||||
}
|
||||
reader.readAsText(file)
|
||||
})
|
||||
|
||||
document.body.append(uploader)
|
||||
deserialiseQueries (str) {
|
||||
let queryList = JSON.parse(str)
|
||||
// Turn data into array if they are not
|
||||
if (!Array.isArray(queryList)) {
|
||||
queryList = [queryList]
|
||||
}
|
||||
uploader.click()
|
||||
|
||||
// Generate new ids if they are the same as existing queries
|
||||
queryList.forEach(query => {
|
||||
const allQueriesIds = this.getStoredQueries().map(query => query.id)
|
||||
if (allQueriesIds.includes(query.id)) {
|
||||
query.id = nanoid()
|
||||
}
|
||||
})
|
||||
|
||||
return queryList
|
||||
},
|
||||
|
||||
importQueries () {
|
||||
return fu.importFile()
|
||||
.then(data => {
|
||||
return this.deserialiseQueries(data)
|
||||
})
|
||||
},
|
||||
|
||||
readPredefinedQueries () {
|
||||
|
||||
Reference in New Issue
Block a user