JSFiddle - React, Tailwind, and code Playground
$filters DB query mapping
by tonytlwu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<div id="result"></div>
<div class="col">
<h3>Input</h3>
<pre id="input"></pre>
</div>
<div class="col">
<h3>Expected</h3>
<pre id="expected"></pre>
</div>
<div class="col">
<h3>Output</h3>
<pre id="output"></pre>
</div>
CSS
.col {
float: left;
width: 33%;
}
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: maroon; }
JavaScript
function syntaxHighlight(json) {
json = JSON.stringify(json, null, 2);
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
const SEQUELIZE_SIFT_COMPATIBLE_OPERATORS = {
logical: ['$or', '$and'],
comparison: ['$gte', '$lte', '$gt', '$lt', '$eq']
};
const ALL_SEQUELIZE_SIFT_COMPATIBLE_OPERATORS = _.concat.apply(undefined, _.values(SEQUELIZE_SIFT_COMPATIBLE_OPERATORS));
function queryValueIsSequelizeCompatible(value) {
// Numbers and strings are safe to pass to DB
if (['number', 'string'].indexOf(typeof value) > -1) {
return true;
}
// Array is safe to pass to DB if all the entries are passable
if (Array.isArray(value)) {
return value.every(queryValueIsSequelizeCompatible);
}
if (typeof value === 'object' && value) {
return Object.keys(value).every((key) => {
if (key === '$raw') {
return false; // avoid SQL injections on Sequelize v3
}
// Key isn't in the allowed list
if (ALL_SEQUELIZE_SIFT_COMPATIBLE_OPERATORS.indexOf(key) === -1) {
return false;
}
return queryValueIsSequelizeCompatible(value[key]);
});
}
return false;
}
function assignQuery(object, key, value) {
object = object || {};
// Key doesn't exist
if (!(key in object)) {
object[key] = value;
return;
}
// Key exists and value is an array
if (Array.isArray(object[key])) {
if...