Move db operations back to db module
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import csvParser from 'csvtojson'
|
||||
import isObject from 'isobject'
|
||||
import { db, getCycleDay } from '../../db'
|
||||
import { schema, tryToImportWithDelete, tryToImportWithoutDelete } from '../../db'
|
||||
import getColumnNamesForCsv from './get-csv-column-names'
|
||||
|
||||
export default async function importCsv(csv, deleteFirst) {
|
||||
@@ -23,12 +23,11 @@ export default async function importCsv(csv, deleteFirst) {
|
||||
return Number(val)
|
||||
}
|
||||
|
||||
const cycleDayDbSchema = db.schema.find(x => x.name === 'CycleDay').properties
|
||||
const config = {
|
||||
ignoreEmpty: true,
|
||||
colParser: getColumnNamesForCsv().reduce((acc, colName) => {
|
||||
const path = colName.split('.')
|
||||
const dbType = getDbType(cycleDayDbSchema, path)
|
||||
const dbType = getDbType(schema.CycleDay, path)
|
||||
acc[colName] = item => {
|
||||
if (item === '') return null
|
||||
return parseFuncs[dbType](item)
|
||||
@@ -45,29 +44,9 @@ export default async function importCsv(csv, deleteFirst) {
|
||||
putNullForEmptySymptoms(cycleDays)
|
||||
|
||||
if (deleteFirst) {
|
||||
db.write(() => {
|
||||
db.delete(db.objects('CycleDay'))
|
||||
cycleDays.forEach(tryToCreateCycleDay)
|
||||
})
|
||||
tryToImportWithDelete(cycleDays)
|
||||
} else {
|
||||
db.write(() => {
|
||||
cycleDays.forEach((day, i) => {
|
||||
const existing = getCycleDay(day.date)
|
||||
if (existing) {
|
||||
db.delete(existing)
|
||||
}
|
||||
tryToCreateCycleDay(day, i)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function tryToCreateCycleDay(day, i) {
|
||||
try {
|
||||
db.create('CycleDay', day)
|
||||
} catch (err) {
|
||||
const msg = `Line ${i + 1}(${day.date}): ${err.message}`
|
||||
throw new Error(msg)
|
||||
tryToImportWithoutDelete(cycleDays)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +78,5 @@ function putNullForEmptySymptoms(data) {
|
||||
function getDbType(modelProperties, path) {
|
||||
if (path.length === 1) return modelProperties[path[0]].type
|
||||
const modelName = modelProperties[path[0]].objectType
|
||||
const model = db.schema.find(x => x.name === modelName)
|
||||
return getDbType(model.properties, path.slice(1))
|
||||
return getDbType(schema[modelName], path.slice(1))
|
||||
}
|
||||
Reference in New Issue
Block a user