Skip to content

Commit 421fdc5

Browse files
authored
Merge pull request #74 from brendon/X-Turbo-Request-Id-Support
Use window.Turbo.fetch if available for turbo-stream requests
2 parents 11a0cd9 + f22d6e9 commit 421fdc5

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

__tests__/fetch_request.js

+31
Original file line numberDiff line numberDiff line change
@@ -281,3 +281,34 @@ describe('query params are parsed', () => {
281281
expect(emptyQueryRequest.url).toBe("localhost/test")
282282
})
283283
})
284+
285+
286+
describe('turbostream', () => {
287+
test('turbo fetch is called for turbo-stream responseKind', async() => {
288+
const mockResponse = new Response("success!", { status: 200 })
289+
290+
window.fetch = jest.fn().mockResolvedValue(mockResponse)
291+
window.Turbo = { fetch: jest.fn().mockResolvedValue(mockResponse) }
292+
293+
const testRequest = new FetchRequest("get", "localhost", { responseKind: 'turbo-stream' })
294+
const testResponse = await testRequest.perform()
295+
296+
expect(window.Turbo.fetch).toHaveBeenCalledTimes(1)
297+
expect(window.fetch).toHaveBeenCalledTimes(0)
298+
expect(testResponse).toStrictEqual(new FetchResponse(mockResponse))
299+
})
300+
301+
test('turbo fetch is called for other responseKind', async() => {
302+
const mockResponse = new Response("success!", { status: 200 })
303+
304+
window.fetch = jest.fn().mockResolvedValue(mockResponse)
305+
window.Turbo = { fetch: jest.fn().mockResolvedValue(mockResponse) }
306+
307+
const testRequest = new FetchRequest("get", "localhost")
308+
const testResponse = await testRequest.perform()
309+
310+
expect(window.Turbo.fetch).toHaveBeenCalledTimes(0)
311+
expect(window.fetch).toHaveBeenCalledTimes(1)
312+
expect(testResponse).toStrictEqual(new FetchResponse(mockResponse))
313+
})
314+
})

src/fetch_request.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ export class FetchRequest {
1919
console.error(error)
2020
}
2121

22-
const response = new FetchResponse(await window.fetch(this.url, this.fetchOptions))
22+
const fetch = (this.responseKind === 'turbo-stream' && window.Turbo)
23+
? window.Turbo.fetch
24+
: window.fetch
25+
26+
const response = new FetchResponse(await fetch(this.url, this.fetchOptions))
2327

2428
if (response.unauthenticated && response.authenticationURL) {
2529
return Promise.reject(window.location.href = response.authenticationURL)

0 commit comments

Comments
 (0)