Skip to content

Instantly share code, notes, and snippets.

@PatrickHeneise
Last active March 2, 2016 15:23
Show Gist options
  • Save PatrickHeneise/e170cd7b48bad37bae58 to your computer and use it in GitHub Desktop.
Save PatrickHeneise/e170cd7b48bad37bae58 to your computer and use it in GitHub Desktop.
Bootstrap/reset your CouchDB views with pretty JavaScript

I use this to destroy and create a fresh database for testing. Importing the views this way I can use my favourite editor and have prettify/beautify/linting/hinting on my map-reduce view functions instead of using the Futon editor.

Put all your view functions into:

  • data/[designDoc]-[viewName].js (like zdata users-index.js)
  • data/index.js (like zdata index.js)

Use something like 0-setup.js to import the views into your CouchDB.

Have fun.

'use strict';
const fs = require('fs');
const path = require('path');
let contents = [];
fs.readdirSync(__dirname)
.forEach((fileName) => {
if (fileName !== 'index.js' && fileName.indexOf('.js') >= 0) {
let viewContent = require(path.join(__dirname, fileName));
let viewPath = fileName.split('.')[0].split('-');
let view = {
'_id': '_design/' + viewPath[0],
'language': 'javascript',
'views': {}
};
view.views[viewPath[1]] = viewContent;
contents.push(view);
}
});
module.exports = exports = contents;
module.exports = exports = {
map: function (doc) {
if (doc.type === 'user') {
emit(doc.name, {
firstName: doc.fistName,
lastName: doc.lastName
});
}
}
};
const config = require('../lib/config.js');
const nano = require('nano')(config.couchdb.host);
const data = require('../couchdb/data');
const db = nano.use('test');
const views = require('../couchdb/views/index.js');
let insertViews = () => {
let promises = [];
views.forEach(view => {
let promise = new Promise((resolve, reject) => {
db.insert(view, view.id, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
promises.push(promise);
});
return Promise.all(promises)
.then(() => db);
};
@PatrickHeneise
Copy link
Author

A more complete solution is couchdb-bootstrap

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment