       'X-Auth-Token': token
   request.get options, (error, response, body) ->
     if (error)
-      callback(error)
+      d.reject(error)
     else
       domain = _.find body.domains, (domain) ->
         recordName.indexOf(domain.name) != -1

        .pluck 'publicURL'
        .head()
        .value()
      callback null,
        expiry: body.access.token.expires,
        token: body.access.token.id,
        endpoint: designateEndpoint
  d.promise

designateRecords = (token, endpoint, recordName, callback) ->
  options =
    url: endpoint + '/domains'
    json: true

      request.get options, (error, response, body) ->
        records = body.records.filter (r) ->
          r.name == recordName
        d.resolve(records)
  d.promise

factory = () ->
  expiryBuffer = moment.duration('5', 'minutes')
  infoRef =
    info:
      expiry: '1970-01-01',
      token: null,
      designateUrl: null

  haveCurrentToken = () ->
    moment(infoRef.info.expiry).isAfter(moment().add(expiryBuffer))

  token = () ->
    if haveCurrentToken()
      Q(infoRef.info)
    else
      newTokenAndEndpoint().then (info) ->
        infoRef.info = info
        info

  (recordName) ->
    token().then (info) ->
      designateRecords(info.token, info.endpoint, recordName)

module.exports = factory()
