dobo-extra 2.4.0 → 2.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.jsdoc.conf.json +1 -1
- package/docs/DoboExtra.html +1 -1
- package/docs/data/search.json +1 -1
- package/docs/global.html +1 -1
- package/docs/index.html +1 -1
- package/docs/index.js.html +234 -57
- package/docs/lib_config.js.html +31 -0
- package/docs/lib_helper.js.html +99 -0
- package/docs/module-Helper.html +16 -0
- package/docs/scripts/core.js +477 -476
- package/docs/scripts/resize.js +36 -36
- package/docs/scripts/search.js +105 -105
- package/docs/scripts/third-party/fuse.js +1 -1
- package/docs/scripts/third-party/hljs-line-num-original.js +285 -282
- package/docs/scripts/third-party/hljs-line-num.js +1 -1
- package/docs/scripts/third-party/hljs-original.js +1202 -1195
- package/docs/scripts/third-party/hljs.js +1 -1
- package/docs/scripts/third-party/popper.js +1 -1
- package/docs/scripts/third-party/tippy.js +1 -1
- package/docs/scripts/third-party/tocbot.js +509 -508
- package/index.js +230 -57
- package/lib/config.js +28 -0
- package/lib/helper.js +96 -0
- package/package.json +2 -2
- package/wiki/CHANGES.md +9 -0
- package/lib/export-to.js +0 -123
- package/lib/import-from.js +0 -65
- package/lib/io-exts.js +0 -1
- package/lib/ndjson-csv-xlsx.js +0 -38
package/index.js
CHANGED
|
@@ -1,84 +1,257 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import path from 'path'
|
|
2
|
+
import { json, ndjson, csv, xlsx } from './lib/helper.js'
|
|
3
|
+
import { createGunzip, createGzip } from 'zlib'
|
|
4
|
+
import scramjet from 'scramjet'
|
|
5
|
+
import config from './lib/config.js'
|
|
6
|
+
|
|
7
|
+
const { DataStream } = scramjet
|
|
8
|
+
const exts = ['.json', '.jsonl', '.ndjson', '.csv', '.xlsx', '.tsv']
|
|
3
9
|
|
|
4
10
|
/**
|
|
5
|
-
* Plugin factory
|
|
11
|
+
* Plugin factory.
|
|
12
|
+
*
|
|
13
|
+
* **Never** call this function directly!!! It's only-meant to be called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
|
|
6
14
|
*
|
|
7
15
|
* @param {string} pkgName - NPM package name
|
|
8
|
-
* @returns {
|
|
16
|
+
* @returns {DoboExtra}
|
|
9
17
|
*/
|
|
10
18
|
async function factory (pkgName) {
|
|
11
19
|
const me = this
|
|
12
20
|
|
|
13
21
|
/**
|
|
14
|
-
* DoboExtra class
|
|
22
|
+
* DoboExtra class definition
|
|
15
23
|
*
|
|
16
|
-
*
|
|
24
|
+
* This class provides more functionality to the Dobo plugin including:
|
|
25
|
+
* - new additional `ndjson` format for Bajo's configHandlers
|
|
26
|
+
* - data import/export from/to file system in various formats (JSON, NDJSON, CSV, TSV, XLSX)
|
|
27
|
+
*
|
|
28
|
+
* @class
|
|
17
29
|
*/
|
|
18
30
|
class DoboExtra extends this.app.baseClass.Base {
|
|
19
31
|
constructor () {
|
|
32
|
+
/**
|
|
33
|
+
* Constructor
|
|
34
|
+
*/
|
|
20
35
|
super(pkgName, me.app)
|
|
21
|
-
this.config = {
|
|
22
|
-
export: {
|
|
23
|
-
maxBatch: 1000,
|
|
24
|
-
stringify: {
|
|
25
|
-
open: '[\n',
|
|
26
|
-
sep: ',\n',
|
|
27
|
-
close: '\n]\n'
|
|
28
|
-
}
|
|
29
|
-
},
|
|
30
|
-
import: {
|
|
31
|
-
maxBatch: 1000
|
|
32
|
-
},
|
|
33
|
-
archive: {
|
|
34
|
-
tasks: [],
|
|
35
|
-
checkInterval: false,
|
|
36
|
-
runEarly: true
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
36
|
|
|
40
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Configuration object
|
|
39
|
+
* @type {TConfig}
|
|
40
|
+
*/
|
|
41
|
+
this.config = config
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Import data from a file into a Dobo model
|
|
46
|
+
*
|
|
47
|
+
* @async
|
|
48
|
+
* @method
|
|
49
|
+
* @param {string} source - Source file path (absolute or relative to plugin data dir)
|
|
50
|
+
* @param {string|boolean} dest - Destination model name or `false`. If `false`, the data will be returned instead of being imported into a model.
|
|
51
|
+
* @param {object} options - Import options
|
|
52
|
+
* @param {boolean} [options.trashOld=true] - Whether to clear the destination model before importing
|
|
53
|
+
* @param {number} [options.batch=100] - Number of records to import in a single batch.
|
|
54
|
+
* @param {function} [options.progressFn] - Callback function to report progress
|
|
55
|
+
* @param {function} [options.converterFn] - Callback function to convert each record before importing
|
|
56
|
+
* @param {boolean} [options.useHeader=true] - Whether to use the first row as header (for CSV/TSV/XLSX)
|
|
57
|
+
* @param {string} [options.fileType] - File type (json, ndjson, csv, tsv, xlsx)
|
|
58
|
+
* @returns {Promise<object|array>} - Imported data or summary report including file path and record count affected
|
|
59
|
+
*/
|
|
60
|
+
importFrom = async (source, dest, options = {}) => {
|
|
61
|
+
let {
|
|
62
|
+
trashOld = true, batch = 100, progressFn, converterFn, useHeader = true,
|
|
63
|
+
fileType, createOpts = {}, parserOpts = {}
|
|
64
|
+
} = options
|
|
65
|
+
const { merge } = this.app.lib._
|
|
66
|
+
const { fs } = this.app.lib
|
|
67
|
+
const { getModel } = this.app.dobo
|
|
46
68
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
item[key] = item[key] ?? 'createdAt'
|
|
55
|
-
const schema = getSchema(item[f])
|
|
56
|
-
const prop = schema.properties.find(p => p.name === item[key])
|
|
57
|
-
if (!prop) throw this.error('unknownField%s%s', item[key], item[f])
|
|
58
|
-
if (!types.includes(prop.type)) throw this.error('isNotSupported%s%s%s%s', item[key], item[f], prop.type, join(types))
|
|
59
|
-
}
|
|
60
|
-
if (item.source === item.destination) throw this.error('sourceDestMustBeDifferent')
|
|
61
|
-
item.maxAge = item.maxAge ?? 1 // in days, less then 1 is ignored
|
|
69
|
+
let dmodel
|
|
70
|
+
if (dest !== false) dmodel = getModel(dest) // make sure dest model is valid
|
|
71
|
+
let file
|
|
72
|
+
if (path.isAbsolute(source)) file = source
|
|
73
|
+
else {
|
|
74
|
+
file = `${this.app.getPluginDataDir(this.ns)}/import/${source}`
|
|
75
|
+
fs.ensureDirSync(path.dirname(file))
|
|
62
76
|
}
|
|
77
|
+
if (!fs.existsSync(file)) throw this.error('sourceFileNotExists%s', file)
|
|
78
|
+
let ext = fileType ? `.${fileType}` : path.extname(file)
|
|
79
|
+
let decompress = false
|
|
80
|
+
if (ext === '.gz') {
|
|
81
|
+
ext = path.extname(path.basename(file, '.gz'))
|
|
82
|
+
decompress = true
|
|
83
|
+
}
|
|
84
|
+
if (!exts.includes(ext)) throw this.error('unsupportedFormat%s', ext.slice(1))
|
|
85
|
+
if (trashOld && dest !== false) await dmodel.clearRecord()
|
|
86
|
+
const reader = fs.createReadStream(file)
|
|
87
|
+
batch = parseInt(batch) || 100
|
|
88
|
+
if (batch > this.config.import.maxBatch) batch = this.config.import.maxBatch
|
|
89
|
+
if (batch < 0) batch = 1
|
|
90
|
+
let count = 0
|
|
91
|
+
const pipes = [reader]
|
|
92
|
+
if (decompress) pipes.push(createGunzip())
|
|
93
|
+
if (ext === '.json') pipes.push(json.parse(parserOpts))
|
|
94
|
+
else if (['.ndjson', '.jsonl'].includes(ext)) pipes.push(ndjson.parse(parserOpts))
|
|
95
|
+
else if (ext === '.csv') pipes.push(csv.parse(merge({}, { headers: useHeader }, parserOpts)))
|
|
96
|
+
else if (ext === '.tsv') pipes.push(csv.parse(merge({}, { headers: useHeader }, merge({}, parserOpts, { delimiter: '\t' }))))
|
|
97
|
+
else if (ext === '.xlsx') pipes.push(xlsx.parse(merge({}, { header: useHeader }, parserOpts)))
|
|
98
|
+
|
|
99
|
+
const stream = DataStream.pipeline(...pipes)
|
|
100
|
+
let batchNo = 1
|
|
101
|
+
const data = []
|
|
102
|
+
await stream
|
|
103
|
+
.batch(batch)
|
|
104
|
+
.map(async items => {
|
|
105
|
+
if (items.length === 0) return null
|
|
106
|
+
const batchStart = new Date()
|
|
107
|
+
for (let item of items) {
|
|
108
|
+
count++
|
|
109
|
+
item = converterFn ? await converterFn.call(this, item) : item
|
|
110
|
+
if (dest !== false) await dmodel.createRecord(item, createOpts)
|
|
111
|
+
else data.push(item)
|
|
112
|
+
}
|
|
113
|
+
if (progressFn) await progressFn.call(this, { batchNo, data: items, batchStart, batchEnd: new Date() })
|
|
114
|
+
batchNo++
|
|
115
|
+
})
|
|
116
|
+
.run()
|
|
63
117
|
|
|
64
|
-
|
|
118
|
+
return dest === false ? data : { file, count }
|
|
65
119
|
}
|
|
66
120
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
121
|
+
/**
|
|
122
|
+
* Export data from a Dobo model into a file
|
|
123
|
+
* @async
|
|
124
|
+
* @method
|
|
125
|
+
* @param {string} source - Source model name
|
|
126
|
+
* @param {string} dest - Destination file path (absolute or relative to plugin data dir)
|
|
127
|
+
* @param {object} options - Export options
|
|
128
|
+
* @param {object} [options.filter={}] - Filter object to select records to export
|
|
129
|
+
* @param {boolean} [options.ensureDir] - Whether to create the destination directory if it doesn't exist
|
|
130
|
+
* @param {boolean} [options.useHeader=true] - Whether to include the header row (for CSV/TSV/XLSX)
|
|
131
|
+
* @param {number} [options.batch=500] - Number of records to export in a single batch
|
|
132
|
+
* @param {function} [options.progressFn] - Callback function to report progress
|
|
133
|
+
* @param {Array<string>} [options.fields] - List of fields to include in the export
|
|
134
|
+
* @param {object} [options.parserOpts={}] - Options for the parser (e.g., CSV delimiter)
|
|
135
|
+
* @returns {Promise<object>} - Export summary including file path and record count affected
|
|
136
|
+
*/
|
|
137
|
+
exportTo = (source, dest, options = {}) => {
|
|
138
|
+
let {
|
|
139
|
+
filter = {}, ensureDir, useHeader = true, batch = 500,
|
|
140
|
+
progressFn, fields, parserOpts = {}
|
|
141
|
+
} = options
|
|
142
|
+
const { importPkg } = this.app.bajo
|
|
143
|
+
const { fs } = this.app.lib
|
|
144
|
+
const { merge, omit } = this.app.lib._
|
|
145
|
+
const { getModel } = this.app.dobo
|
|
146
|
+
|
|
147
|
+
const getFile = async () => {
|
|
148
|
+
const increment = await importPkg('bajo:add-filename-increment')
|
|
149
|
+
let file
|
|
150
|
+
if (path.isAbsolute(dest)) file = dest
|
|
151
|
+
else {
|
|
152
|
+
file = `${this.app.getPluginDataDir(this.ns)}/export/${dest}`
|
|
153
|
+
fs.ensureDirSync(path.dirname(file))
|
|
154
|
+
}
|
|
155
|
+
file = increment(file, { fs: true, platform: 'win32' })
|
|
156
|
+
const dir = path.dirname(file)
|
|
157
|
+
if (!fs.existsSync(dir)) {
|
|
158
|
+
if (ensureDir) fs.ensureDirSync(dir)
|
|
159
|
+
else throw this.error('dirNotExists%s', dir)
|
|
160
|
+
}
|
|
161
|
+
let compress = false
|
|
162
|
+
let ext = path.extname(file)
|
|
163
|
+
if (ext === '.gz') {
|
|
164
|
+
compress = true
|
|
165
|
+
ext = path.extname(file.slice(0, -3))
|
|
166
|
+
// file = file.slice(0, file.length - 3)
|
|
167
|
+
}
|
|
168
|
+
if (!exts.includes(ext)) throw this.error('unsupportedFormat%s', ext.slice(1))
|
|
169
|
+
return { file, ext, compress }
|
|
71
170
|
}
|
|
72
|
-
if (this.config.archive.runEarly) await this.archive()
|
|
73
|
-
this.archiveIntv = setInterval(() => {
|
|
74
|
-
this.archive().then().catch(err => {
|
|
75
|
-
this.log.error('archiveError%s', err.message)
|
|
76
|
-
})
|
|
77
|
-
}, this.config.archive.checkInterval * 60 * 1000)
|
|
78
|
-
}
|
|
79
171
|
|
|
80
|
-
|
|
81
|
-
|
|
172
|
+
const getData = async (options = {}) => {
|
|
173
|
+
const { source, filter, count, stream, progressFn, fields } = options
|
|
174
|
+
let cnt = count ?? 0
|
|
175
|
+
const { find } = this.app.lib._
|
|
176
|
+
const { getModel } = this.app.dobo
|
|
177
|
+
const { maxLimit, hardCap } = this.app.dobo.config.default.filter
|
|
178
|
+
filter.limit = maxLimit
|
|
179
|
+
let sort
|
|
180
|
+
const model = getModel(source)
|
|
181
|
+
const idField = find(model.properties, { name: 'id' }).name
|
|
182
|
+
for (const name of ['createdAt', 'updatedAt', 'ts', 'dt']) {
|
|
183
|
+
const field = find(model.properties, { name })
|
|
184
|
+
if (field) {
|
|
185
|
+
sort = field.name
|
|
186
|
+
break
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
filter.sort = `${sort ?? idField}:1`
|
|
190
|
+
for (;;) {
|
|
191
|
+
const batchStart = new Date()
|
|
192
|
+
const { data: rows, page } = await model.findRecord(filter, { dataOnly: false, fields, fmt: true, refs: '*', noCache: true })
|
|
193
|
+
const data = rows.map(item => omit(item, ['_immutable', '_fmt', '_ref']))
|
|
194
|
+
if (data.length === 0) break
|
|
195
|
+
if (cnt + data.length > hardCap) {
|
|
196
|
+
const sliced = data.slice(0, hardCap - cnt)
|
|
197
|
+
await stream.pull(sliced)
|
|
198
|
+
cnt += sliced.length
|
|
199
|
+
if (progressFn) await progressFn.call(this, { batchNo: page, data: sliced, batchStart, batchEnd: new Date() })
|
|
200
|
+
break
|
|
201
|
+
}
|
|
202
|
+
cnt += data.length
|
|
203
|
+
await stream.pull(data)
|
|
204
|
+
if (progressFn) await progressFn.call(this, { batchNo: page, data, batchStart, batchEnd: new Date() })
|
|
205
|
+
filter.page++
|
|
206
|
+
}
|
|
207
|
+
await stream.end()
|
|
208
|
+
return cnt
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
filter.page = 1
|
|
212
|
+
batch = parseInt(batch) ?? 500
|
|
213
|
+
if (batch > this.config.export.maxBatch) batch = this.config.export.maxBatch
|
|
214
|
+
if (batch < 0) batch = 1
|
|
215
|
+
filter.limit = batch
|
|
216
|
+
|
|
217
|
+
return new Promise((resolve, reject) => {
|
|
218
|
+
let count = 0
|
|
219
|
+
let file
|
|
220
|
+
let ext
|
|
221
|
+
let stream
|
|
222
|
+
let compress
|
|
223
|
+
let writer
|
|
224
|
+
getModel(source)
|
|
225
|
+
getFile()
|
|
226
|
+
.then(res => {
|
|
227
|
+
file = res.file
|
|
228
|
+
ext = res.ext
|
|
229
|
+
compress = res.compress
|
|
230
|
+
writer = fs.createWriteStream(file)
|
|
231
|
+
writer.on('error', err => {
|
|
232
|
+
reject(err)
|
|
233
|
+
})
|
|
234
|
+
writer.on('finish', () => {
|
|
235
|
+
resolve({ file, count })
|
|
236
|
+
})
|
|
237
|
+
stream = new DataStream()
|
|
238
|
+
stream = stream.flatMap(items => (items))
|
|
239
|
+
const pipes = []
|
|
240
|
+
if (ext === '.json') pipes.push(json.stringify(parserOpts))
|
|
241
|
+
else if (['.ndjson', '.jsonl'].includes(ext)) pipes.push(ndjson.stringify(parserOpts))
|
|
242
|
+
else if (ext === '.csv') pipes.push(csv.stringify(merge({}, { headers: useHeader }, parserOpts)))
|
|
243
|
+
else if (ext === '.tsv') pipes.push(csv.stringify(merge({}, { headers: useHeader }, merge({}, parserOpts, { delimiter: '\t' }))))
|
|
244
|
+
else if (ext === '.xlsx') pipes.push(xlsx.stringify(merge({}, { header: useHeader }, parserOpts)))
|
|
245
|
+
if (compress) pipes.push(createGzip())
|
|
246
|
+
DataStream.pipeline(stream, ...pipes).pipe(writer)
|
|
247
|
+
return getData({ source, filter, count, stream, fields, progressFn })
|
|
248
|
+
})
|
|
249
|
+
.then(cnt => {
|
|
250
|
+
count = cnt
|
|
251
|
+
})
|
|
252
|
+
.catch(reject)
|
|
253
|
+
})
|
|
254
|
+
}
|
|
82
255
|
}
|
|
83
256
|
|
|
84
257
|
return DoboExtra
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef TConfig
|
|
3
|
+
* @memberof DoboExtra
|
|
4
|
+
* @type {object}
|
|
5
|
+
* @property {object} export - Export configuration
|
|
6
|
+
* @property {number} export.maxBatch - Maximum number of records to export in a single batch
|
|
7
|
+
* @property {object} export.stringify - Stringify options for exported data
|
|
8
|
+
* @property {string} export.stringify.open - Opening string for exported data
|
|
9
|
+
* @property {string} export.stringify.sep - Separator string for exported data
|
|
10
|
+
* @property {string} export.stringify.close - Closing string for exported data
|
|
11
|
+
* @property {object} import - Import configuration
|
|
12
|
+
* @property {number} import.maxBatch - Maximum number of records to import in a single batch
|
|
13
|
+
*/
|
|
14
|
+
const config = {
|
|
15
|
+
export: {
|
|
16
|
+
maxBatch: 1000,
|
|
17
|
+
stringify: {
|
|
18
|
+
open: '[\n',
|
|
19
|
+
sep: ',\n',
|
|
20
|
+
close: '\n]\n'
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
import: {
|
|
24
|
+
maxBatch: 1000
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export default config
|
package/lib/helper.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import ndj from 'ndjson'
|
|
2
|
+
import fastCsv from 'fast-csv'
|
|
3
|
+
import xlsxparse from 'xlsx-parse-stream'
|
|
4
|
+
import XLSXWriteStream from '@atomictech/xlsx-write-stream'
|
|
5
|
+
import StreamArray from 'stream-json/streamers/StreamArray.js'
|
|
6
|
+
import Stringer from 'stream-json/Stringer.js'
|
|
7
|
+
import Disassembler from 'stream-json/Disassembler.js'
|
|
8
|
+
import chain from 'stream-chain'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Helper functions for Dobo Extra
|
|
12
|
+
* @module Helper
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
// Borrow the idea from: https://github.com/fanlia/ndjson-csv-xlsx/blob/main/index.js
|
|
16
|
+
|
|
17
|
+
const XLSXStreamer = XLSXWriteStream.default
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* NDJSON parser and stringifier.
|
|
21
|
+
*
|
|
22
|
+
* To be able to use this helper, do something like this:
|
|
23
|
+
* ```js
|
|
24
|
+
* const { importModule } = this.app.bajo
|
|
25
|
+
* const { ndjson } = await importModule('dobo-extra:/lib/helper.js', { asDefaultImport: false })
|
|
26
|
+
* console.log(ndjson.parse('{"a":1}\n{"b":2}')) // [{a:1},{b:2}]
|
|
27
|
+
* console.log(ndjson.stringify([{a:1},{b:2}])) // '{"a":1}\n{"b":2}\n'
|
|
28
|
+
* ```
|
|
29
|
+
* @type {object}
|
|
30
|
+
* @property {function} parse - Parse NDJSON data
|
|
31
|
+
* @property {function} stringify - Stringify data to NDJSON format
|
|
32
|
+
*/
|
|
33
|
+
export const ndjson = {
|
|
34
|
+
parse: (...args) => ndj.parse(...args),
|
|
35
|
+
stringify: (...args) => ndj.stringify(...args)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* CSV parser and stringifier.
|
|
40
|
+
*
|
|
41
|
+
* To be able to use this helper, do something like this:
|
|
42
|
+
* ```js
|
|
43
|
+
* const { importModule } = this.app.bajo
|
|
44
|
+
* const { csv } = await importModule('dobo-extra:/lib/helper.js', { asDefaultImport: false })
|
|
45
|
+
* ...
|
|
46
|
+
* ```
|
|
47
|
+
* @type {object}
|
|
48
|
+
* @property {function} parse - Parse CSV data
|
|
49
|
+
* @property {function} stringify - Stringify data to CSV format
|
|
50
|
+
*/
|
|
51
|
+
export const csv = {
|
|
52
|
+
parse: (...args) => fastCsv.parse(...args),
|
|
53
|
+
stringify: (...args) => fastCsv.format(...args)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Excel XLSX parser and stringifier.
|
|
58
|
+
*
|
|
59
|
+
* To be able to use this helper, do something like this:
|
|
60
|
+
* ```js
|
|
61
|
+
* const { importModule } = this.app.bajo
|
|
62
|
+
* const { xlsx } = await importModule('dobo-extra:/lib/helper.js', { asDefaultImport: false })
|
|
63
|
+
* ...
|
|
64
|
+
* ```
|
|
65
|
+
* @type {object}
|
|
66
|
+
* @property {function} parse - Parse XLSX data
|
|
67
|
+
* @property {function} stringify - Stringify data to XLSX format
|
|
68
|
+
*/
|
|
69
|
+
export const xlsx = {
|
|
70
|
+
parse: (...args) => xlsxparse(...args),
|
|
71
|
+
stringify: (...args) => new XLSXStreamer(...args)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* JSON parser and stringifier. Use stream to handle large JSON files.
|
|
76
|
+
*
|
|
77
|
+
* To be able to use this helper, do something like this:
|
|
78
|
+
* ```js
|
|
79
|
+
* const { importModule } = this.app.bajo
|
|
80
|
+
* const { json } = await importModule('dobo-extra:/lib/helper.js', { asDefaultImport: false })
|
|
81
|
+
* ...
|
|
82
|
+
* ```
|
|
83
|
+
* @type {object}
|
|
84
|
+
* @property {function} parse - Parse JSON data
|
|
85
|
+
* @property {function} stringify - Stringify data to JSON format
|
|
86
|
+
*/
|
|
87
|
+
export const json = {
|
|
88
|
+
parse: (...args) => chain([
|
|
89
|
+
StreamArray.withParser(...args),
|
|
90
|
+
data => data.value
|
|
91
|
+
]),
|
|
92
|
+
stringify: (options, ...args) => chain([
|
|
93
|
+
new Disassembler(),
|
|
94
|
+
new Stringer({ ...options, makeArray: true })
|
|
95
|
+
])
|
|
96
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dobo-extra",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.5.1",
|
|
4
4
|
"description": "Bajo DB Extra Tools/Utility",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"keywords": [
|
|
21
21
|
"extra",
|
|
22
22
|
"db",
|
|
23
|
-
"
|
|
23
|
+
"adapter",
|
|
24
24
|
"bajo",
|
|
25
25
|
"framework",
|
|
26
26
|
"modular"
|
package/wiki/CHANGES.md
CHANGED
package/lib/export-to.js
DELETED
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import path from 'path'
|
|
2
|
-
import { json, ndjson, csv, xlsx } from './ndjson-csv-xlsx.js'
|
|
3
|
-
import { createGzip } from 'node:zlib'
|
|
4
|
-
import scramjet from 'scramjet'
|
|
5
|
-
import supportedExt from './io-exts.js'
|
|
6
|
-
|
|
7
|
-
const { DataStream } = scramjet
|
|
8
|
-
|
|
9
|
-
async function getFile (dest, ensureDir) {
|
|
10
|
-
const { importPkg } = this.app.bajo
|
|
11
|
-
const { fs } = this.app.lib
|
|
12
|
-
const increment = await importPkg('bajo:add-filename-increment')
|
|
13
|
-
let file
|
|
14
|
-
if (path.isAbsolute(dest)) file = dest
|
|
15
|
-
else {
|
|
16
|
-
file = `${this.app.getPluginDataDir(this.ns)}/export/${dest}`
|
|
17
|
-
fs.ensureDirSync(path.dirname(file))
|
|
18
|
-
}
|
|
19
|
-
file = increment(file, { fs: true })
|
|
20
|
-
const dir = path.dirname(file)
|
|
21
|
-
if (!fs.existsSync(dir)) {
|
|
22
|
-
if (ensureDir) fs.ensureDirSync(dir)
|
|
23
|
-
else throw this.error('dirNotExists%s', dir)
|
|
24
|
-
}
|
|
25
|
-
let compress = false
|
|
26
|
-
let ext = path.extname(file)
|
|
27
|
-
if (ext === '.gz') {
|
|
28
|
-
compress = true
|
|
29
|
-
ext = path.extname(file.slice(0, -3))
|
|
30
|
-
// file = file.slice(0, file.length - 3)
|
|
31
|
-
}
|
|
32
|
-
if (!supportedExt.includes(ext)) throw this.error('unsupportedFormat%s', ext.slice(1))
|
|
33
|
-
return { file, ext, compress }
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
async function getData ({ source, filter, count, stream, progressFn, fields }) {
|
|
37
|
-
let cnt = count ?? 0
|
|
38
|
-
const { find } = this.app.lib._
|
|
39
|
-
const { recordFind, getSchema } = this.app.dobo
|
|
40
|
-
const { maxLimit, hardCap } = this.app.dobo.config.default.filter
|
|
41
|
-
filter.limit = maxLimit
|
|
42
|
-
let sort
|
|
43
|
-
const schema = getSchema(source)
|
|
44
|
-
const idField = find(schema.properties, { name: 'id' })
|
|
45
|
-
for (const name of ['createdAt', 'updatedAt', 'ts', 'dt']) {
|
|
46
|
-
const field = find(schema.properties, { name })
|
|
47
|
-
if (field) {
|
|
48
|
-
sort = field.name
|
|
49
|
-
break
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
filter.sort = `${sort ?? idField}:1`
|
|
53
|
-
for (;;) {
|
|
54
|
-
const batchStart = new Date()
|
|
55
|
-
const { data, page } = await recordFind(source, filter, { dataOnly: false, fields })
|
|
56
|
-
if (data.length === 0) break
|
|
57
|
-
if (cnt + data.length > hardCap) {
|
|
58
|
-
const sliced = data.slice(0, hardCap - cnt)
|
|
59
|
-
await stream.pull(sliced)
|
|
60
|
-
cnt += sliced.length
|
|
61
|
-
if (progressFn) await progressFn.call(this, { batchNo: page, data: sliced, batchStart, batchEnd: new Date() })
|
|
62
|
-
break
|
|
63
|
-
}
|
|
64
|
-
cnt += data.length
|
|
65
|
-
await stream.pull(data)
|
|
66
|
-
if (progressFn) await progressFn.call(this, { batchNo: page, data, batchStart, batchEnd: new Date() })
|
|
67
|
-
filter.page++
|
|
68
|
-
}
|
|
69
|
-
await stream.end()
|
|
70
|
-
return cnt
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function exportTo (source, dest, { filter = {}, ensureDir, useHeader = true, batch = 500, progressFn, fields } = {}, opts = {}) {
|
|
74
|
-
const { fs } = this.app.lib
|
|
75
|
-
const { merge } = this.app.lib._
|
|
76
|
-
const { getInfo } = this.app.dobo
|
|
77
|
-
|
|
78
|
-
filter.page = 1
|
|
79
|
-
batch = parseInt(batch) ?? 500
|
|
80
|
-
if (batch > this.config.export.maxBatch) batch = this.config.export.maxBatch
|
|
81
|
-
if (batch < 0) batch = 1
|
|
82
|
-
filter.limit = batch
|
|
83
|
-
|
|
84
|
-
return new Promise((resolve, reject) => {
|
|
85
|
-
let count = 0
|
|
86
|
-
let file
|
|
87
|
-
let ext
|
|
88
|
-
let stream
|
|
89
|
-
let compress
|
|
90
|
-
let writer
|
|
91
|
-
getInfo(source)
|
|
92
|
-
getFile.call(this, dest, ensureDir)
|
|
93
|
-
.then(res => {
|
|
94
|
-
file = res.file
|
|
95
|
-
ext = res.ext
|
|
96
|
-
compress = res.compress
|
|
97
|
-
writer = fs.createWriteStream(file)
|
|
98
|
-
writer.on('error', err => {
|
|
99
|
-
reject(err)
|
|
100
|
-
})
|
|
101
|
-
writer.on('finish', () => {
|
|
102
|
-
resolve({ file, count })
|
|
103
|
-
})
|
|
104
|
-
stream = new DataStream()
|
|
105
|
-
stream = stream.flatMap(items => (items))
|
|
106
|
-
const pipes = []
|
|
107
|
-
if (ext === '.json') pipes.push(json.stringify(opts))
|
|
108
|
-
else if (['.ndjson', '.jsonl'].includes(ext)) pipes.push(ndjson.stringify(opts))
|
|
109
|
-
else if (ext === '.csv') pipes.push(csv.stringify(merge({}, { headers: useHeader }, opts)))
|
|
110
|
-
else if (ext === '.tsv') pipes.push(csv.stringify(merge({}, { headers: useHeader }, merge({}, opts, { delimiter: '\t' }))))
|
|
111
|
-
else if (ext === '.xlsx') pipes.push(xlsx.stringify(merge({}, { header: useHeader }, opts)))
|
|
112
|
-
if (compress) pipes.push(createGzip())
|
|
113
|
-
DataStream.pipeline(stream, ...pipes).pipe(writer)
|
|
114
|
-
return getData.call(this, { source, filter, count, stream, fields, progressFn })
|
|
115
|
-
})
|
|
116
|
-
.then(cnt => {
|
|
117
|
-
count = cnt
|
|
118
|
-
})
|
|
119
|
-
.catch(reject)
|
|
120
|
-
})
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
export default exportTo
|
package/lib/import-from.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import path from 'path'
|
|
2
|
-
import { json, ndjson, csv, xlsx } from './ndjson-csv-xlsx.js'
|
|
3
|
-
import { createGunzip } from 'zlib'
|
|
4
|
-
import supportedExt from './io-exts.js'
|
|
5
|
-
import scramjet from 'scramjet'
|
|
6
|
-
|
|
7
|
-
const { DataStream } = scramjet
|
|
8
|
-
|
|
9
|
-
async function importFrom (source, dest, { trashOld = true, batch = 1, progressFn, converterFn, useHeader = true, fileType, createOpts = {} } = {}, opts = {}) {
|
|
10
|
-
const { recordCreate } = this.app.dobo
|
|
11
|
-
const { merge } = this.app.lib._
|
|
12
|
-
const { fs } = this.app.lib
|
|
13
|
-
|
|
14
|
-
if (dest !== false) this.app.dobo.getInfo(dest) // make sure dest model is valid
|
|
15
|
-
let file
|
|
16
|
-
if (path.isAbsolute(source)) file = source
|
|
17
|
-
else {
|
|
18
|
-
file = `${this.app.getPluginDataDir(this.ns)}/import/${source}`
|
|
19
|
-
fs.ensureDirSync(path.dirname(file))
|
|
20
|
-
}
|
|
21
|
-
if (!fs.existsSync(file)) throw this.error('sourceFileNotExists%s', file)
|
|
22
|
-
let ext = fileType ? `.${fileType}` : path.extname(file)
|
|
23
|
-
let decompress = false
|
|
24
|
-
if (ext === '.gz') {
|
|
25
|
-
ext = path.extname(path.basename(file, '.gz'))
|
|
26
|
-
decompress = true
|
|
27
|
-
}
|
|
28
|
-
if (!supportedExt.includes(ext)) throw this.error('unsupportedFormat%s', ext.slice(1))
|
|
29
|
-
if (trashOld && dest !== false) await this.app.dobo.modelClear(dest)
|
|
30
|
-
const reader = fs.createReadStream(file)
|
|
31
|
-
batch = parseInt(batch) || 100
|
|
32
|
-
if (batch > this.config.import.maxBatch) batch = this.config.import.maxBatch
|
|
33
|
-
if (batch < 0) batch = 1
|
|
34
|
-
let count = 0
|
|
35
|
-
const pipes = [reader]
|
|
36
|
-
if (decompress) pipes.push(createGunzip())
|
|
37
|
-
if (ext === '.json') pipes.push(json.parse(opts))
|
|
38
|
-
else if (['.ndjson', '.jsonl'].includes(ext)) pipes.push(ndjson.parse(opts))
|
|
39
|
-
else if (ext === '.csv') pipes.push(csv.parse(merge({}, { headers: useHeader }, opts)))
|
|
40
|
-
else if (ext === '.tsv') pipes.push(csv.parse(merge({}, { headers: useHeader }, merge({}, opts, { delimiter: '\t' }))))
|
|
41
|
-
else if (ext === '.xlsx') pipes.push(xlsx.parse(merge({}, { header: useHeader }, opts)))
|
|
42
|
-
|
|
43
|
-
const stream = DataStream.pipeline(...pipes)
|
|
44
|
-
let batchNo = 1
|
|
45
|
-
const data = []
|
|
46
|
-
await stream
|
|
47
|
-
.batch(batch)
|
|
48
|
-
.map(async items => {
|
|
49
|
-
if (items.length === 0) return null
|
|
50
|
-
const batchStart = new Date()
|
|
51
|
-
for (let item of items) {
|
|
52
|
-
count++
|
|
53
|
-
item = converterFn ? await converterFn.call(this, item) : item
|
|
54
|
-
if (dest !== false) await recordCreate(dest, item, createOpts)
|
|
55
|
-
else data.push(item)
|
|
56
|
-
}
|
|
57
|
-
if (progressFn) await progressFn.call(this, { batchNo, data: items, batchStart, batchEnd: new Date() })
|
|
58
|
-
batchNo++
|
|
59
|
-
})
|
|
60
|
-
.run()
|
|
61
|
-
|
|
62
|
-
return dest === false ? data : { file, count }
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export default importFrom
|
package/lib/io-exts.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export default ['.json', '.jsonl', '.ndjson', '.csv', '.xlsx', '.tsv']
|