Skip to content

Instantly share code, notes, and snippets.

@matb33
Last active December 15, 2015 23:29
Show Gist options
  • Save matb33/5340487 to your computer and use it in GitHub Desktop.
Save matb33/5340487 to your computer and use it in GitHub Desktop.
SyncObject smart package for Meteor. Drop this in your Meteor app /packages/syncobject/
ServerTime = (function () {
var sync = new Meteor.SyncObject("serverTime");
var intervalId;
function updateTime() {
sync.set({ms: Date.now()});
}
function updateInterval(intervalMs) {
Meteor.clearInterval(intervalId);
intervalId = Meteor.setInterval(updateTime, intervalMs);
updateTime();
}
function getTimeMs() {
var obj = sync.get();
return obj ? obj.ms : Date.now();
}
if (Meteor.isServer) {
sync.bind(function (intervalMs) {
updateInterval(intervalMs);
});
}
if (Meteor.isClient) {
sync.bind(1000);
}
return {
getTimeMs: getTimeMs
};
})();
Package.describe({
summary: "sync server-persisted objects between server and client"
});
Package.on_use(function (api, where) {
api.add_files("syncobject.js", ["client", "server"]);
});
Meteor.SyncObject = (function () {
return function (name, allow) {
var self = this;
var collectionName = "SyncObject_" + name;
var subName = "SyncObjectSub_" + name;
function subscribe(/* optional parameters */) {
if (Meteor.isClient) {
Meteor.subscribe.apply(self, [subName].concat(Array.prototype.slice.call(arguments)));
}
}
function publish(callback) {
if (Meteor.isServer) {
Meteor.startup(function () {
Meteor.publish(subName, function (/* parameters */) {
if (typeof callback === "function") {
callback.apply(self, Array.prototype.slice.call(arguments));
}
return self.collection.find();
});
});
// Default permissions are server-only access
allow({
insert: function () { return false; },
update: function () { return false; },
remove: function () { return false; }
});
}
}
function set(obj) {
var doc = self.collection.findOne();
if (doc) {
return self.collection.update({_id: doc._id}, {$set: obj});
} else {
return self.collection.insert(obj);
}
}
function get() {
return self.collection.findOne();
}
function allow(rules) {
self.collection.allow(rules);
}
function deny(rules) {
self.collection.deny(rules);
}
self.collection = new Meteor.Collection(collectionName);
if (Meteor.isServer) {
return {
bind: publish,
publish: publish,
set: set,
get: get,
allow: allow,
deny: deny
};
}
if (Meteor.isClient) {
return {
bind: subscribe,
subscribe: subscribe,
set: set,
get: get
};
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment