synopsis-client
Version:
A client that connects to a synopsis-backend for simple data storage
62 lines (48 loc) • 1.62 kB
JavaScript
module.exports = PersonalStore;
var Store = require('./index');
var dynamicDuplex = require('dynamic-duplex');
var defaults = require('defaults');
function PersonalStore(name, options) {
var authHash = null;
var store = null;
var debug = require('debug')('store:personal:' + name);
var duplexStream = dynamicDuplex(function(authChange, enc, cb) {
var newAuthHash = authChange.auth && authChange.profile ? authChange.auth.network + '-' + authChange.profile.id : null;
if (authHash === newAuthHash) {
return cb(null, store);
}
if (store) {
store.destroy()
}
if (authChange && authChange.auth) {
options = defaults(options, {
auth: {
network: authChange.auth.network,
access_token: authChange.auth.authResponse.access_token,
profile: authChange.profile.id
}
});
var storeName = 'p-' + name + '-' + newAuthHash;
store = new Store(storeName, options);
authHash = newAuthHash;
duplexStream.edit = store.edit.bind(store);
store.on('bootstrap-error', function(err) {
debug('bubbling up bootstrap-error', err);
duplexStream.emit('bootstrap-error', err);
});
store.on('update-error', function(err) {
debug('bubbling up update-error', err);
duplexStream.emit('update-error', err);
});
cb(null, store);
} else {
authHash = null;
store = null;
duplexStream.edit = function() {
debug('attempting to edit a disconnected personal stream');
};
cb(null, null);
}
});
return duplexStream;
};