Beispiel #1
0
		return function(method, model, options) {
			options = merge.defaults({}, options, defaults, gdef, { database: db });
			return Lazybones.sync.call(this, method, model, options);
		}
Beispiel #2
0
Lazybones.sync = function(method, model, options) {
	var self, dbMethod, db, onChange, promise, chgopts, chgfilter, processed, processPromise;

	// resolve method and database
	self = this;
	options = merge.defaults({}, options, getSyncOptions(model), getSyncOptions(model.collection), Lazybones.defaults);
	method = method.toLowerCase().trim();
	db = getDatabase(options) || getDatabase(model);
	if (db == null) throw new Error("Missing PouchDB database.");

	// deal with writes
	if (method !== "read") {
		promise = db[methodMap[method]](model.toJSON(), options.options[methodMap[method]]);
	}

	// deal with normal reads
	else if (!options.changes) {
		promise = options.fetch.call(self, model, db, options);
		if (promise == null || typeof promise.then !== "function") {
			promise = Promise.resolve(promise);
		}
	}

	// deal with changes feed reads
	else {
		chgopts = merge.defaults({
			include_docs: true
		}, options.changes, options.options.changes);

		if (typeof chgopts.filter === "function") {
			chgfilter = chgopts.filter;
			chgopts.filter = null;
		}

		promise = db.changes(chgopts);

		onChange = function(row) {
			var val = options.process.call(self, row, method, model, options);
			if (chgfilter && !chgfilter(val, row, options)) return;
			model.set(val, merge.extend({ remove: false }, options));
		}

		promise.on("create", onChange);
		promise.on("update", onChange);

		promise.on("delete", function(row) {
			var m = !isCollection(model) ? model : model.remove(row.id, options);

			if (m) {
				var val = options.process.call(self, row, method, model, options);
				m.set(val, options);
			}
		});

		// return the changes object immediately
		return promise;
	}

	// trigger the request event
	model.trigger('request', model, db, options);

	// process the result into something that backbone can use
	// and ship result to success and error callbacks
	return promise.then(function(res) {
		options.success(options.process.call(self, res, method, model, options));
		return res;
	}).catch(function(err) {
		options.error(err);
		throw err;
	});
}