diff --git a/README.md b/README.md index 610ebdd..280220a 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/src/index.js b/src/index.js index 31ba037..a99069e 100644 --- a/src/index.js +++ b/src/index.js @@ -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 } diff --git a/src/verbs.js b/src/verbs.js new file mode 100644 index 0000000..1985f47 --- /dev/null +++ b/src/verbs.js @@ -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 }