Skip to content

Commit 75afd67

Browse files
authored
feat(loki): return an existing collection if a collection with the same name already exists (#77)
See techfort/LokiJS@60c6c57
1 parent 2d44384 commit 75afd67

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

packages/loki/spec/generic/collection.spec.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ describe("collection", () => {
4444
expect(result.name).toEqual("coll2");
4545
});
4646

47+
it("add existing collection name works", function () {
48+
const db = new Loki("test.db");
49+
const coll1 = db.addCollection("coll1");
50+
const coll2 = db.addCollection("coll1");
51+
expect(coll1).toEqual(coll2);
52+
});
53+
4754
it("findAndUpdate works", () => {
4855
const db = new Loki("test.db");
4956
const coll = db.addCollection<CL>("testcoll");

packages/loki/src/loki.ts

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,13 @@ export class Loki extends LokiEventEmitter {
249249
* @returns {Collection} a reference to the collection which was just added
250250
*/
251251
public addCollection<T extends object = object, U extends object = object>(name: string, options: Collection.Options<T> = {}): Collection<T, U> {
252+
// Return an existing collection if a collection with the same name already exists.
253+
for (let i = 0; i < this._collections.length; i++) {
254+
if (this._collections[i].name === name) {
255+
return this._collections[i] as Collection<T, U>;
256+
}
257+
}
258+
// Create a new collection otherwise.
252259
const collection = new Collection<T, U>(name, options);
253260
this._collections.push(collection);
254261

@@ -267,21 +274,18 @@ export class Loki extends LokiEventEmitter {
267274

268275
/**
269276
* Retrieves reference to a collection by name.
270-
* @param {string} collectionName - name of collection to look up
277+
* @param {string} name - name of collection to look up
271278
* @returns {Collection} Reference to collection in database by that name, or null if not found
272279
*/
273-
public getCollection<T extends object = object>(collectionName: string): Collection<T> {
274-
let i;
275-
const len = this._collections.length;
276-
277-
for (i = 0; i < len; i++) {
278-
if (this._collections[i].name === collectionName) {
279-
return this._collections[i] as Collection<T>;
280+
public getCollection<T extends object = object, U extends object = object>(name: string): Collection<T, U> {
281+
for (let i = 0; i < this._collections.length; i++) {
282+
if (this._collections[i].name === name) {
283+
return this._collections[i] as Collection<T, U>;
280284
}
281285
}
282286

283287
// no such collection
284-
this.emit("warning", "collection " + collectionName + " not found");
288+
this.emit("warning", "collection " + name + " not found");
285289
return null;
286290
}
287291

0 commit comments

Comments
 (0)