From 07acf3083ffe0090b514221c5728ffc91c977444 Mon Sep 17 00:00:00 2001 From: Marcelo Lauxen Date: Wed, 16 Jun 2021 07:47:45 -0300 Subject: [PATCH] Add support to stringify automatically the body of the request if the type of it isn't a string This allows us the make the request sending a javascript object and then RequestJS does the job of stringify the body --- README.md | 17 +++++++++++++++++ src/fetch_request.js | 18 ++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 121ed97..444744a 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,23 @@ async myMethod () { } ``` +#### Request body + +Instead of stringify the body of a request which the content type is `application/json`, you can just pass the javascript object as the body of the request and Request.JS will stringify it for you. + +```js +import { post } from '@rails/request.js' + +... + +async myMethod () { + const response = await post('localhost:3000/my_endpoint', { body: { name: 'Request.JS' } }) + if (response.ok) { + ... + } +} +``` + #### Turbo Streams diff --git a/src/fetch_request.js b/src/fetch_request.js index 3d0684c..08a0d80 100644 --- a/src/fetch_request.js +++ b/src/fetch_request.js @@ -24,7 +24,10 @@ export class FetchRequest { return Promise.reject(window.location.href = response.authenticationURL) } - if (response.ok && response.isTurboStream) { response.renderTurboStream() } + if (response.ok && response.isTurboStream) { + response.renderTurboStream() + } + return response } @@ -38,7 +41,7 @@ export class FetchRequest { return { method: this.method.toUpperCase(), headers: this.headers, - body: this.body, + body: this.formattedBody, signal: this.signal, credentials: 'same-origin', redirect: 'follow' @@ -101,4 +104,15 @@ export class FetchRequest { get additionalHeaders () { return this.options.headers || {} } + + get formattedBody () { + const bodyIsAString = Object.prototype.toString.call(this.body) === '[object String]' + const contentTypeIsJson = this.headers['Content-Type'] === 'application/json' + + if (contentTypeIsJson && !bodyIsAString) { + return JSON.stringify(this.body) + } + + return this.body + } }