Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getValues method for fetching array of docs from collection #306

Merged
merged 3 commits into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/Model/collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Doc } from './Doc';
import { Model, RootModel } from './Model';
import { JSONObject } from 'sharedb/lib/sharedb';
import type { Path, ReadonlyDeep, ShallowCopiedValue, Segments } from '../types';

var LocalDoc = require('./LocalDoc');
var util = require('../util');

Expand Down Expand Up @@ -78,6 +79,14 @@ declare module './Model' {
_get(segments: Segments): any;
_getCopy(segments: Segments): any;
_getDeepCopy(segments: Segments): any;

/**
* Gets array of values of collection at this models path or relative subpath
*
* If no values exist at subpath, an empty array is returned
* @param subpath
*/
getValues<S>(subpath?: Path): ReadonlyDeep<S>[];
}
}

Expand Down Expand Up @@ -124,6 +133,10 @@ Model.prototype._getDeepCopy = function(segments) {
return util.deepCopy(value);
};

Model.prototype.getValues = function<S>(subpath?: Path) {
return this.filter(subpath, null).get();
}

Model.prototype.getOrCreateCollection = function(name) {
var collection = this.root.collections[name];
if (collection) return collection;
Expand Down
30 changes: 30 additions & 0 deletions test/Model/collections.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const {expect} = require('../util');
const {RootModel} = require('../../lib');

describe('collections', () => {
describe('getValues', () => {
it('returns array of values from collection', () => {
const model = new RootModel();
model.add('_test_docs', {name: 'foo'});
model.add('_test_docs', {name: 'bar'});

const values = model.getValues('_test_docs');

expect(values).to.be.instanceOf(Array);
expect(values).to.have.lengthOf(2);

['foo', 'bar'].forEach((value, index) => {
expect(values[index]).to.have.property('name', value);
});
});

it('return empty array when no values at subpath', () => {
const model = new RootModel();

const values = model.getValues('_test_docs');

expect(values).to.be.instanceOf(Array);
expect(values).to.have.lengthOf(0);
});
});
});
Loading