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 request timeout #1554

Merged
merged 5 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 50 additions & 8 deletions src/http-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,13 @@ class HttpRequests {
url: URL
requestConfig?: Config['requestConfig']
httpClient?: Required<Config>['httpClient']
timeout?: number
amit-ksh marked this conversation as resolved.
Show resolved Hide resolved

constructor(config: Config) {
this.headers = createHeaders(config)
this.requestConfig = config.requestConfig
this.httpClient = config.httpClient
this.timeout = config.timeout

try {
const host = constructHostURL(config.host)
Expand Down Expand Up @@ -140,14 +142,17 @@ class HttpRequests {
const headers = { ...this.headers, ...config.headers }

try {
const fetchFn = this.httpClient ? this.httpClient : fetch
const result = fetchFn(constructURL.toString(), {
...config,
...this.requestConfig,
method,
body,
headers,
})
const result = this.fetchWithTimeout(
constructURL.toString(),
{
...config,
...this.requestConfig,
method,
body,
headers,
},
this.timeout
)

// When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit
if (this.httpClient) {
Expand All @@ -166,6 +171,43 @@ class HttpRequests {
}
}

async fetchWithTimeout(
url: string,
options: RequestInit | undefined,
bidoubiwa marked this conversation as resolved.
Show resolved Hide resolved
timeout: HttpRequests['timeout']
): Promise<Response> {
return new Promise((resolve, reject) => {
const fetchFn = this.httpClient ? this.httpClient : fetch

const fetchPromise = fetchFn(url, options)

const promises: Array<Promise<any>> = [fetchPromise]

// TimeoutPromise will not run if undefined or zero
let timeoutId: ReturnType<typeof setTimeout>
if (timeout) {
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(() => {
reject(new Error('Error: Request Timed Out'))
}, timeout)
})

promises.push(timeoutPromise)
}

Promise.race(promises)
.then((response) => {
resolve(response)
})
.catch((error) => {
reject(error)
})
.finally(() => {
clearTimeout(timeoutId)
})
amit-ksh marked this conversation as resolved.
Show resolved Hide resolved
})
}

async get(
url: string,
params?: { [key: string]: any },
Expand Down
1 change: 1 addition & 0 deletions src/types/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export type Config = {
clientAgents?: string[]
requestConfig?: Partial<Omit<RequestInit, 'body' | 'method'>>
httpClient?: (input: string, init?: RequestInit) => Promise<any>
timeout?: number
}

///
Expand Down
15 changes: 15 additions & 0 deletions tests/search.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1059,6 +1059,21 @@ describe.each([
expect(error).toHaveProperty('message', 'The user aborted a request.')
})
})

test(`${permission} key: search should be aborted when reaching timeout`, async () => {
const key = await getKey(permission)
const client = new MeiliSearch({
...config,
apiKey: key,
timeout: 1,
})
try {
await client.health()
} catch (e: any) {
expect(e.message).toEqual('Error: Request Timed Out')
expect(e.name).toEqual('MeiliSearchCommunicationError')
}
})
})

describe.each([
Expand Down