Skip to content

Commit 67d5b22

Browse files
committed
Automatically inserts Turbo Stream responses.
This makes it easier for users so they don't have to insert the Turbo Stream HTML into the body.
1 parent 529f25a commit 67d5b22

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ async myMethod () {
3535
}
3636
```
3737

38+
#### Turbo Streams
39+
40+
Request.js can automatically process Turbo Streams responses for you. Ensure that your web app sets the `window.Turbo` global variable:
41+
42+
```javascript
43+
import { Turbo } from "@hotwired/turbo-rails"
44+
window.Turbo = Turbo
45+
```
46+
3847
# License
3948

4049
Rails Request.JS is released under the [MIT License](LICENSE).

src/request.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export class Request {
1313
if (response.unauthenticated && response.authenticationURL) {
1414
return Promise.reject(window.location.href = response.authenticationURL)
1515
} else {
16+
if (response.ok && response.isTurboStream) { response.renderTurboStream() }
1617
return response
1718
}
1819
}

src/response.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,20 @@ export class Response {
4747
get text () {
4848
return this.response.text()
4949
}
50+
51+
get isTurboStream () {
52+
return this.contentType.match(/^text\/vnd\.turbo-stream\.html/)
53+
}
54+
55+
async renderTurboStream () {
56+
if (this.isTurboStream) {
57+
if (window.Turbo) {
58+
Turbo.renderStreamMessage(await this.text)
59+
} else {
60+
console.warn('You must set `window.Turbo = Turbo` to automatically process Turbo Stream events with request.js')
61+
}
62+
} else {
63+
return Promise.reject(new Error(`Expected a Turbo Stream response but got "${this.contentType}" instead`))
64+
}
65+
}
5066
}

0 commit comments

Comments
 (0)