Skip to content

Commit 5784fe9

Browse files
author
Peter Svetlichny
committed
refactor(index): stringify object-type fields after validation
1 parent 28f0996 commit 5784fe9

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/index.js

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,16 +68,20 @@ module.exports = class {
6868
create (body, version = false) {
6969
return this.validate(body)
7070
.then(data => {
71+
const res = Object.assign({}, data)
7172
const vals = []
7273
const cols = Object.keys(data).reduce((acc, key) => {
74+
if (typeof data[key] === 'object' && data[key] !== null) {
75+
data[key] = JSON.stringify(data[key])
76+
}
7377
vals.push(`'${data[key]}'`)
7478
acc.push(key)
7579
return acc
7680
}, [])
7781
const query = `INSERT INTO ${this.tableName} (${cols.join(',')}) VALUES (${vals.join(',')})`
7882
return this.query(query)
79-
.then(res => {
80-
if (res.rowCount) return data
83+
.then(data => {
84+
if (data.rowCount) return res
8185
throw new Error('Unable to create record')
8286
})
8387
})
@@ -108,17 +112,26 @@ module.exports = class {
108112
update (query, body, version = false) {
109113
return this.validate(body)
110114
.then(data => {
115+
const res = Object.assign({}, data)
111116
let i = 1
112117
let changes = ''
113118
let len = Object.keys(data).length
114-
for (let prop in data) {
115-
if ({}.hasOwnProperty.call(data, prop)) {
119+
for (let key in data) {
120+
/* istanbul ignore else: should not happen */
121+
if ({}.hasOwnProperty.call(data, key)) {
122+
if (typeof data[key] === 'object' && data[key] !== null) {
123+
data[key] = JSON.stringify(data[key])
124+
}
116125
let comma = (i !== len) ? ', ' : ''
117-
changes += `${prop}='${data[prop]}'${comma}`
126+
changes += `${key}='${data[key]}'${comma}`
118127
i++
119128
}
120129
}
121130
return this.query(`UPDATE ${this.tableName} SET ${changes} WHERE ${query}`)
131+
.then(data => {
132+
if (data.rowCount) return res
133+
throw new Error('Unable to update record(s)')
134+
})
122135
})
123136
}
124137

0 commit comments

Comments
 (0)