Skip to content

Commit

Permalink
build: ensure to handle common statuses
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Jan 22, 2020
1 parent 9e3316c commit 519e025
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 8 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Given an URL, it will be resolved fastest as possible.

It will be performing different HTTP requests in parallel (GET, HEAD) and it will return the first response to respond.

Because of that, don't use this module for consume `body` because it not always be available.
Don't use this module for consuming `body` since it isn't always be available.

## Install

Expand Down
26 changes: 22 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,35 @@ const createRequest = method => async (url, opts) => {
redirectStatusCodes.push(res.statusCode)
})

const { value: response = {} } = await pReflect(
const { isFulfilled, value: response = {}, reason: error } = await pReflect(
pTimeout(req, opts.timeout || Infinity)
)

return { ...response, redirectUrls, redirectStatusCodes }
return {
isFulfilled,
value: { ...response, redirectUrls, redirectStatusCodes },
error
}
}

const fromHEAD = createRequest('head')
const fromGET = createRequest('get')

module.exports = (url, opts = {}) => {
module.exports = async (url, opts = {}) => {
const { href: encodedUrl } = new URL(url)
return pAny([fromHEAD(encodedUrl, opts), fromGET(encodedUrl, opts)])
const { isFulfilled, value, error } = await pAny([
fromHEAD(encodedUrl, opts),
fromGET(encodedUrl, opts)
])

return isFulfilled
? value
: {
redirectStatusCodes: [],
redirectUrls: [],
statusCode: error.statusCode,
headers: error.headers,
statusMessage: error.statusMessage,
url: error.url
}
}
20 changes: 17 additions & 3 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,23 @@ test('keep original query search', async t => {
t.is(200, res.statusCode)
})

test('hanlde unresolved requests', async t => {
test('hanlde 404 urls', async t => {
const url = 'https://demo-1yr5bmtqy.now.sh/'
const res = await reachableUrl(url, { timeout: 500 })
t.is(res.url, undefined)
t.is(res.statusCode, undefined)
t.is(res.url, 'https://demo-1yr5bmtqy.now.sh/')
t.is(res.statusCode, 404)
})

test('hanlde 201 urls', async t => {
const url = 'https://httpbin.org/status/201'
const res = await reachableUrl(url)
t.is(res.url, 'https://httpbin.org/status/201')
t.is(res.statusCode, 201)
})

test('hanlde 500 urls', async t => {
const url = 'https://httpbin.org/status/500'
const res = await reachableUrl(url)
t.is(res.url, 'https://httpbin.org/status/500')
t.is(res.statusCode, 500)
})

0 comments on commit 519e025

Please sign in to comment.