createdb.js 592 Bytes
const su = require('superagent')

const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
}

const dbhost = process.env.COUCHDB_URL

const createDB = (dbname) =>
  su.put(`${dbhost}/${dbname}`)
    .set(headers)
    .then((result) => result.body)

module.exports = (dbname) =>
  su.head(`${dbhost}/${dbname}`)
    .then(
      (result) => result.status === 200,
      (error) => {
        if (error.status === 404) return false
        throw error
      }
    )
    .then((exists) => {
      if(exists) return { ok: true }
      return createDB(dbname)
    })