public
Last active

Test-drive a self-contained node module (viewUtils.js here), and then use it as a CouchDB CommonJS module. Sample schema installation and update scripts included.

  • Download Gist
couchModuleText.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
(function (undefined) {
"use strict";
 
var _ = require("underscore");
 
module.exports = function (nodeModule, dependencyNameToPathMap) {
return _.map(dependencyNameToPathMap, function (path, name) {
return ["var ", name, " = require(\"", path, "\");"].join("");
}).concat(
_.isFunction(nodeModule) ?
["module.exports = ", nodeModule.toString(), ";"].join("") :
 
_.map(nodeModule, function (method, methodName) {
return ["exports.", methodName, " = ", method.toString(), ";"].join("");
})
).join("\n");
};
}());
couchSchemaExample.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
(function (undefined) {
"use strict";
var couchModuleText = require("./couchModuleText"),
viewUtils = require("./viewUtils"),
viewMapWhatever = function (doc) {
emit(
require("views/lib/utils").bar(doc._id),
doc
);
};
module.exports = {
views: {
lib: { utils: couchModuleText(viewUtils) },
whatever: { map: viewMapWhatever }
}
};
}());
installSchema.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
(function (undefined) {
"use strict";
 
var cradle = require("cradle"),
async = require("async"),
mainSchema = require("./couchSchemaExample"),
db = new (cradle.Connection)().database("awesome");
 
async.waterfall([
function (callback) {
db.exists(callback);
},
 
function (exists, callback) {
if (exists) {
callback({error: "DB already exists. Won't touch."});
}
else {
callback(undefined);
}
},
 
function (callback) {
db.create(callback);
},
 
function (creationResult, callback) {
db.save("_design/main", mainSchema, callback);
}
], function (err, res) {
console.info(err || res);
});
}());
updateSchema.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
(function (undefined) {
"use strict";
 
var cradle = require("cradle"),
db = new (cradle.Connection)().database("awesome"),
async = require("async"),
mainSchema = require("./couchSchemaExample"),
 
updateDesignDoc = function (id, newDocVersion, callback) {
async.waterfall([
function (callback) {
db.get(id, callback);
},
 
function (designDoc, callback) {
db.save(id, designDoc._rev, newDocVersion, callback);
}
], callback);
};
updateDesignDoc("_design/main", mainSchema, function (err, res) {
console.info(err || res);
});
}());
viewUtils.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11
(function (undefined) {
"use strict";
 
exports.foo = function (x) {
return exports.bar(x);
};
 
exports.bar = function (x) {
return "Bar for " + x;
};
}());

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.