-
Notifications
You must be signed in to change notification settings - Fork 76
/
pouch.js
273 lines (235 loc) · 7.93 KB
/
pouch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import Ember from 'ember';
import DS from 'ember-data';
import {
extractDeleteRecord
} from 'ember-pouch/utils';
const {
run: {
bind
},
on,
String: {
pluralize,
camelize,
classify
}
} = Ember;
export default DS.RESTAdapter.extend({
coalesceFindRequests: true,
// The change listener ensures that individual records are kept up to date
// when the data in the database changes. This makes ember-data 2.0's record
// reloading redundant.
shouldReloadRecord: function () { return false; },
shouldBackgroundReloadRecord: function () { return false; },
_onInit : on('init', function() {
this._startChangesToStoreListener();
}),
_startChangesToStoreListener: function () {
var db = this.get('db');
if (db) {
this.changes = db.changes({
since: 'now',
live: true,
returnDocs: false
}).on('change', bind(this, 'onChange'));
}
},
changeDb: function(db) {
if (this.changes) {
this.changes.cancel();
}
var store = this.store;
var schema = this._schema || [];
for (var i = 0, len = schema.length; i < len; i++) {
store.unloadAll(schema[i].singular);
}
this._schema = null;
this.set('db', db);
this._startChangesToStoreListener();
},
onChange: function (change) {
// If relational_pouch isn't initialized yet, there can't be any records
// in the store to update.
if (!this.get('db').rel) { return; }
var obj = this.get('db').rel.parseDocID(change.id);
// skip changes for non-relational_pouch docs. E.g., design docs.
if (!obj.type || !obj.id || obj.type === '') { return; }
var store = this.store;
try {
store.modelFor(obj.type);
} catch (e) {
// The record refers to a model which this version of the application
// does not have.
return;
}
var recordInStore = store.peekRecord(obj.type, obj.id);
if (!recordInStore) {
// The record hasn't been loaded into the store; no need to reload its data.
return;
}
if (!recordInStore.get('isLoaded') || recordInStore.get('hasDirtyAttributes')) {
// The record either hasn't loaded yet or has unpersisted local changes.
// In either case, we don't want to refresh it in the store
// (and for some substates, attempting to do so will result in an error).
return;
}
if (change.deleted) {
store.unloadRecord(recordInStore);
} else {
recordInStore.reload();
}
},
willDestroy: function() {
if (this.changes) {
this.changes.cancel();
}
},
_init: function (store, type) {
var self = this,
recordTypeName = this.getRecordTypeName(type);
if (!this.get('db') || typeof this.get('db') !== 'object') {
throw new Error('Please set the `db` property on the adapter.');
}
if (!Ember.get(type, 'attributes').has('rev')) {
var modelName = classify(recordTypeName);
throw new Error('Please add a `rev` attribute of type `string`' +
' on the ' + modelName + ' model.');
}
this._schema = this._schema || [];
var singular = recordTypeName;
var plural = pluralize(recordTypeName);
// check that we haven't already registered this model
for (var i = 0, len = this._schema.length; i < len; i++) {
var currentSchemaDef = this._schema[i];
if (currentSchemaDef.singular === singular) {
return;
}
}
var schemaDef = {
singular: singular,
plural: plural
};
if (type.documentType) {
schemaDef['documentType'] = type.documentType;
}
// else it's new, so update
this._schema.push(schemaDef);
// check all the subtypes
// We check the type of `rel.type`because with ember-data beta 19
// `rel.type` switched from DS.Model to string
type.eachRelationship(function (_, rel) {
if (rel.kind !== 'belongsTo' && rel.kind !== 'hasMany') {
// TODO: support inverse as well
return; // skip
}
var relDef = {},
relModel = (typeof rel.type === 'string' ? store.modelFor(rel.type) : rel.type);
if (relModel) {
relDef[rel.kind] = {
type: self.getRecordTypeName(relModel),
options: rel.options
};
if (!schemaDef.relations) {
schemaDef.relations = {};
}
schemaDef.relations[rel.key] = relDef;
self._init(store, relModel);
}
});
this.get('db').setSchema(this._schema);
},
_recordToData: function (store, type, record) {
var data = {};
// Though it would work to use the default recordTypeName for modelName &
// serializerKey here, these uses are conceptually distinct and may vary
// independently.
var modelName = type.modelName || type.typeKey;
var serializerKey = camelize(modelName);
var serializer = store.serializerFor(modelName);
serializer.serializeIntoHash(
data,
type,
record,
{includeId: true}
);
data = data[serializerKey];
// ember sets it to null automatically. don't need it.
if (data.rev === null) {
delete data.rev;
}
return data;
},
/**
* Returns the string to use for the model name part of the PouchDB document
* ID for records of the given ember-data type.
*
* This method uses the camelized version of the model name in order to
* preserve data compatibility with older versions of ember-pouch. See
* nolanlawson/ember-pouch#63 for a discussion.
*
* You can override this to change the behavior. If you do, be aware that you
* need to execute a data migration to ensure that any existing records are
* moved to the new IDs.
*/
getRecordTypeName(type) {
return camelize(type.modelName);
},
findAll: function(store, type /*, sinceToken */) {
// TODO: use sinceToken
this._init(store, type);
return this.get('db').rel.find(this.getRecordTypeName(type));
},
findMany: function(store, type, ids) {
this._init(store, type);
return this.get('db').rel.find(this.getRecordTypeName(type), ids);
},
findQuery: function(/* store, type, query */) {
throw new Error(
"findQuery not yet supported by ember-pouch. " +
"See https://github.com/nolanlawson/ember-pouch/issues/7.");
},
/**
* `find` has been deprecated in ED 1.13 and is replaced by 'new store
* methods', see: https://github.com/emberjs/data/pull/3306
* We keep the method for backward compatibility and forward calls to
* `findRecord`. This can be removed when the library drops support
* for deprecated methods.
*/
find: function (store, type, id) {
return this.findRecord(store, type, id);
},
findRecord: function (store, type, id) {
this._init(store, type);
var recordTypeName = this.getRecordTypeName(type);
return this.get('db').rel.find(recordTypeName, id).then(function (payload) {
// Ember Data chokes on empty payload, this function throws
// an error when the requested data is not found
if (typeof payload === 'object' && payload !== null) {
var singular = recordTypeName;
var plural = pluralize(recordTypeName);
var results = payload[singular] || payload[plural];
if (results && results.length > 0) {
return payload;
}
}
throw new Error('Not found: type "' + recordTypeName +
'" with id "' + id + '"');
});
},
createRecord: function(store, type, record) {
this._init(store, type);
var data = this._recordToData(store, type, record);
return this.get('db').rel.save(this.getRecordTypeName(type), data);
},
updateRecord: function (store, type, record) {
this._init(store, type);
var data = this._recordToData(store, type, record);
return this.get('db').rel.save(this.getRecordTypeName(type), data);
},
deleteRecord: function (store, type, record) {
this._init(store, type);
var data = this._recordToData(store, type, record);
return this.get('db').rel.del(this.getRecordTypeName(type), data)
.then(extractDeleteRecord);
}
});