authenticate: function(username, password, callback) { nano(options.couchdbUrl).auth( username, password, function(error, body, headers) { if (error || !body.ok) { if (error.code === 'ECONNREFUSED') { return reply(error, null, null); } return callback( Boom.unauthorized(null, 'couchdb-cookie'), null ); } var cookieData; if (headers && headers['set-cookie']) { cookieData = cookie.parse(headers['set-cookie'][0]); reply.state( 'AuthSession', cookieData.AuthSession, { path: cookieData.Path } ); } callback(null, body); } ); },
function DataAccesObject(config) { if(config == null) { console.log('Invalid Database Parameter!! EXITING'); return; } var dbConfig = config; var nano = require('nano'); var couch = nano(dbConfig.uri + ":" + dbConfig.port); var db = couch.use(dbConfig.database); function putNewEntry(data) { db.insert(data, function(err) { if(err) console.log(err); }) } function listEntries(func) { db.list(func); } function getEntry(data_id, func) { db.get(data_id, func); } return { newEntry: putNewEntry, list: listEntries, getEntry: getEntry, }; }
adapter.registerSingleCollection = function registerCollection(connection, collectionName, collection, cb) { var url = urlForConfig(connection); var db = nano(url); db.db.get(collectionName, gotDatabase); function gotDatabase(err) { if (err && err.status_code == 404 && err.reason == 'no_db_file') { db.db.create(collectionName, createdDB); } else { registry.collection(collectionName, collection); registry.db(collectionName, nano(url + collectionName)); cb(); } } function createdDB(err) { if (err) { cb(err); } else { adapter.registerSingleCollection(connection, collectionName, collection, cb); } } };
db.db.get(collectionName, function gotDatabase(err) { // No error means we're good! The collection (or in couch terms, the "db") // is already known and ready to use. if (!err) { registry.collection(collectionName, collection); registry.db(collectionName, nano(url + collectionName)); return cb(); } try { if (err.status_code == 404 && err.reason == 'no_db_file') { db.db.create(collectionName, function createdDB(err) { if (err) { return cb(err); } adapter.registerSingleCollection(connection, collectionName, collection, cb); }); return; } // console.log('unexpected ERROR', err); return cb(err); } catch (e) { return cb(e); } });
module.exports = function() { function with_log(json) { var diff = process.hrtime(json.ns); json.ns = 1e9 * diff[0] + diff[1], json.event = options.event, d.couch.insert(json, function(error) { error ? console.error(error) : timeout = setTimeout(query, d.timeout); }), log(options.logger.log); } function without_log(json) { var diff = process.hrtime(json.ns); json.ns = 1e9 * diff[0] + diff[1], d.couch.insert(json, function(error) { error ? console.error(error) : timeout = setTimeout(query, d.timeout); }); } function query() { clearTimeout(timeout); var json = require(options.min + "lib/obj.js").dynamics(); net ? (json.net = options.net, json.io = options.io, end(json), io && (net(), io())) : end(json); } var timeout, log, net, io, options = global.monitode, d = options.db, end = without_log; options.os && (options.monitor.os ? (options.monitor.os = !1, net = require(options.min + "lib/net.js")(), io = require(options.min + "lib/io.js")()) : net = !0), options.logger.log && (end = with_log, options.monitor.log ? (options.monitor.log = !1, log = require(options.min + "lib/log.js")) : log = function() {}), d.couch = CLIENT(d.couch), options.output && console.log("starting monitor on CouchDb database"), query(); };
adapter.drop = function drop(connectionName, collectionName, relations, cb) { collectionName = sanitizeCollectionName(collectionName); var connection = registry.connection(connectionName); var url = urlForConfig(connection); var db = nano(url); db.db.destroy(collectionName, cb); };
/** * Run whole setup process. * @param {Object} cfg * @param {Object} auth * @return {String|Object} success msg/bulkFN result */ async function setupAsync(cfg, auth={user:'', password:''}) { const funcName = '[setupAsync]'; const authURL = _getAuthURL(cfg, auth); // Create database, if missing. await addDatabase(cfg, authURL); const dbURL = `${authURL}/${cfg.get('databaseName')}`; console.debug(funcName, dbURL, cfg.defaults.designDoc); const nanoDriver = nano(authURL); const db = nanoDriver.use(cfg.get('databaseName')); const bulkFn = util.promisify(db.bulk); // Load design doc & default docs. const docs = [ JSON.parse(fs.readFileSync(cfg.defaults.designDoc)) ]; _.forEach(fs.readdirSync(cfg.defaults.docs), (docName) => { docs.push(JSON.parse(fs.readFileSync(path.join(cfg.defaults.docs, docName)))); }); // Upload docs. return bulkFn({docs}).then(() => { console.debug(funcName, 'Added all docs.'); return "Complete."; }, (msgData) => { console.warn(funcName, 'Failed to add docs.'); throw msgData; }); }
module.exports = function (dbUrl) { var db = Promise.promisifyAll(nano(dbUrl)) // create view if exists putIfExists(db, doc, '_design/compact') return function () { return R.pipeP( db.viewAsync, R.nth(0), R.path(['rows']), R.map(R.path(['value'])), docsObj, db.bulkAsync, compactDocs )('compact', 'docs') } function compactDocs () { return db.compactAsync() } function docsObj (docs) { return { docs: docs } } }
this.init = () => { if (process.env.host_db == 'localhost') { console.log("BD en local"); // bd en local (CouchDb) var db = nano(this.BD_LOCAL_HOST); this.clientDB = prom(db).db.use(process.env.cloudant_database); } else if (process.env.host_db == 'cloudant') { console.log('en init()'); //credenciales para cloudant var me = process.env.cloudant_username || "nodejs", password = process.env.cloudant_password, databaseName = process.env.cloudant_database; var db = Cloudant({ account: me, password: password }); this.clientDB = prom(db).db.use(databaseName); } //this.client = new Client("http://localhost:5984", "visio"); //console.log(this.client); /* var cloudant = Cloudant({ account: "irodgal", password: "******" }); //console.log(cloudant); this.client = cloudant.db.use("visio"); console.log(this.client); */ /* var db = nano('http://localhost:5984'); this.client = db.db.use("visio"); console.log(this.client); */ //var db = nano('http://localhost:5984'); //var db = Cloudant({ account: "irodgal", password: "******" }); //this.clientDB = prom(db).db.use('visio'); //this.client = prom(nano('http://localhost:5984')).db.use('visio'); //console.log(this.client); //this.client. };
before(function () { // set up db connections this.collection = 'orchestrate-couchdb'; this.nano = nano('http://localhost:5984'); this.couchdb = this.nano.use(this.collection); this.orc = orchestrate(process.env.ORCHESTRATE_API_KEY); });
module.exports = function(config) { var extendDoc = config.extendDoc; var bulkWriteIntervalSeconds = config.writeIntervalSeconds || 60; var dbUrl = config.dbUrl || process.env.CLOUDANT_URL; var db = nano(dbUrl + '/' + config.dbName); var hits = []; app.get('/pixie-([a-zA-Z0-9]+).gif', function(req, res){ var referer = req.get('Referer'); var refHostname = url.parse(referer + '').hostname; var hit = { pixie: req.params[0], ip: req.ip, url: req.url, referer: referer, ref_hostname: refHostname, time: new Date().getTime() }; if (extendDoc) hit = _.extend(hit, extendDoc(req)); console.log('pixie-tracked:', JSON.stringify(hit)); hits.push(hit); res.type('gif'); res.send(imageBuf); }); var bulkWrite = function() { if (hits.length === 0) return; var bulk = hits.splice(0, hits.length); db.bulk({docs: bulk}, function(err, docs){ if (err) { console.log(err); hits = hits.concat(bulk); } else { console.log('Wrote', bulk.length, "docs to storage"); } }); }; return { listen: function(port, callback) { app.listen(port, function(){ console.log('Pixie listening on port', port); if (callback) callback(); }); setInterval(bulkWrite, bulkWriteIntervalSeconds * 1000); } }; };
cp.exec('git rev-list HEAD --max-count=1', function(err, stdout, stderr) { var results = { started: testStartTime, completed: new Date(), git_hash: stdout.replace(/[\n\r]/g, ''), passed: true, runs: {}, runner: 'grunt' }; for (var key in testResults) { results.runs[key] = { started: testResults[key].started || "", completed: testResults[key].completed || "", passed: !!(testResults[key].passed), report: testResults[key] }; console.log("Test Result for %s is %s".yellow , key , results.runs[key].passed); results.passed = results.passed && results.runs[key].passed; } nano(grunt.config("publish-results.server")) .use(grunt.config("publish-results.db")) .insert(results, testStartTime.getTime() + "", function(err, body){ console.log(testStartTime.getTime(), err ? err.message : body); done(results.passed && err == null); }); });
var CouchDBSource = module.exports = function(options) { options = options || {}; this.db = nano(options.db); if(options.id) { this.ids = options.id.push ? options.id : [options.id]; } };
function connect() { var username = "******"; var password = "******"; var dbName = "defero.cloudant.com/db"; var dbString = 'https://' + username + ":" + password + "@" + dbName; return nano(dbString); }
return Promise.try(() => { if (!process.env.DB) { throw new Error("DB envvar is undefinied"); } n = nano(process.env.DB); return Promise.promisify(n.db.destroy)("test"); })
module.exports = function (job) { var mount = util.resolvePath(job.local); var remote = job.remote; var db = nano(remote), filepath = util.filepath(mount); function update (task, callback) { log.info(task.id, 'checking local update'); function _create () { log.info(task.id, '> locally updating'); util.mkdirParent(path.dirname(fp), undefined, function (err) { if (err) throw err; db.attachment.get(task.id, 'file') .on('error', function (err) { throw err; }) .on('end', callback) .pipe(fs.createWriteStream(fp)); }); } var fp = filepath(task.id); fs.stat(fp, function (err, stat) { if (err) { if (err.code === 'ENOENT') { _create(); } else { throw err; } } else { var file_timestamp = stat ? new Date(stat.mtime).getTime() : 0; var hash = util.getMd5Hash(fp); if (task.hash === hash) { log.info(task.id, '> rejected local: identical hash'); callback(); } else if (task.timestamp > file_timestamp) { _create(); } else { log.info(task.id, '> rejected local: smaller timestamp'); callback(); } } }); } function destroy (task, callback) { var fp = filepath(task.id); if (fp[fp.length-1] === path.sep) { fs.rmdir(fp, callback); } else { fs.unlink(fp, callback); } } return { update: async.queue(update), destroy: async.queue(destroy) }; };
function gotDatabase(err) { if (err && err.status_code == 404 && err.reason == 'no_db_file') { db.db.create(collectionName, createdDB); } else { registry.collection(collectionName, collection); registry.db(collectionName, nano(url + collectionName)); cb(); } }
function getCouchDb(couchdbAddr, options) { const couchdb = typeof couchdbAddr === 'string' ? nano(couchdbAddr, options.nano) : couchdbAddr; if (!couchdb.config.db) { throw new Error('No database is selected, did you pass a database in the couchdb address?'); } return couchdb; }
function wrap(options) { if (typeof options != 'object') { options = { url: options }; } return nano(options); }
return new Promise(function(resolve, reject) { var dbClient = nano(self._url); dbClient.db.destroy(self._name, function(err, body) { if (err) { resolve(false); } else { resolve(true); } }); });
, 'that accepts a nano db': function(t) { var Entity = odm.deliver('entity') , dburl = 'http://localhost:5984/stork_test' , _ = null , db = nano(dburl) ; Entity.from.bind(_, db).should.not.throw(); t.done(); }
priv.db = function db() { log.trace("priv.db: Connecting to data base, host - '%s' - port '%s' - db '%s'", this.host, this.port, this.database); dbServer = dbServer || nano( { url: 'http://' + this.host + ":" + this.port, log: nanoLogFunc } ); return dbServer.use(this.database); };
adapter.session = function session(connection, collectionName, sid, cb) { var url = urlForConfig(registry.connection(connection)); var sessionDb = nano({ url: url, cookie: 'AuthSession=' + encodeURIComponent(sid) }); sessionDb.session(cb); };
onTestComplete: function(status, page, config, browser) { var done = this.async(); var browserDB = nano('http://127.0.0.1:5984').use('test_results'); var retries = 0; (function getResults() { browser.eval("window.testReport", function(err, val) { testResults[config.name] = err ? "No results" : val; done(true); }); }()); }
module.exports = CouchDb = function(options) { options = options || {}; this.database = options.database || 'cqrs'; this.host = options.host || 'localhost'; this.port = options.port || 5984; this._db = nano('http://' + this.host + ':' + this.port + '/' + this.database); }
function CouchStream(db, options) { if (!(this instanceof CouchStream)) { return new CouchStream(db, options); } if (!options) options = {}; options.objectMode = true; this.couch = nano(options.url || 'http://localhost:5984'); this.db = this.couch.use(db); Writable.call(this, options); }
function _makeDeleteHandler(config, dash) { // get the couch url var couchurl = config.couchurl, db; if (config.admin) { couchurl = config.admin.couchurl || couchurl; } // initialise the mesh db connection debug('initialized delete handler, pointing to: ' + couchurl + '/' + config.meshdb); db = nano(couchurl).use(config.meshdb); function deleteAppFiles(appid, callback) { var appPath = path.resolve(dash.serverPath, 'lib/apps/' + appid); debug('checking for application files in: ' + appPath); path.exists(appPath, function(exists) { if (! exists) { callback(); } else { debug('deleting application files in path: ' + appPath); exec('rm -r ' + appPath, callback); } }); } // deleteAppFiles return function(req, res, next) { var appid = req.param('id'); debug('received delete request for app: ' + appid); deleteAppFiles(appid, function() { // TODO: delete dashboard plugins db.get('app::' + appid, function(err, doc) { if (! err) { debug('doc exists, rev id = ', doc._rev); db.destroy('app::' + appid, doc._rev, function(err, doc) { debug('delete response: ', err, doc); res.redirect('/apps/list'); }); } else { res.redirect('/apps/list'); } }); }); }; } // _makeDeleteHandler
this.initForTest = () => { if (process.env.host_db_test == 'localhost') { console.log("BD en local"); // bd de test en local (CouchDb) var db = nano(this.BD_LOCAL_HOST); this.clientDB = prom(db).db.use(process.env.cloudant_database_test); } else if (process.env.host_db_test == 'cloudant_test') { //credenciales para cloudant; bd de test var me = process.env.cloudant_username || "nodejs", password = process.env.cloudant_password, databaseName = process.env.cloudant_database_test; var cloudant = Cloudant({ account: me, password: password }); this.clientDB = prom(db).db.use(databaseName); } };
function Couch(cfg) { var couch = nano({ 'url' : cfg.url, 'parseUrl' : false }); this.db = couch.db.use(cfg.db); this.feed = this.db.follow({ since : 'now', include_docs : true, filter : 'project/by_name', query_params : {name : cfg.filter} }); }
function backup(options, done) { options = _.defaults(options || {}, defaults); debug('backing up databases', options); var connection = nano(options.credentials); var pack = tar.pack(); getDbs(options, connection, function (err, dbs) { if (err) { return pack.emit('error', err); } async.forEach(dbs, function (dbname, next) { var db = connection.use(dbname); var params = {include_docs: true}; // eslint-disable-line camelcase db.list(params, function (err, body) { if (err) { return next(err); } // todo: fetch the attachments and include them if (body.rows.some(function (row) { return row.doc._attachments; // eslint-disable-line no-underscore-dangle })) { console.error('WARNING: couchdb-backup-restore does not currently support attachments. At least one document in %s has attachments that will not be included in the backup.', dbname); //eslint-disable-line no-console } body.dbname = dbname; var filename = dbname.replace(/[^a-z0-9-_]+/ig, '_') + '.json'; pack.entry({name: filename}, JSON.stringify(body)); next(); }); }, function (err) { if (err) { return pack.emit('error', err); } pack.finalize(); }); }); var gzipStream = zlib.createGzip(); pack.pipe(gzipStream); if (done) { pack.on('error', done); gzipStream.on('error', done); gzipStream.on('end', done); } return gzipStream; }