Skip to content

Commit

Permalink
fix: empty query bug
Browse files Browse the repository at this point in the history
  • Loading branch information
markwylde committed Dec 24, 2024
1 parent d55fb8b commit 20564ae
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 29 deletions.
30 changes: 1 addition & 29 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,35 +331,7 @@ async function createDoubleDb(dataDirectory: string): Promise<DoubleDb> {

async function query(queryObject?: object, options?: { limit?: number; offset?: number; sort?: { [key: string]: 1 | -1 }; project?: { [key: string]: 1 } }): Promise<Document[]> {
if (!queryObject || Object.keys(queryObject).length === 0) {
const allIds = await getAllIds();
let results = await Promise.all([...allIds].map(id => read(id)));
const offset = options?.offset ?? 0;
const limit = options?.limit ?? results.length;

if (options?.sort) {
const sortFields = Object.entries(options.sort);
results.sort((a, b) => {
for (const [field, direction] of sortFields) {
if (a[field] < b[field]) return direction === 1 ? -1 : 1;
if (a[field] > b[field]) return direction === 1 ? 1 : -1;
}
return 0;
});
}

if (options?.project) {
results = results.map(doc => {
const projected: Document = {};
for (const field of Object.keys(options.project)) {
if (field in doc) {
projected[field] = doc[field];
}
}
return projected;
});
}

return results.filter((doc): doc is Document => doc !== undefined).slice(offset, offset + limit);
queryObject = { id: { $exists: true } };
}

let resultIds = new Set<string>();
Expand Down
14 changes: 14 additions & 0 deletions test/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ test('empty query', async () => {
await db.close();
});

test('special characters', async () => {
const db = await setupTestDb();
await db.insert({ id: 'users/mark', name: 'Mark' });
await db.insert({ id: 'users/joe', name: 'Joe' });
await db.insert({ id: 'users/mary', name: 'Mary' });
await db.insert({ id: 'groups/standard', name: 'Standard' });
await db.insert({ id: 'groups/admin', name: 'Admin' });
await db.insert({ id: 'rootD', name: 'rootD' });

const result = await db.query();
assert.strictEqual(result.length, 6);
await db.close();
});

test('$sw operator on string', async () => {
const db = await setupTestDb();
await db.insert({ value: 'alpha' });
Expand Down

0 comments on commit 20564ae

Please sign in to comment.