Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
silesky committed Jul 12, 2023
1 parent d3d694f commit 9c43c89
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
7 changes: 7 additions & 0 deletions packages/node/src/__tests__/typedef-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ export default {
new Analytics({ writeKey: 'foo', httpClient: globalThis.fetch })
},

'HTTPFetchFn options should be the expected type': () => {
type BadFetch = (url: string, requestInit: { _bad_object?: string }) => any

// @ts-expect-error
new Analytics({ writeKey: 'foo', httpClient: {} as BadFetch })
},

'httpClient setting should be compatible with axios': () => {
new (class implements HTTPClient {
async makeRequest(options: HTTPClientRequest) {
Expand Down
4 changes: 3 additions & 1 deletion packages/node/src/lib/__tests__/abort.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { abortSignalAfterTimeout } from '../abort'
import nock from 'nock'
import { fetch } from '../fetch'
import { sleep } from '@segment/analytics-core'
import { fetch as _fetch } from '../fetch'

const fetch = _fetch as typeof globalThis.fetch

describe(abortSignalAfterTimeout, () => {
const HOST = 'https://foo.com'
Expand Down
19 changes: 14 additions & 5 deletions packages/node/src/lib/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ export interface HTTPFetchFn {
* @link https://developer.mozilla.org/en-US/docs/Web/API/Request
*/
export interface HTTPFetchRequest {
headers?: Record<string, string>
body?: string
method?: HTTPClientRequest['method']
signal?: any // AbortSignal type does not play nicely with node-fetch
headers: Record<string, string>
body: string
method: HTTPClientRequest['method']
signal: any // AbortSignal type does not play nicely with node-fetch
}

/**
Expand Down Expand Up @@ -73,7 +73,16 @@ export interface HTTPClient {
export class FetchHTTPClient implements HTTPClient {
private _fetch: HTTPFetchFn
constructor(fetchFn?: HTTPFetchFn) {
this._fetch = fetchFn ?? defaultFetch
const _fetch = fetchFn ?? defaultFetch
this._fetch = (url: string, requestInit: HTTPFetchRequest) => {
if (typeof url !== 'string') {
throw new Error('URL must be a string. Received: ' + url)
}
if (!requestInit.body || typeof requestInit.body !== 'string') {
throw new Error('Body must be a string. Received: ' + requestInit.body)
}
return _fetch(url, requestInit)
}
}
async makeRequest(options: HTTPClientRequest): Promise<HTTPResponse> {
const [signal, timeoutId] = abortSignalAfterTimeout(
Expand Down

0 comments on commit 9c43c89

Please sign in to comment.