Skip to content

Commit

Permalink
fix: ensure optimized URL is reachabel
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Jul 16, 2021
1 parent fc8cce5 commit 0db0b1a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
14 changes: 10 additions & 4 deletions src/avatar-url.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ const urlRegex = require('url-regex')
const pReflect = require('p-reflect')
const pAny = require('p-any')

const { gotOpts } = require('./got')

const { isReachable } = reachableUrl

const { AVATAR_SIZE, AVATAR_TIMEOUT } = require('./constant')
const { providers, providersBy } = require('./providers')

const proxyImageUrl = (url, query) =>
`https://images.weserv.nl/?${new URLSearchParams({
const optimizeUrl = async (url, query) => {
const proxyUrl = `https://images.weserv.nl/?${new URLSearchParams({
url,
l: 9,
af: '',
Expand All @@ -30,6 +32,10 @@ const proxyImageUrl = (url, query) =>
...omit(query, ['json', 'fallback'])
}).toString()}`

const { statusCode, url: resourceUrl } = await reachableUrl(proxyUrl, gotOpts)
return isReachable({ statusCode }) ? resourceUrl : url
}

const getDefaultFallbackUrl = memoizeOne(
({ protocol, host }) => `${protocol}://${host}/fallback.png`
)
Expand All @@ -52,7 +58,7 @@ const is = input => {
const getAvatarUrl = async (fn, input) => {
const avatarUrl = await fn(input)
if (!isAbsoluteUrl(avatarUrl)) throw new Error('Avatar URL is not valid.')
const { statusCode, url } = await reachableUrl(avatarUrl)
const { statusCode, url } = await reachableUrl(avatarUrl, gotOpts)
if (!isReachable({ statusCode })) throw new Error('Avatar URL is not reachable.')
return url
}
Expand All @@ -78,7 +84,7 @@ module.exports = (fn = getFirstReachableAvatarUrl) => async (req, res) => {
if (isRejected) debug(beautyError(reason))

return {
url: proxyImageUrl(url, query),
url: await optimizeUrl(url, query),
isJSON: !isNil(get(req, 'query.json')),
isError: isNil(url)
}
Expand Down
5 changes: 3 additions & 2 deletions src/got.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ const got = require('got')
const dnsCache = new CacheableLookup()
dnsCache.servers = ['1.1.1.1', '1.0.0.1']

const defaultOpts = {
const gotOpts = {
dnsCache,
https: { rejectUnauthorized: false },
retry: 0
}

module.exports = got.extend(defaultOpts)
module.exports = got.extend(gotOpts)
module.exports.gotOpts = gotOpts

1 comment on commit 0db0b1a

@vercel
Copy link

@vercel vercel bot commented on 0db0b1a Jul 16, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.