Client Libraries
Several JS packages are provided to handle URL interpolation and requests.
You can select which one to use by configuring client_library, which also enables you to target your own code instead.
@js-from-routes/client
The default client. Uses fetch
to avoid additional dependencies.
@js-from-routes/axios
Choose it if already using axios, or have a complex use case with extensive usage of interceptors.
@js-from-routes/inertia
Allows you to easily submit forms and make requests using your existing configuration in Inertia.js.
@js-from-routes/redaxios
Choose it if already using redaxios, for consistency within your codebase.
Usage ๐
The methods are fully typed, and documented using JSDoc.
Here a few examples when using @js-from-routes/client, more examples coming soon.
Importing helpers
If you use Vite Rails, aliases will allow you to import these files as:
import { videoClips } from '~/api'
// or
import VideoClipsApi from '~/api/VideoClipsApi'
When using webpack, it's highly recommended to add an alias to simplify imports.
Passing parameters
You can pass a plain object as parameters; properties will be interpolated on any matching placeholders (:id
) in the URL.
const video = { id: 5, title: 'New Wave' }
videoClips.download.path(video) == "/video_clips/5/download"
Missing parameters will throw an error providing the full context.
Submitting data
You can pass data
to specify the request body, just like in axios.
videoClips.update({ params: video, data: { title: 'New Waves' } })
By default, the CSRF token will be extracted using the same conventions in @rails/ujs.
Obtaining the raw response
By default, JSON responses are automatically unwrapped.
If you need access to the response, or are using MIME types, pass responseAs
:
const response = await videoClips.download({ params: video, responseAs: 'response' })
The type of the response object depends on which library you are using.
For example, it will be an AxiosResponse
if using @js-from-routes/axios.
Configuring Requests โ๏ธ
You can configure the defaults in all clients by using Config
:
import { Config } from '@js-from-routes/client'
Config.baseUrl = process.env.API_BASE_URL
Disabling Case Conversion
By default, object keys are camelCased
when deserialized, and snake_cased
when sent back to the server, but you can disable this behavior.
const noop = val => val
Config.deserializeData = noop
Config.serializeData = noop
Other Options
You can provide default headers, intercept all requests, handle response errors, and more.
A new section documenting all available configuration options will be added soon.
In the meantime, refer to the source code.