Last active
June 16, 2016 09:49
-
-
Save Dev-Dipesh/fdd30f0f36014c2a64ace0789fff2161 to your computer and use it in GitHub Desktop.
Create Couchbase Views on the fly. Automate the view creation process in Couchbase.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Create Couchbase Views on the fly | |
* v1.0.0 June 15, 2016 | |
* Dipesh Bhardwaj | |
* Code Style - ES6 Javascript | ES Lint | AirBnB Arrow Functions | |
* This script contains example for sample beer bucket, which comes | |
* pre-loaded with Couchbase. | |
* Create a `startupCheck.js` script in your application, if not already exist | |
* and call this script through it to create all your Couchbase views | |
* during app initialization. This script first checks if the views are already | |
* exist, if not then only it will create new views. Also it checks for those | |
* which are already created and simply leave them as is and create new views. | |
* | |
* Replace all static values with your configurations defined in config files. | |
*/ | |
/* eslint-disable no-console */ | |
// Load the Couchbase driver and connect to the cluster | |
import couchbase from 'couchbase'; | |
const cluster = new couchbase.Cluster('localhost:8091'); | |
// It is important to make this async call as otherwise you will try create the | |
// view before the connection to couchbase is established, resulting in a failure. | |
const bsBucket = cluster.openBucket('beer-sample', err => { | |
if (err) { | |
console.error('error:', err); | |
} else { | |
console.info('connected'); | |
} | |
}); | |
// If connected, then create the views | |
bsBucket.on('connect', err => { | |
if (err) { | |
console.error(`Failed to connect to cluster: ${err}`); | |
process.exit(1); | |
} else { | |
console.info('Couchbase Connected'); | |
const bManager = bsBucket.manager('Administrator', 'password'); | |
// Update the beer view, to index beers 'by_name'. | |
bManager.insertDesignDocument('beer', { | |
views: { | |
beer_by_name: { | |
map: (doc, meta) => { // eslint-disable-line no-unused-vars | |
if (doc.type && doc.type === 'beer') { | |
emit(doc.name, null); // eslint-disable-line no-undef | |
} | |
} | |
} | |
} | |
}, error => { | |
// Tell me the error and exit | |
if (error) { | |
console.error('ERROR', error); | |
process.exit(0); | |
} else { | |
// All good, exit | |
console.info('Done!'); | |
process.exit(0); | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment