Skip to content

Commit

Permalink
Added selectById
Browse files Browse the repository at this point in the history
  • Loading branch information
chronoDave committed Jul 18, 2024
1 parent 2605fe9 commit 283f4e1
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
- [`close()`](#close)
- [`insert()`](#insert)
- [`select()`](#select)
- [`selectById()`][#select-by-id]
- [`update()`](#update)
- [`delete()`](#delete)
- [`drop()`](#drop)
Expand Down Expand Up @@ -254,6 +255,21 @@ const docs = db.select({ name: 'Mipha' });
const docs = db.select({ name: 'Mipha' }, { name: 'Tulin' });
```

### `selectById()`

Find document(s) based on `_id`. Multiple ids can be used.

```TS
import LeafDB from 'leaf-db';

const db = new LeafDB('db');

// Return docs where `_id` is equal to `Mipha`
const docs = db.selectById('Mipha');
// Return docs where `_id` is equal to `Mipha` or where `_id` is equal to `Tulin`
const docs = db.selectById('Mipha', 'Tulin');
```

### `update()`

Update document(s) based on [query](#queries). Multiple queries can be used. Updated document cannot change shape.
Expand Down
8 changes: 8 additions & 0 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,14 @@ export default class LeafDB<T extends Draft> {
return docs;
}

selectById(...ids: string[]) {
return ids.reduce<Array<Doc<T>>>((acc, cur) => {
const doc = this._memory.get(cur);
if (doc) acc.push(doc);
return acc;
}, []);
}

update(update: Update<Doc<T>>, ...queries: Array<Query<Doc<T>>>) {
if ('_id' in update) throw new Error('Invalid update, cannot contain key `_id`');

Expand Down
24 changes: 24 additions & 0 deletions test/unit/model/model.selectById.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import test from 'tape';

import type { Doc } from './fixture';
import setup, { memory } from './fixture';

test('[model.selectById] returns docs on empty query', t => {
const { db } = setup<Doc>({ memory });

const docs = db.selectById();
t.true(Array.isArray(docs), 'is array');
t.strictEqual(docs.length, 0, 'finds docs (empty)');

t.end();
});

test('[model.selectById] returns docs on id match', t => {
const { db } = setup<Doc>({ memory });

const docs = db.selectById('2', '6');
t.strictEqual(docs.length, 2, 'finds docs');
t.strictEqual(docs[0].name, 'Aarhus', 'finds correct docs');

t.end();
});

0 comments on commit 283f4e1

Please sign in to comment.