JSFiddle - React, Tailwind, and code Playground
by evan
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.13.6/underscore-min.js"></script>
<pre id="log"></pre>
CSS
html, body {
display: flex;
width: 100%;
height: 100%;
}
textarea {
font-family: monospace;
width: 100%;
height: 100%;
}
JavaScript
// 2023-10-11:
// The following function is in response to an incident where Connect service was
// degraded due to a change in the Mongo driver behavior for .count(). Specifically,
// .count now leverages an aggregate. In the event the selector is effectively empty,
// Mongo (at least in version 4.4) doesn't understand what index to fall back to. The filter
// observed looked something like: { $and: [ {}, {} ] }. This is what we're guarding against here.
const isSelectorSeeminglyEmpty = (selector) => {
if (_.isEmpty(selector)) {
return true;
}
if (!_.isObject(selector)) {
return false;
}
const hasKeysOtherThanAnd = Object.keys(selector).length !== 1 || !selector.$and;
// It's out of scope of this function to evaluate stuff beyond the $and.
// That was a deliberate choice.
if (hasKeysOtherThanAnd) {
return false;
}
// sanity check before just expecting that $and is an array
if (!Array.isArray(selector.$and)) {
return false;
}
// nb: future improvment might be to just call
// isSelectorSeeminglyEmpty as the predicate.
return selector.$and.every((v) => _.isEmpty(v));
}
const isQueryEmpty = isSelectorSeeminglyEmpty;
function expect(test, value, name) {
const result = test === value;
document.getElementById('log').innerText += `${result ? '🟢' : '❌'} - ${name} ${value ? 'is empty' : 'is not empty'} (saw ${test})\n`
}
function test(query, pass) {
expect(isQueryEmpty(query), pass, JSON.stringify(query));
}
test(1, false);
test({}, true);
test({$and: [{}, {}]}, true);
test({$and: [{}, {}, {'a': 1}]}, false);
test({$and: [{}, {}]}, true);
test({_id: '123'}, false);
test({_id: '123', $and: [{}, {}]}, false);
test({_id: '123', $and: [{a: 1}, {}]}, false);