Skip to content

Commit

Permalink
feat: add option to override fetch implementation (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
wereHamster committed May 20, 2022
1 parent 2223e35 commit 4386c5e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 12 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -111,6 +111,7 @@ type Metadata = {
}[]
description?: string
determiner?: string
site_name?: string
locale: string
locale_alt: string
videos: {
Expand Down
30 changes: 18 additions & 12 deletions src/index.ts
Expand Up @@ -30,7 +30,7 @@ function unfurl (url: string, opts?: Opts): Promise<Metadata> {
Number.isInteger(opts.size) || (opts.size = 0)

const ctx: {
url?: string;
url: string;
oembedUrl?: string;
} = {
url
Expand All @@ -42,17 +42,23 @@ function unfurl (url: string, opts?: Opts): Promise<Metadata> {
.then(parse(ctx))
}

async function getPage (url, opts: Opts) {
const res = await fetch(new URL(url), {
headers: {
Accept: 'text/html, application/xhtml+xml',
'User-Agent': opts.userAgent
},
// @ts-ignore
size: opts.size,
follow: opts.follow,
timeout: opts.timeout
})
async function getPage (url: string, opts: Opts) {
const res = await (() => {
if (opts.fetch) {
return opts.fetch(url)
} else {
return fetch(new URL(url), {
headers: {
Accept: 'text/html, application/xhtml+xml',
'User-Agent': opts.userAgent
},
// @ts-ignore
size: opts.size,
follow: opts.follow,
timeout: opts.timeout
})
}
})()

const buf = Buffer.from(await res.arrayBuffer())
const contentType = res.headers.get('Content-Type')
Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Expand Up @@ -11,6 +11,8 @@ export type Opts = {
size?: number
/** User-Agent string is often used for content negotiation */
userAgent?: string
/** Custom fetch implementation */
fetch?: (url: string) => Promise<any /* Response */>
}

export type Metadata = {
Expand Down Expand Up @@ -87,6 +89,7 @@ export type Metadata = {
}[]
description?: string
determiner?: string
site_name?: string
locale: string
locale_alt: string
videos: {
Expand Down

0 comments on commit 4386c5e

Please sign in to comment.