Skip to content

Automatically inserts Turbo Stream responses #6

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 1 commit into from
Jun 4, 2021
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
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ async myMethod () {
}
```

#### Turbo Streams

Request.JS will automatically process Turbo Stream responses. Ensure that your Javascript sets the `window.Turbo` global variable:

```javascript
import { Turbo } from "@hotwired/turbo-rails"
window.Turbo = Turbo
```

# License

Rails Request.JS is released under the [MIT License](LICENSE).
Expand Down
1 change: 1 addition & 0 deletions src/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export class Request {
if (response.unauthenticated && response.authenticationURL) {
return Promise.reject(window.location.href = response.authenticationURL)
} else {
if (response.ok && response.isTurboStream) { response.renderTurboStream() }
return response
}
}
Expand Down
16 changes: 16 additions & 0 deletions src/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,20 @@ export class Response {
get text () {
return this.response.text()
}

get isTurboStream () {
return this.contentType.match(/^text\/vnd\.turbo-stream\.html/)
}

async renderTurboStream () {
if (this.isTurboStream) {
if (window.Turbo) {
Turbo.renderStreamMessage(await this.text)
} else {
console.warn('You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js')
}
} else {
return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`))
}
}
}