feat: improve MongoDB query assistance

This commit is contained in:
林剑凛 authored and GitHub committed 2026-06-19 23:59:34 +08:00
1 parent 8b6eb353db
commit 39ced46282
7 files changed
+976 -35

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
import { strict as assert } from "node:assert";
import { test } from "vitest";
import { formatMongoShellText, MAX_MONGO_FORMAT_CHARS } from "../../apps/desktop/src/lib/mongoFormatter.ts";
test("formats MongoDB find query objects", () => {
assert.equal(
formatMongoShellText('db.characters.find({name:"Ada",age:{$gte:18,$lt:30}}).sort({createdAt:-1}).limit(20)'),
`db.characters.find({
name: "Ada",
age: {
$gte: 18,
$lt: 30
}
})
.sort({
createdAt: -1
})
.limit(20)`,
);
});
test("formats MongoDB aggregation pipelines", () => {
assert.equal(
formatMongoShellText('db.orders.aggregate([{$match:{status:"paid"}},{$group:{_id:"$userId",total:{$sum:"$amount"}}}])'),
`db.orders.aggregate([
{
$match: {
status: "paid"
}
},
{
$group: {
_id: "$userId",
total: {
$sum: "$amount"
}
}
}
])`,
);
});
test("preserves strings, regex literals, and comments", () => {
assert.equal(
formatMongoShellText('db.users.find({name:/a,b\\/c/i,note:"x,y",active:true}) // keep comment'),
`db.users.find({
name: /a,b\\/c/i,
note: "x,y",
active: true
}) // keep comment`,
);
});
test("respects tab indentation setting", () => {
assert.equal(
formatMongoShellText("db.users.find({name:'Ada'})", { useTabs: true, tabWidth: 4 }),
"db.users.find({\n\tname: 'Ada'\n})",
);
});
test("leaves blank MongoDB text unchanged", () => {
assert.equal(formatMongoShellText(" \n\t"), " \n\t");
});
test("rejects very large MongoDB queries", () => {
assert.throws(() => formatMongoShellText("x".repeat(MAX_MONGO_FORMAT_CHARS + 1)), /too large/i);
});