Skip to content
This repository has been archived by the owner on Feb 27, 2022. It is now read-only.

Commit

Permalink
fix(api): throw hard rejection from api client
Browse files Browse the repository at this point in the history
api client resolves the promise when request returns error and gives a chance to assert errors, but
in case of hard rejections it will reject the promise
  • Loading branch information
thetutlage committed Jul 29, 2017
1 parent 2c1b68d commit e4940cd
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 8 deletions.
12 changes: 7 additions & 5 deletions src/ApiClient/Request.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,15 @@ class Request {

then (userResolve, userReject) {
if (!this._fullfilledPromise) {
this._fullfilledPromise = new Promise((resolve) => {
this._fullfilledPromise = new Promise((resolve, reject) => {
this.agent.end((error, response) => {
if (error) {
resolve(new Response(error, this._assert))
return
if (error && error.response) {
resolve(new Response(error.response, true, this._assert))
} else if (error) {
reject(error)
} else {
resolve(new Response(response, false, this._assert))
}
resolve(new Response(response, this._assert))
})
})
}
Expand Down
6 changes: 3 additions & 3 deletions src/ApiClient/Response.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
const urlModule = require('url')

class Response {
constructor (resOrError, assert) {
constructor (res, isError, assert) {
this._assert = assert
this._isError = resOrError.name === 'Error'
this._res = this._isError ? resOrError.response : resOrError
this._isError = isError
this._res = res
}

get status () {
Expand Down
16 changes: 16 additions & 0 deletions test/unit/api-client.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ test.group('Api Client', (group) => {
this.server.close()
})

test('throw error when unable to connect', async (assert) => {
assert.plan(1)
this.server.on('request', (req, res) => {
res.end('yayy')
})

const env = new Env({ TEST_SERVER_URL: 'null:null' })
const client = new ApiClient(env, assert)
try {
const response = await client.get('/')
console.log(response)
} catch ({ message }) {
assert.equal(message, 'getaddrinfo ENOTFOUND null null:80')
}
})

test('initiate client with new request', async (assert) => {
this.server.on('request', (req, res) => {
res.end('yayy')
Expand Down

0 comments on commit e4940cd

Please sign in to comment.