Skip to content

Commit c8d7881

Browse files
authored
Merge pull request #6 from excid3/handle-turbo-stream-on-success
Automatically inserts Turbo Stream responses
2 parents d073c85 + f28a6d5 commit c8d7881

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 will automatically process Turbo Stream responses. Ensure that your Javascript 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)