Skip to content

Commit 7c238ff

Browse files
committed
fix: support multiple createRecord calls (fixes #239)
This commit changes how ember-pouch implements `Adapter.createRecord`, which is invoked after calling `.save()` on a new record, so that it does not create multiple records if `.save()` is called more than once before the first operation has finished. If `.save()` is only invoked once before the record has finished persisting to the DB (i.e. the promise that it returns has resolved) then the behavior is unchanged. However, subsequent calls will wait for the previously returned promise to resolve and then, if changes have been made to the record, as indicated by Snapshot#changedAttributes, it will delegate the task to `updateRecord`. To avoid a problem caused by ember-data changing the ID associated with the internalModel/record when the record has finished persisting, the `Adapter.generateIdForRecord` method has been implemented so that the ID is available immediately. Previously ember-pouch had still been generating this id during `createRecord`, but ember-data was not being made aware of this until its returned promise resolved. Also, rather than rely on `adapter.db.rel.uuid()` to generate an RFC4122 v4 UUID (requiring initialization to have completed), this has been replaced by the equivalent `uuid` module from npm, and the ember-auto-import addon has been installed to make it easy to access this from within ember-pouch. Finally, the `engines` section of package.json has been updated to align with ember-auto-import's minimum version of 6.x BREAKING CHANGE: drop node 4.x support (and 6.x/7.x not tested by CI)
1 parent 9bfde5c commit 7c238ff

File tree

3 files changed

+66
-20
lines changed

3 files changed

+66
-20
lines changed

addon/adapters/pouch.js

Lines changed: 53 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import Ember from 'ember';
22
import DS from 'ember-data';
33
import { pluralize } from 'ember-inflector';
4+
import { v4 } from 'uuid';
45
//import BelongsToRelationship from 'ember-data/-private/system/relationships/state/belongs-to';
56

67
import {
@@ -9,6 +10,20 @@ import {
910
configFlagDisabled
1011
} from '../utils';
1112

13+
function getRevFromSaveResult(records) {
14+
let rev = null;
15+
try {
16+
rev = records[Object.keys(records)[0]][0].rev;
17+
if (!rev || Object.keys(records).length > 1) {
18+
// eslint-disable-next-line no-console
19+
console.warn(`getRevFromSaveResult going to return ${rev}, but that may not be correct`);
20+
}
21+
} catch(e) {
22+
throw Error(`Could not determine rev`);
23+
}
24+
return rev;
25+
}
26+
1227
const {
1328
getOwner,
1429
run: {
@@ -153,7 +168,7 @@ export default DS.RESTAdapter.extend({
153168
willDestroy: function() {
154169
this._stopChangesListener();
155170
},
156-
171+
157172
_indexPromises: [],
158173

159174
_init: function (store, type) {
@@ -206,8 +221,9 @@ export default DS.RESTAdapter.extend({
206221
relModel = (typeof rel.type === 'string' ? store.modelFor(rel.type) : rel.type);
207222
if (relModel) {
208223
let includeRel = true;
209-
if (!('options' in rel)) rel.options = {};
210-
224+
if (!('options' in rel)) {
225+
rel.options = {};
226+
}
211227
if (typeof(rel.options.async) === "undefined") {
212228
rel.options.async = config.emberPouch && !Ember.isEmpty(config.emberPouch.async) ? config.emberPouch.async : true;//default true from https://github.com/emberjs/data/pull/3366
213229
}
@@ -464,27 +480,47 @@ export default DS.RESTAdapter.extend({
464480
});
465481
},
466482

483+
generateIdForRecord: function(/* store, type, inputProperties */) {
484+
return v4();
485+
},
486+
467487
createdRecords: {},
468-
createRecord: function(store, type, record) {
469-
this._init(store, type);
470-
var data = this._recordToData(store, type, record);
471-
let rel = this.get('db').rel;
472-
473-
let id = data.id;
474-
if (!id) {
475-
id = data.id = rel.uuid();
488+
createRecord: function(store, type, snapshot) {
489+
const record = snapshot.record;
490+
if (record._emberPouchSavePromise) {
491+
const changes = record.changedAttributes();
492+
record._emberPouchSavePromise = record._emberPouchSavePromise.then(records => {
493+
// If there have been changes since the document was created then we should update the record now
494+
if (Object.keys(changes).length > 0) {
495+
// Include latest rev to indicate that we're aware that data has changed since original request
496+
// (otherwise a document update conflict error would be thrown by the DB)
497+
snapshot._attributes.rev = getRevFromSaveResult(records);
498+
return this.updateRecord(store, type, snapshot);
499+
}
500+
return records;
501+
});
502+
return record._emberPouchSavePromise;
476503
}
504+
505+
this._init(store, type);
506+
var data = this._recordToData(store, type, snapshot);
507+
const rel = this.get('db').rel;
508+
const id = data.id;
477509
this.createdRecords[id] = true;
478-
479-
return rel.save(this.getRecordTypeName(type), data).catch((e) => {
480-
delete this.createdRecords[id];
481-
throw e;
510+
Object.defineProperty(record, '_emberPouchSavePromise', {
511+
enumerable: false,
512+
writable: true,
513+
value: rel.save(this.getRecordTypeName(type), data).catch((e) => {
514+
delete this.createdRecords[id];
515+
throw e;
516+
}),
482517
});
518+
return record._emberPouchSavePromise;
483519
},
484520

485-
updateRecord: function (store, type, record) {
521+
updateRecord: function (store, type, snapshot) {
486522
this._init(store, type);
487-
var data = this._recordToData(store, type, record);
523+
var data = this._recordToData(store, type, snapshot);
488524
return this.get('db').rel.save(this.getRecordTypeName(type), data);
489525
},
490526

ember-cli-build.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,15 @@ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon');
55

66
module.exports = function(defaults) {
77
let app = new EmberAddon(defaults, {
8-
// Add options here
8+
autoImport: {
9+
webpack: {
10+
node: {
11+
global: true
12+
}
13+
},
14+
// We could use ember-auto-import for these, but index.js is already handling them
15+
exclude: ['pouchdb', 'pouchdb-find', 'relational-pouch']
16+
}
917
});
1018

1119
/*

package.json

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
"CouchDB"
2727
],
2828
"engines": {
29-
"node": "^4.5 || 6.* || >= 7.*"
29+
"node": ">= 6.*"
3030
},
3131
"author": "Nolan Lawson",
3232
"license": "Apache-2.0",
@@ -62,9 +62,11 @@
6262
"dependencies": {
6363
"broccoli-file-creator": "^2.1.1",
6464
"broccoli-stew": "^2.1.0",
65+
"ember-auto-import": "^1.5.3",
66+
"ember-cli-babel": "^7.7.3",
6567
"pouchdb": "^7.1.1",
6668
"relational-pouch": "^3.1.0",
67-
"ember-cli-babel": "^7.7.3"
69+
"uuid": "^3.3.3"
6870
},
6971
"ember-addon": {
7072
"configPath": "tests/dummy/config"

0 commit comments

Comments
 (0)