saveToken.js 791 Bytes
const { path, pathOr, head } = require('ramda')
const su = require('superagent')
const uuid = require('uuid/v1')
const dbhost = process.env.COUCHDB_URL
const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
}


module.exports = (({ accessToken }) => {
  su.get(`${dbhost}/${process.env.DB_TOKENS}/_all_docs`)
  .set(headers)
  .then(path(['body', 'rows']))
  .then(head)
  .then((token)  => {
    if(token && token.id) {
      const { id, value: { rev } } = token
      return su.put(`${dbhost}/tokens/${id}`)
      .set(headers)
      .send(JSON.stringify({ _id: id, _rev: rev, accessToken }))
      .then(x => x.body)
    }
    return su.post(`${dbhost}/tokens/`)
    .set(headers)
    .send(JSON.stringify({ accessToken }))
    .then(x => x.body)
  })
})