UNPKG

wkr-util

Version:
36 lines (28 loc) 1.84 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _f = require("@cullylarson/f"); var _validate = require("@cullylarson/validate"); var _mysql = require("@cullylarson/mysql"); var _default = (0, _f.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 = (0, _f.isObject)(paramNameToColumnName) && !Array.isArray(paramNameToColumnName) ? (0, _f.compose)(_f.values, (0, _f.map)((columnInfo, paramName) => buildCondition(columnInfo, params[paramName])))(paramNameToColumnName) : [buildCondition(paramNameToColumnName, value)]; // nothing to check if (!whereInfo.length) return (0, _validate.simpleValidationResult)(); const where = whereInfo.map((0, _f.get)(0, '')).join(' AND '); const whereValues = whereInfo.map((0, _f.get)(1, '')); return (0, _mysql.query)(pool, `SELECT COUNT(*) as count FROM ${tableName} WHERE ${where}`, whereValues).then((0, _f.get)(['results', 0, 'count'], 0)).then((0, _f.toInt)(0)).then(count => { return count === 0 ? (0, _validate.simpleValidationResult)((0, _validate.messageObj)('not-found', 'The entry could not be found.')) : (0, _validate.simpleValidationResult)(); }); }); exports.default = _default; module.exports = exports.default;