wkr-util
Version:
Utility library for wkr project.
38 lines (31 loc) • 1.81 kB
JavaScript
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");
// 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).
var _default = (0, _f.curry)((pool, tableName, idColumnName, ignoreIdInfo, paramNameToColumnName, _, params) => {
ignoreIdInfo = (0, _f.liftA)(ignoreIdInfo);
const whereInfo = (0, _f.compose)(xs => {
const ignoreId = (0, _f.get)(0, undefined, ignoreIdInfo);
const ignoreValuePlaceholder = (0, _f.get)(1, '?', ignoreIdInfo);
return !ignoreId ? xs : [...xs, [`${idColumnName} != ${ignoreValuePlaceholder}`, ignoreId]];
}, _f.values, (0, _f.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((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'], 1)).then((0, _f.toInt)(1)).then(count => {
return count > 0 ? (0, _validate.simpleValidationResult)((0, _validate.messageObj)('is-duplicate', 'This entry already exists.')) : (0, _validate.simpleValidationResult)();
});
});
exports.default = _default;
module.exports = exports.default;
;