wkr-util
Version:
Utility library for wkr project.
47 lines (40 loc) • 1.84 kB
JavaScript
import {compose, curry, map, get, toInt, values, liftA} from '@cullylarson/f'
import {messageObj, simpleValidationResult} from '@cullylarson/validate'
import {query} from '@cullylarson/mysql'
// ignoreIdInfo can just be an id (will ignore the row with this id when looking for dupes), or an array.
// if it's an array, the first value is the id to ignore and the second is the placeholder to use instead of just a '?'
// (used if you need to convert the id using an sql function like UUID_TO_BIN).
export default curry((pool, tableName, idColumnName, ignoreIdInfo, paramNameToColumnName, _, params) => {
ignoreIdInfo = liftA(ignoreIdInfo)
const whereInfo = compose(
xs => {
const ignoreId = get(0, undefined, ignoreIdInfo)
const ignoreValuePlaceholder = get(1, '?', ignoreIdInfo)
return !ignoreId
? xs
: [...xs, [
`${idColumnName} != ${ignoreValuePlaceholder}`,
ignoreId,
]]
},
values,
map((columnName, paramName) => {
return [
`${columnName} = ?`, // the condition query
params[paramName], // the value to fill in for the '?'
]
}),
)(paramNameToColumnName)
// nothing to check
if(!whereInfo.length) return null
const where = whereInfo.map(get(0, '')).join(' AND ')
const whereValues = whereInfo.map(get(1, ''))
return query(pool, `SELECT COUNT(*) as count FROM ${tableName} WHERE ${where}`, whereValues)
.then(get(['results', 0, 'count'], 1))
.then(toInt(1))
.then(count => {
return count > 0
? simpleValidationResult(messageObj('is-duplicate', 'This entry already exists.'))
: simpleValidationResult()
})
})