From f28a6d593a5522ddd11247a69907b4a4f0a298b2 Mon Sep 17 00:00:00 2001 From: Chris Oliver Date: Thu, 3 Jun 2021 12:53:58 -0500 Subject: [PATCH] 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. --- README.md | 9 +++++++++ src/request.js | 1 + src/response.js | 16 ++++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/README.md b/README.md index f8db46b..a3e9827 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/src/request.js b/src/request.js index d671f88..7c68692 100644 --- a/src/request.js +++ b/src/request.js @@ -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 } } diff --git a/src/response.js b/src/response.js index 93dec8e..47280c8 100644 --- a/src/response.js +++ b/src/response.js @@ -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`)) + } + } }