From 9c4a903ca95b918f669689139b9687b023472dd8 Mon Sep 17 00:00:00 2001 From: Kiko Beats Date: Thu, 24 Mar 2022 12:59:15 +0100 Subject: [PATCH 1/2] refactor: remove unnecessary code --- index.js | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index ab4a60a..9dc03a5 100644 --- a/index.js +++ b/index.js @@ -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 = [] @@ -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 From f628c14ff82223c05706c9c018f6c9a483233a97 Mon Sep 17 00:00:00 2001 From: Kiko Beats Date: Thu, 24 Mar 2022 13:05:12 +0100 Subject: [PATCH 2/2] test: add additional cases --- test/index.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/test/index.js b/test/index.js index 7265824..ad8c7a8 100644 --- a/test/index.js +++ b/test/index.js @@ -2,6 +2,7 @@ const { URL } = require('url') const test = require('ava') +const got = require('got') const reachableUrl = require('..') @@ -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)