Skip to content
This repository has been archived by the owner on Sep 30, 2023. It is now read-only.

Commit

Permalink
Merge pull request #36 from orbitdb/feat/put-all-v2
Browse files Browse the repository at this point in the history
Add `putAll()` function
  • Loading branch information
aphelionz authored May 12, 2020
2 parents eff9c11 + 893ee60 commit 11a8c0e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
15 changes: 13 additions & 2 deletions src/DocumentIndex.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,20 @@ class DocumentIndex {

updateIndex (oplog, onProgressCallback) {
const reducer = (handled, item, idx) => {
if (handled[item.payload.key] !== true) {
if (item.payload.op === 'PUTALL') {
for (const doc of item.payload.docs) {
if (handled[doc.key] !== true) {
handled[doc.key] = true
this._index[doc.key] = {
op: item.payload.op,
key: doc.key,
value: doc.value
}
}
}
} else if (handled[item.payload.key] !== true) {
handled[item.payload.key] = true
if(item.payload.op === 'PUT') {
if (item.payload.op === 'PUT') {
this._index[item.payload.key] = item
} else if (item.payload.op === 'DEL') {
delete this._index[item.payload.key]
Expand Down
20 changes: 16 additions & 4 deletions src/DocumentStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ class DocumentStore extends Store {
}

put (doc, options = {}) {
if (!doc[this.options.indexBy])
throw new Error(`The provided document doesn't contain field '${this.options.indexBy}'`)
if (!doc[this.options.indexBy]) { throw new Error(`The provided document doesn't contain field '${this.options.indexBy}'`) }

return this._addOperation({
op: 'PUT',
Expand All @@ -75,9 +74,22 @@ class DocumentStore extends Store {
}, options)
}

putAll (docs, options = {}) {
if (!(Array.isArray(docs))) {
docs = [docs]
}
if (!(docs.every(d => d[this.options.indexBy]))) { throw new Error(`The provided document doesn't contain field '${this.options.indexBy}'`) }
return this._addOperation({
op: 'PUTALL',
docs: docs.map((value) => ({
key: value[this.options.indexBy],
value
}))
}, options)
}

del (key, options = {}) {
if (!this._index.get(key))
throw new Error(`No entry with key '${key}' in the database`)
if (!this._index.get(key)) { throw new Error(`No entry with key '${key}' in the database`) }

return this._addOperation({
op: 'DEL',
Expand Down

0 comments on commit 11a8c0e

Please sign in to comment.