forked from samlown/backbone-cradle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
114 lines (98 loc) · 3.25 KB
/
index.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
var _ = require('underscore');
var Backbone = require('backbone');
// A model subclass that uses our sync.
var Model = Backbone.Model.extend({
// Use the collection database by default. Override this and set it to a
// function or instance of a database to use another.
database: function() {
if (this.collection) {
return _.result(this.collection, 'database');
}
},
// Use `_id` as the identifier, to match CouchDB.
idAttribute: '_id',
// Whether it's okay if the record is missing.
allowMissing: true,
// Override sync with ours.
sync: function(method, model, options) {
var db = _.result(model, 'database');
var success = options.success || function() {};
var error = options.error || function() {};
switch (method) {
case 'read':
db.get(model.id, function(err, doc) {
if (!err) {
success(model, doc, options);
}
else if (err.error === 'not_found' && model.allowMissing) {
success(model, {}, options);
}
else {
error(err);
}
});
break;
case 'create':
case 'update':
db.insert(model.toJSON(), function(err, res) {
if (err) {
error(model, err, options);
}
else {
success(model, { _id: res.id, _rev: res.rev }, options);
}
});
break;
case 'delete':
db.destroy(model.id, model.get('_rev'), function(err, res) {
if (err) {
error(model, err, options);
}
else {
success(model, { _id: res.id, _rev: res.rev }, options);
}
});
break;
}
}
});
// A collection subclass that uses our sync.
var Collection = Backbone.Collection.extend({
// Override this and set it to a function or instance of a database.
database: null,
// The call to read all the documents. You usually want to override this
// with a call to `db.view()` instead.
read: function(db, callback) {
db.list({ include_docs: true }, callback);
},
// Provide a default `parse` override that extracts documents.
parse: function(res) {
return _.pluck(res.rows, 'doc');
},
// Override sync with ours.
sync: function(method, model, options) {
var db = _.result(model, 'database');
var success = options.success || function() {};
var error = options.error || function() {};
switch (method) {
case 'read':
model.read(db, function(err, res) {
if (err)
error(model, err, options);
else
success(model, res, options);
});
break;
}
}
});
// Create a scope for the given database.
var bbnano = module.exports = function(db) {
return {
Model: Model.extend({ database: db }),
Collection: Collection.extend({ database: db })
};
};
// Export the subclasses.
bbnano.Model = Model;
bbnano.Collection = Collection;