Cache implementation for CouchDB

@extends Cache

@param {object} [options] Options
@param {string} [options.url] CouchDB base URL (or use protocol + host + port)
@param {string} [options.protocol=http] CouchDB protocol (http|https)
@param {string} [options.host=http://localhost] CouchDB host
@param {string} [options.port=5984] CouchDB port
@param {string} [options.db=openamagent] CouchDB database name
@param {object} [options.auth] CouchDB auth credentials
@param {string} [options.auth.username] CouchDB user name
@param {string} [options.auth.password] CouchDB password
@param {number} [options.expireAfterSeconds=60] Expiration time in seconds

@example
var couchDBCache = new CouchDBCache({
host: 'db.example.com',
port: 5984,
auth: {
username: 'admin',
password: 'secret123'
},
expireAfterSeconds: 600
});

@constructor
function CouchDBCache(options) {
    var self = this;
    options = options || {};

    this.expireAfterSeconds = options.expireAfterSeconds || 60;

    this.connection = Promise.resolve()
        .then(function () {
            return options.auth ? this.auth(options.auth.username, options.auth.password) : null;
        })
        .then(function (cookie) {
            return nano({
                url: options.url || (options.protocol + '://' + options.host + ':' + options.port),
                cookie: cookie
            });
        });

    // create database if it doesn't exist
    this.db = this.connection.then(function (connection) {
        var dbName = options.db || 'openamagent';
        return Promise.promisify(connection.db.create.bind(connection.db))(dbName)
            .catch(function () {
                // ignore
            })
            .then(function () {
                return connection.use(dbName);
            });
    });
}