mirror of
https://github.com/lana-k/sqliteviz.git
synced 2025-12-06 18:18:53 +08:00
refactor import method
This commit is contained in:
@@ -59,7 +59,18 @@ export default {
|
||||
localStorage.setItem('myQueries', JSON.stringify(value))
|
||||
},
|
||||
|
||||
export (data) {
|
||||
exportQueries (data) {
|
||||
const preparedData = JSON.parse(JSON.stringify(data))
|
||||
|
||||
// Remove isPredefined mark for exported queries
|
||||
if (Array.isArray(data)) {
|
||||
// group operation
|
||||
preparedData.forEach(query => delete query.isPredefined)
|
||||
} else {
|
||||
// single operation
|
||||
delete preparedData.isPredefined
|
||||
}
|
||||
|
||||
// Create downloader
|
||||
const downloader = document.createElement('a')
|
||||
downloader.style.display = 'none'
|
||||
@@ -67,7 +78,7 @@ export default {
|
||||
|
||||
// Prepare data
|
||||
const name = data.name || 'My sqlitevis queries'
|
||||
const json = JSON.stringify(data, null, 4)
|
||||
const json = JSON.stringify(preparedData, null, 4)
|
||||
const blob = new Blob([json], { type: 'octet/stream' })
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
downloader.href = url
|
||||
@@ -79,5 +90,55 @@ export default {
|
||||
// Clear
|
||||
window.URL.revokeObjectURL(url)
|
||||
downloader.remove()
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.style.display = 'none'
|
||||
|
||||
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.appendChild(uploader)
|
||||
}
|
||||
uploader.click()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user