Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to override fetch implementation #90

Merged
merged 2 commits into from
May 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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