Skip to content

Commit 171a137

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 171a137

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-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: 16 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

@@ -38,7 +41,7 @@ export class FetchRequest {
3841
return {
3942
method: this.method.toUpperCase(),
4043
headers: this.headers,
41-
body: this.body,
44+
body: this.formattedBody,
4245
signal: this.signal,
4346
credentials: 'same-origin',
4447
redirect: 'follow'
@@ -101,4 +104,15 @@ export class FetchRequest {
101104
get additionalHeaders () {
102105
return this.options.headers || {}
103106
}
107+
108+
get formattedBody () {
109+
const bodyIsAString = Object.prototype.toString.call(this.body) === '[object String]'
110+
const contentTypeIsJson = this.headers['Content-Type'] === 'application/json'
111+
112+
if (contentTypeIsJson && !bodyIsAString) {
113+
return JSON.stringify(this.body);
114+
}
115+
116+
return this.body;
117+
}
104118
}

0 commit comments

Comments
 (0)