Skip to content

Commit

Permalink
feat(http): support http/after-fetch event
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Aug 20, 2024
1 parent b2da31b commit 7620202
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@cordisjs/plugin-http",
"description": "Fetch-based axios-style HTTP client",
"version": "0.6.0",
"version": "0.6.2",
"type": "module",
"main": "lib/index.js",
"types": "lib/index.d.ts",
Expand Down
11 changes: 11 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ declare module 'cordis' {
'http/file'(this: HTTP, url: string, options: FileOptions): Awaitable<FileResponse | undefined>
'http/config'(this: HTTP, config: HTTP.Config): void
'http/fetch-init'(this: HTTP, url: URL, init: RequestInit, config: HTTP.Config): void
'http/after-fetch'(this: HTTP, data: HTTP.AfterFetch): void
'http/websocket-init'(this: HTTP, url: URL, init: ClientOptions, config: HTTP.Config): void
}
}
Expand Down Expand Up @@ -115,6 +116,14 @@ export namespace HTTP {
headers: Headers
}

export interface AfterFetch {
url: URL
init: RequestInit
config: RequestConfig
result?: globalThis.Response
error?: any
}

export type Decoder<T = any> = (raw: globalThis.Response) => Awaitable<T>

export type Error = HTTPError
Expand Down Expand Up @@ -319,11 +328,13 @@ export class HTTP extends Service<HTTP.Config> {
}
this.ctx.emit(this, 'http/fetch-init', url, init, config)
const raw = await fetch(url, init).catch((cause) => {
this.ctx.emit(this, 'http/after-fetch', { url, init, config, error: cause })
if (HTTP.Error.is(cause)) throw cause
const error = new HTTP.Error(`fetch ${url} failed`)
error.cause = cause
throw error
})
this.ctx.emit(this, 'http/after-fetch', { url, init, config, result: raw })

const response: HTTP.Response = {
data: null,
Expand Down
2 changes: 1 addition & 1 deletion packages/proxy-agent/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"cordis": "^3.17.4"
},
"peerDependencies": {
"@cordisjs/plugin-http": "^0.6.0",
"@cordisjs/plugin-http": "^0.6.2",
"cordis": "^3.17.4"
},
"dependencies": {
Expand Down

0 comments on commit 7620202

Please sign in to comment.