Skip to content

Commit 6d3d574

Browse files
committed
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
1 parent 6b0be45 commit 6d3d574

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,23 @@ async myMethod () {
5454
}
5555
```
5656

57+
#### Request body
58+
59+
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.
60+
61+
```js
62+
import { post } from '@rails/request.js'
63+
64+
...
65+
66+
async myMethod () {
67+
const response = await post('localhost:3000/my_endpoint', { body: { name: 'Request.JS' } })
68+
if (response.ok) {
69+
...
70+
}
71+
}
72+
```
73+
5774

5875
#### Turbo Streams
5976

src/fetch_request.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ export class FetchRequest {
2424
return Promise.reject(window.location.href = response.authenticationURL)
2525
}
2626

27-
if (response.ok && response.isTurboStream) { response.renderTurboStream() }
27+
if (response.ok && response.isTurboStream) {
28+
response.renderTurboStream()
29+
}
30+
2831
return response
2932
}
3033

@@ -35,14 +38,18 @@ export class FetchRequest {
3538
}
3639

3740
get fetchOptions () {
38-
return {
41+
const requestOptions = {
3942
method: this.method.toUpperCase(),
4043
headers: this.headers,
4144
body: this.body,
4245
signal: this.signal,
4346
credentials: 'same-origin',
4447
redirect: 'follow'
4548
}
49+
50+
this._stringifyBody(requestOptions)
51+
52+
return requestOptions
4653
}
4754

4855
get headers () {
@@ -101,4 +108,13 @@ export class FetchRequest {
101108
get additionalHeaders () {
102109
return this.options.headers || {}
103110
}
111+
112+
_stringifyBody (requestOptions) {
113+
const bodyIsAString = Object.prototype.toString.call(requestOptions.body) === '[object String]'
114+
const contentTypeIsJson = requestOptions.headers['Content-Type'] === 'application/json'
115+
116+
if (contentTypeIsJson && !bodyIsAString) {
117+
requestOptions.body = JSON.stringify(requestOptions.body)
118+
}
119+
}
104120
}

0 commit comments

Comments
 (0)