Skip to content

Commit

Permalink
Merge pull request #74 from brendon/X-Turbo-Request-Id-Support
Browse files Browse the repository at this point in the history
Use window.Turbo.fetch if available for turbo-stream requests
  • Loading branch information
marcelolx authored Aug 30, 2024
2 parents 11a0cd9 + f22d6e9 commit 421fdc5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
31 changes: 31 additions & 0 deletions __tests__/fetch_request.js
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,34 @@ describe('query params are parsed', () => {
expect(emptyQueryRequest.url).toBe("localhost/test")
})
})


describe('turbostream', () => {
test('turbo fetch is called for turbo-stream responseKind', async() => {
const mockResponse = new Response("success!", { status: 200 })

window.fetch = jest.fn().mockResolvedValue(mockResponse)
window.Turbo = { fetch: jest.fn().mockResolvedValue(mockResponse) }

const testRequest = new FetchRequest("get", "localhost", { responseKind: 'turbo-stream' })
const testResponse = await testRequest.perform()

expect(window.Turbo.fetch).toHaveBeenCalledTimes(1)
expect(window.fetch).toHaveBeenCalledTimes(0)
expect(testResponse).toStrictEqual(new FetchResponse(mockResponse))
})

test('turbo fetch is called for other responseKind', async() => {
const mockResponse = new Response("success!", { status: 200 })

window.fetch = jest.fn().mockResolvedValue(mockResponse)
window.Turbo = { fetch: jest.fn().mockResolvedValue(mockResponse) }

const testRequest = new FetchRequest("get", "localhost")
const testResponse = await testRequest.perform()

expect(window.Turbo.fetch).toHaveBeenCalledTimes(0)
expect(window.fetch).toHaveBeenCalledTimes(1)
expect(testResponse).toStrictEqual(new FetchResponse(mockResponse))
})
})
6 changes: 5 additions & 1 deletion src/fetch_request.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ export class FetchRequest {
console.error(error)
}

const response = new FetchResponse(await window.fetch(this.url, this.fetchOptions))
const fetch = (this.responseKind === 'turbo-stream' && window.Turbo)
? window.Turbo.fetch
: window.fetch

const response = new FetchResponse(await fetch(this.url, this.fetchOptions))

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

0 comments on commit 421fdc5

Please sign in to comment.