UNPKG

wkr-util

Version:
40 lines (33 loc) 1.77 kB
import {curry, compose, map, get, toInt, isObject, values} from '@cullylarson/f' import {messageObj, simpleValidationResult} from '@cullylarson/validate' import {query} from '@cullylarson/mysql' export default curry((pool, tableName, paramNameToColumnName, value, params) => { // if columnInfo is an array, the first item is the column name, the second item // is SQL that should be used as the value or value placeholder. It must include a question mark which will be replaced by the value. const buildCondition = (columnInfo, value) => { const columnName = Array.isArray(columnInfo) ? columnInfo[0] : columnInfo const valuePlaceholder = Array.isArray(columnInfo) ? columnInfo[1] : '?' return [ `${columnName} = ${valuePlaceholder}`, // the condition query value, // the value to fill in for the '?' ] } const whereInfo = isObject(paramNameToColumnName) && !Array.isArray(paramNameToColumnName) ? compose( values, map((columnInfo, paramName) => buildCondition(columnInfo, params[paramName])), )(paramNameToColumnName) : [buildCondition(paramNameToColumnName, value)] // nothing to check if(!whereInfo.length) return simpleValidationResult() 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'], 0)) .then(toInt(0)) .then(count => { return count === 0 ? simpleValidationResult(messageObj('not-found', 'The entry could not be found.')) : simpleValidationResult() }) })