Skip to content

Commit

Permalink
Merge f628c14 into 6d41472
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Mar 24, 2022
2 parents 6d41472 + f628c14 commit c495d1e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 12 deletions.
16 changes: 4 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ const mergeResponse = (responseOrigin = {}, responseDestination = {}) => ({
...responseDestination
})

const createFetcher = method => async (url, opts = {}) => {
const reachableUrl = async (url, opts = {}) => {
const req = got(url, {
retry: 0,
...opts,
retry: 0,
decompress: false,
responseType: 'buffer',
method
responseType: 'buffer'
})

const redirectStatusCodes = []
Expand Down Expand Up @@ -48,15 +47,8 @@ const createFetcher = method => async (url, opts = {}) => {
}
}

const createRequest = fetch => (url, opts) => fetch(url, opts)

const fromGET = createRequest(createFetcher('get'))

const isReachable = ({ statusCode }) => statusCode >= 200 && statusCode < 400

module.exports = async (url, opts = {}) => {
const { href: encodedUrl } = new URL(url)
return fromGET(encodedUrl, opts)
}
module.exports = async (url, opts) => reachableUrl(new URL(url).href, opts)

module.exports.isReachable = isReachable
33 changes: 33 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const { URL } = require('url')
const test = require('ava')
const got = require('got')

const reachableUrl = require('..')

Expand All @@ -17,6 +18,38 @@ test('resolve GET request', async t => {
t.true(isReachable(res))
})

test('allow to cache', async t => {
const url = 'https://microlink.io/favicon.ico'
const cache = new Map()

await got.head(url, { throwHttpErrors: false })
await got(url, { throwHttpErrors: false })

t.is(cache.size, 0)

const responseOne = await reachableUrl(url, { cache })

t.is(responseOne.isFromCache, false)
t.is(cache.size, 1)

const responseTwo = await reachableUrl(url, { cache })

t.is(responseTwo.isFromCache, true)
t.is(cache.size, 1)
})

test('resolve as fast a HEAD', async t => {
const url = 'https://microlink.io/favicon.ico'

const headResponse = await got.head(url, { throwHttpErrors: false })
const headTime = headResponse.timings.phases.total

const getResponse = await reachableUrl(url)
const getTime = getResponse.timings.phases.total

t.true(getTime <= headTime * 2)
})

test('resolve prerender GET request', async t => {
const url = 'https://www.instagram.com/teslamotors'
const res = await reachableUrl(url)
Expand Down

0 comments on commit c495d1e

Please sign in to comment.