Skip to content

Commit

Permalink
adds 5 shorthand functions for request verbs get, post, put, patch, d…
Browse files Browse the repository at this point in the history
…estroy (#10)

close #9 

This PR adds shorthand functions to directly call one specific HTTP request verb.

5 new functions are available : get, post, put, patch, destroy

### Example 
```js
import {get, post, put, patch, destroy} from '@rails/request.js'

async myMethod () {
  const response = await post('localhost:3000/my_endpoint', { body: { name: 'Request.JS' }}))
  if (response.ok) {
    const body = await response.text
    ...
  }
}
```

### DELETE -> `destroy`

`delete` is a javascript reserved word so for this shorthand function I used `destroy`
  • Loading branch information
adrienpoly authored Jun 7, 2021
1 parent 72bb933 commit 0f0dbe4
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,26 @@ async myMethod () {
}
```

#### Shorthand methods

Alternatively, you can use a shorthand version for the main HTTP verbs, `get`, `post`, `put`, `patch` or `destroy`.

Example:

```js
import { get, post, put, patch, destroy } from '@rails/request.js'

...

async myMethod () {
const response = await post('localhost:3000/my_endpoint', { body: { name: 'Request.JS' }})
if (response.ok) {
...
}
}
```


#### Turbo Streams

Request.JS will automatically process Turbo Stream responses. Ensure that your Javascript sets the `window.Turbo` global variable:
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { FetchRequest } from './fetch_request'
import { FetchResponse } from './fetch_response'
import { RequestInterceptor } from './request_interceptor'
import { get, post, put, patch, destroy } from './verbs'

export { FetchRequest, FetchResponse, RequestInterceptor }
export { FetchRequest, FetchResponse, RequestInterceptor, get, post, put, patch, destroy }
28 changes: 28 additions & 0 deletions src/verbs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { FetchRequest } from './fetchRequest'

async function get (url, options) {
const response = new FetchRequest('get', url, options)
return response.perform()
}

async function post (url, options) {
const response = new FetchRequest('post', url, options)
return response.perform()
}

async function put (url, options) {
const response = new FetchRequest('put', url, options)
return response.perform()
}

async function patch (url, options) {
const response = new FetchRequest('patch', url, options)
return response.perform()
}

async function destroy (url, options) {
const response = new FetchRequest('delete', url, options)
return response.perform()
}

export { get, post, put, patch, destroy }

0 comments on commit 0f0dbe4

Please sign in to comment.