bajo-extra 0.2.1 → 0.2.3

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.
@@ -0,0 +1,42 @@
1
+ async function fetchAndSave ({ source = {}, converter, coll, current = {}, options = {} } = {}) {
2
+ const { print, setImmediate, importPkg } = this.bajo.helper
3
+ const { isEmpty, isFunction } = await importPkg('lodash-es')
4
+ const { fetch } = this.bajoExtra.helper
5
+ const { recordCreate, recordFind, recordUpdate, validationErrorMessage } = this.bajoDb.helper
6
+ const spinner = print.bora('Fetching starts...', { showCounter: true, showDatetime: true }).start()
7
+ const resp = await fetch(source.url, source.options ?? {})
8
+ if (isEmpty(resp)) spinner.fatal('No result from server, aborted!')
9
+ if (source.abort) {
10
+ const aborted = await source.abort.call(this, resp)
11
+ if (aborted) spinner.fatal(aborted)
12
+ }
13
+ let count = 0
14
+ spinner.setText('Got %d records, processing...', resp.response.length)
15
+ const iterator = isFunction(source.dataKey) ? await source.dataKey.call(this, resp) : resp[source.dataKey]
16
+ for (let r of iterator) {
17
+ await setImmediate()
18
+ if (converter) r = await converter.call(this, r, options)
19
+ try {
20
+ await recordCreate(coll, r)
21
+ if (current.coll && current.query) {
22
+ const recs = await recordFind(current.coll, current.query)
23
+ if (recs.length > 0) {
24
+ const id = recs[0].id
25
+ await recordUpdate(current.coll, id, r)
26
+ } else {
27
+ await recordCreate(current.coll, r)
28
+ }
29
+ }
30
+ if (options.printCount && (count % options.printCount === 0)) print.succeed(`[${spinner.getElapsed()}] Batch line %d/%d`, count, resp.response.length, { showDatetime: true })
31
+ else spinner.setText('Record %d/%d...', count, resp.response.length)
32
+ count++
33
+ } catch (err) {
34
+ console.log(err)
35
+ spinner.setText(validationErrorMessage(err) + ', continue')
36
+ }
37
+ }
38
+ spinner.info(`${count}/${resp.response.length} records processed`)
39
+ spinner.succeed('Done!')
40
+ }
41
+
42
+ export default fetchAndSave
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bajo-extra",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Extra package for Bajo Framework",
5
5
  "main": "index.js",
6
6
  "scripts": {