forked from utags/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport-json.ts
More file actions
67 lines (60 loc) · 1.57 KB
/
Copy pathimport-json.ts
File metadata and controls
67 lines (60 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Import and validate JSON from a file.
*/
export function importJson<T = any>(options: {
validate?: (data: any) => boolean
onSuccess: (data: T) => Promise<void | boolean> | void | boolean
confirmMessage?: string
errorMessage?: string
}) {
const {
validate,
onSuccess,
confirmMessage = '导入会与现有数据合并,是否继续?',
errorMessage = '导入的数据格式不正确',
} = options
if (confirmMessage) {
const ok = globalThis.confirm(confirmMessage)
if (!ok) return
}
const fileInput = document.createElement('input')
fileInput.type = 'file'
fileInput.accept = 'application/json'
fileInput.style.display = 'none'
const cleanup = () => {
fileInput.removeEventListener('change', onChange)
fileInput.removeEventListener('cancel', cleanup)
fileInput.remove()
}
const onChange = async () => {
try {
const f = fileInput.files?.[0]
if (!f) return
const txt = await f.text()
let obj: any
try {
obj = JSON.parse(txt)
} catch {
alert('无法解析 JSON 文件')
return
}
if (validate && !validate(obj)) {
alert(errorMessage)
return
}
const result = await onSuccess(obj)
if (result !== false) {
alert('导入完成')
}
} catch (error) {
console.error(error)
alert('导入失败')
} finally {
cleanup()
}
}
fileInput.addEventListener('change', onChange)
fileInput.addEventListener('cancel', cleanup)
document.documentElement.append(fileInput)
fileInput.click()
}