Skip to content

Use window.Turbo.fetch if available for turbo-stream requests #74

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

Merged
merged 2 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
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
Loading