Skip to content

Commit

Permalink
Include data on error response as well
Browse files Browse the repository at this point in the history
  • Loading branch information
kjellmorten committed Jan 1, 2019
1 parent cfd6a14 commit 653f72f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/adapter/send.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ test('should use POST when request data is set', async (t) => {
data: 'key=value'
}
const expectedHeaders = {
'Content-Type': 'application/x-www-form-urlencoded'
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}

const ret = await send(got)(request)
Expand Down
11 changes: 6 additions & 5 deletions src/adapter/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@ import { GotFn } from 'got'
import { Request, RequestData, Response } from '.'

export interface HttpError extends Error {
statusCode: number
statusCode: number,
response: { body?: string }
}

const createError = ({ statusCode }: HttpError, uri: string) => {
const createError = ({ statusCode, message }: HttpError, uri: string) => {
switch (statusCode) {
case 404: return { status: 'notfound', error: `Could not find the url ${uri}` }
case 401: return { status: 'noaccess', error: `Service requires authentication for ${uri}` }
}
return { status: 'error', error: `Server returned ${statusCode} for ${uri}` }
return { status: 'error', error: `Server returned ${statusCode} error for ${uri}. ${message}` }
}

const resolveMethod = (data?: RequestData) => (data) ? 'POST' : 'GET'
const generateHeaders = (method: string) => (method === 'POST')
? { 'Content-Type': 'application/x-www-form-urlencoded' }
? { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' }
: {}

const send = (got: GotFn) => async (request: Request): Promise<Response> => {
Expand All @@ -40,7 +41,7 @@ const send = (got: GotFn) => async (request: Request): Promise<Response> => {
data: response.body
}
} catch (error) {
return createError(error, uri)
return { ...createError(error, uri), data: error.response && error.response.body }
}
}

Expand Down
21 changes: 21 additions & 0 deletions src/tests/get.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,24 @@ test('should return notfound on 404', async (t) => {

t.is(ret.status, 'notfound')
})

test('should return body data on error', async (t) => {
nock('http://test.com')
.get('/error')
.reply(400, 'error=There+was+an+error')
const request = {
method: 'QUERY',
endpoint: {
uri: 'http://test.com/error'
}
}
const expectedData = {
error: 'There was an error'
}

const response = await adapter.send(request)
const ret = await adapter.normalize(response, request)

t.is(ret.status, 'error')
t.deepEqual(ret.data, expectedData)
})

0 comments on commit 653f72f

Please sign in to comment.