Skip to content

Commit

Permalink
docs: overhaul many pages
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Apr 17, 2024
1 parent 4f8c21e commit 68eb1be
Show file tree
Hide file tree
Showing 15 changed files with 55 additions and 137 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default defineNuxtConfig({
If you were to call your API `jsonPlaceholder`, the generated composables are:

- `$jsonPlaceholder` – Returns the response data, similar to [`$fetch`](https://nuxt.com/docs/api/utils/dollarfetch#fetch)
- `useJsonPlaceholderData` – Returns [multiple values](https://nuxt-api-party.byjohann.dev/api/use-my-api-data.html#return-values) similar to [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch)
- `useJsonPlaceholderData` – Returns [multiple values](https://nuxt-api-party.byjohann.dev/api/use-fetch-like.html#return-values) similar to [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch)

Use these composables in your templates or components:

Expand Down
10 changes: 4 additions & 6 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ function nav(): DefaultTheme.NavItem[] {
{ text: 'Interceptors', link: '/guide/interceptors' },
{ text: 'Cookies', link: '/guide/cookies' },
{ text: 'Retries', link: '/guide/retries' },
{ text: 'Hydration', link: '/guide/hydration' },
{ text: 'Dynamic Backend URL', link: '/guide/dynamic-backend-url' },
],
},
Expand All @@ -108,8 +107,8 @@ function nav(): DefaultTheme.NavItem[] {
{
text: 'Composables',
items: [
{ text: 'useFetch Substitute', link: '/api/use-my-api-data' },
{ text: '$fetch Substitute', link: '/api/my-api' },
{ text: 'useFetch-like', link: '/api/use-fetch-like' },
{ text: '$fetch-like', link: '/api/dollarfetch-like' },
],
},
],
Expand Down Expand Up @@ -150,7 +149,6 @@ function sidebarGuide(): DefaultTheme.SidebarItem[] {
{ text: 'Interceptors', link: '/guide/interceptors' },
{ text: 'Cookies', link: '/guide/cookies' },
{ text: 'Retries', link: '/guide/retries' },
{ text: 'Hydration', link: '/guide/hydration' },
{ text: 'Dynamic Backend URL', link: '/guide/dynamic-backend-url' },
],
},
Expand All @@ -169,8 +167,8 @@ function sidebarApi(): DefaultTheme.SidebarItem[] {
{
text: 'Composables',
items: [
{ text: 'useFetch Substitute', link: '/api/use-my-api-data' },
{ text: '$fetch Substitute', link: '/api/my-api' },
{ text: 'useFetch-like', link: '/api/use-fetch-like' },
{ text: '$fetch-like', link: '/api/dollarfetch-like' },
],
},
]
Expand Down
2 changes: 1 addition & 1 deletion docs/api/my-api.md → docs/api/dollarfetch-like.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Nuxt `$fetch` Substitute
# `$fetch`-Like Composable

::: info
`$myApi` is a placeholder used as an example in the documentation. The composable is generated based on your API endpoint ID. For example, if you were to call an endpoint `jsonPlaceholder`, the composable will be called `$jsonPlaceholder`.
Expand Down
10 changes: 4 additions & 6 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@

## Composables

Nuxt API Party offers two distinct composable types to return data from your APIs. All composables are [auto-imported](https://nuxt.com/docs/guide/concepts/auto-imports) and globally available inside your components:
Nuxt API Party provides two distinct composable types to return data from your APIs. All composables are [auto-imported](https://nuxt.com/docs/guide/concepts/auto-imports) and globally available within your components:

- [Substitute for Nuxt `useFetch`](/api/use-my-api-data) – Returns multiple values similar to [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch)
- [Substitute for Nuxt `$fetch`](/api/my-api) – Returns the response data, similar to [`$fetch`](https://nuxt.com/docs/api/utils/dollarfetch#fetch)
- [Async data composable](/api/use-fetch-like) – Returns multiple values similar to [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch). A generated name might be `useMyApiData`.
- [Plain fetch composable](/api/dollarfetch-like) – Returns the response data, similar to [`$fetch`](https://nuxt.com/docs/api/utils/dollarfetch#fetch). A generated name might be `$myApi`.

::: info
`$myApi` and `useMyApiData` are placeholders. They are used as examples in the documentation. The actual composables are generated based on your API endpoint ID.
:::
The actual composables (and their names) are generated based on your API endpoint ID.

## Generated Composables

Expand Down
2 changes: 1 addition & 1 deletion docs/api/use-my-api-data.md → docs/api/use-fetch-like.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Nuxt `useFetch` Substitute
# `useFetch`-Like Composable

::: info
`useMyApiData` is a placeholder used as an example in the documentation. The composable is generated based on your API endpoint ID. For example, if you were to call an endpoint `jsonPlaceholder`, the composable will be called `useJsonPlaceholderData`.
Expand Down
10 changes: 5 additions & 5 deletions docs/guide/caching.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
You can cache your API responses to improve performance between multiple calls like for page navigation.

::: info
Responses from `useMyApiData` are cached by default. On the other hand, you have to enable caching for `$myApi` manually.
Responses from the [`useFetch`-like composable](/api/use-fetch-like) are cached by default. On the other hand, you have to enable caching for [`$fetch` composable](/api/dollarfetch-like) manually.
:::

## Caching Strategy
Expand All @@ -20,19 +20,19 @@ Both [generated composables](/api/#dynamic-composables) will calculate a cache k
If the cache key is already present in the cache, the cached response will be returned instead of making a new API call.

::: tip
The cache key is reactive when using `useMyApiData`. This means that the cache key will be recalculated when any of the properties change.
The cache key is reactive when using the [`useFetch`-like composable](/api/use-fetch-like). This means that the cache key will be recalculated when any of the properties change.
:::

## Custom Cache Key

For more control over when the cache should be invalidated, you can provide a custom cache key to de-duplicate requests. Please head to the API references for more information:

- [Customize the cache key for `useMyApiData`](/api/use-my-api-data#caching)
- [Customize the cache key for `$myApi`](/api/my-api#caching)
- [Customize the cache key](/api/use-fetch-like#caching) for the `useFetch`-like composable.
- [Customize the cache](/api/dollarfetch-like#caching) for the `$fetch`-like composable.

## Cache Options

You can disable the cache for each request by setting the `cache` option to `false`. This is necessary for the `useMyApiData` composable:
You can disable the cache for each request by setting the `cache` option to `false`. This is necessary for the `useFetch`-like composable:

```ts
// Disable caching for a single request
Expand Down
8 changes: 5 additions & 3 deletions docs/guide/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,9 @@ export default defineNuxtConfig({

:::

### Usage with `useJsonPlaceholderData`
### Usage With `useFetch`-Like Composable

When using the `useMyApiData` composable, the `error` is already typed as a `NuxtError`.
When using the [`useFetch`-like composable](/api/use-fetch-like) composable, the `error` is already typed as a `NuxtError`.

```ts
const { data, error } = await useJsonPlaceholderData('not/available')
Expand All @@ -75,7 +75,9 @@ watchEffect(() => {
})
```

### Usage with `$jsonPlaceholder`
### Usage With `$fetch`-Like Composable

When using the [`$fetch`-like composable](/api/dollarfetch-like) composable, you need to cast the `error` to a `NuxtError`.

```ts
import type { NuxtError } from '#app'
Expand Down
8 changes: 4 additions & 4 deletions docs/guide/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ This guide will walk you through the steps to get started with Nuxt API Party.
npx nuxi@latest module add api-party
```

## Step 2: Use the `nuxt-api-party` module
## Step 2: Use the `nuxt-api-party` Module

Add `nuxt-api-party` to your Nuxt configuration:

Expand All @@ -19,7 +19,7 @@ export default defineNuxtConfig({
})
```

## Step 3: Set Up API Endpoints
## Step 3: Set up API Endpoints

Prepare your first API connection by setting an endpoint object. Each key represents an endpoint ID, which is used to generate the composables. The value is an object with the following properties:

Expand Down Expand Up @@ -50,7 +50,7 @@ export default defineNuxtConfig({
For the API endpoint `jsonPlaceholder` above, the following composables are generated:

- `$jsonPlaceholder` – Returns the response data, similar to [`$fetch`](https://nuxt.com/docs/api/utils/dollarfetch#fetch)
- `useJsonPlaceholderData` – Returns [multiple values](/api/use-my-api-data.html#return-values) similar to [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch)
- `useJsonPlaceholderData` – Returns [multiple values](/api/use-fetch-like.html#return-values) similar to [`useFetch`](https://nuxt.com/docs/api/composables/use-fetch)

::: tip
Connect to as many API endpoints as you like. Each endpoint will generate two composables.
Expand Down Expand Up @@ -100,6 +100,6 @@ const { data, pending, refresh, error } = await useJsonPlaceholderData('posts/1'
</template>
```

## Step. 5: Your Turn
## Step 5: Your Turn

Create something awesome! I'm eager to find out what you have built. [Drop me a line](mailto:[email protected]), if you want.
16 changes: 8 additions & 8 deletions docs/guide/how-it-works.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
# How It Works

## tl;dr

The internal `/api/__api_party` server route will proxy your API request.
**tl;dr:** The internal `/api/__api_party` server route will proxy your API request.

::: tip
The proxy layer will not only pass through your API's response body to the response on the client, but also HTTP status code, HTTP status message and headers. This way, you can handle errors just like you would with a direct API call.
:::

## Detailed Answer

The generated composables will initiate a POST request to the Nuxt server route `/api/__api_party`, which then initiates the actual request for a given route to your API and passes the response back to the client. This proxy behavior has the benefit of keeping your API credentials safe from the client and omitting CORS issues, since data is sent from server to server.

During server-side rendering, calls to the Nuxt server route will directly call the relevant function (emulating the request), saving an additional API call.

::: tip
Responses are cached and hydrated to the client. Subsequent calls will return cached responses, saving duplicated requests.
:::
## Hydration

API calls executed on the server (SSR) are hydrated on the client to avoid unnecessary API calls. Thus, a request initiated on the server will not be executed again on the client.

## Nuxt Static Generation

When using `nuxi generate` to pre-render your application, the result of each API call is stored in the [Nuxt `payload`](https://nuxt.com/docs/api/composables/use-nuxt-app#payload).
7 changes: 0 additions & 7 deletions docs/guide/hydration.md

This file was deleted.

22 changes: 11 additions & 11 deletions docs/guide/interceptors.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,32 +12,32 @@ A common question when working with APIs is how to handle the HTTP status code.
Getting the HTTP status code is as simple as logging the response status from the `response` object in the `onResponse` interceptor.

```ts
const { data } = await useApiData('path', {
const { data } = await useMyApiData('path', {
onResponse(ctx) {
const status = ctx.response.status
console.log('The status code is:', status)
},
}
})
```

::: tip
The examples below work with both the `$fetch` and `useFetch` composable substitutes, `$myApi` and `useMyApiData` respectively.
The examples below use `useMyApiData` as a placeholder for the generated composable. Replace it with the actual composable name generated by Nuxt API Party. Fetch interceptors work with both the [`$fetch`-like](/api/dollarfetch-like) and [`useFetch`-like](/api/use-fetch-like) composables.
:::

## `onRequest({ request, options })`

`onRequest` is called as soon as the given composable is called, allowing you to modify options or log the request.

```ts
const { data } = await useApiData('path', {
const { data } = await useMyApiData('path', {
async onRequest({ request, options }) {
// Log the request
console.log(request, options)

// Add a timestamp to the search parameters
options.query ||= {}
options.query.t = Date.now()
},
}
})
```

Expand All @@ -46,11 +46,11 @@ const { data } = await useApiData('path', {
`onRequestError` will be called when the fetch request fails before it is made, allowing you to log the error.

```ts
const { data } = await useApiData('path', {
const { data } = await useMyApiData('path', {
async onRequestError({ request, options, error }) {
// Log the error
console.error(error)
},
}
})
```

Expand All @@ -59,11 +59,11 @@ const { data } = await useApiData('path', {
`onResponse` will be called after the fetch request is made, allowing you to log the response or modify the data.

```ts
const { data } = await useApiData('path', {
const { data } = await useMyApiData('path', {
async onResponse({ request, response, options }) {
// Log the response status code and body
console.log(response.status, response.body)
},
}
})
```

Expand All @@ -72,13 +72,13 @@ const { data } = await useApiData('path', {
`onResponseError` is the same as `onResponse` but will be called when the fetch request fails and `response.ok` is `false`.

```ts
const { data } = await useApiData('path', {
const { data } = await useMyApiData('path', {
async onResponseError({ request, response, options }) {
// Log the response status code and body
console.error(
response.status,
response.body
)
},
}
})
```
77 changes: 0 additions & 77 deletions docs/guide/migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,80 +43,3 @@ catch (error) {
console.error(error as NuxtError)
}
```

## v0.17.0

::: tip
The breaking changes only apply, if you rely on error handling with your API composables.
:::

With this version, the API response including status code and headers will be passed to the client fetch call. As such, error properties like `statusCode` and `statusMessage` of the error object contain the response status code and message, respectively. Before v0.17.0, these properties were always returning `404` and `Not Found` respectively.

```ts
import type { FetchError } from 'ofetch'

// Will now log the actual response status code
console.error(error.statusCode)
// Will now log the actual response status message
console.error(error.statusMessage)
```

The response body is still available via the `data` property of the error object and didn't change:

```ts
import type { FetchError } from 'ofetch'

// Log your API's error response
console.error('Response body:', error.data)
```

## v0.10.0

::: tip
If you're using the `endpoints` module option, you can skip this section. Nothing has changed for you!
:::

Support for the single API endpoint has been removed to keep the module simple and focused. Migration is fairly straightforward by moving your API configuration into the `endpoints` object. The former `name` property is now the key of the endpoint object:

```diff
export default defineNuxtConfig({
apiParty: {
- name: 'myApi',
- url: '<your-api-url>',
- token: '<your-api-token>',
- query: {},
- headers: {},
+ endpoints: {
+ myApi: {
+ url: '<your-api-url>',
+ token: '<your-api-token>',
+ query: {},
+ headers: {},
+ }
}
}
})
```

If you are using the following environment variables in your project's `.env` file:

```ini
API_PARTY_BASE_URL=your-api-url
# Optionally, add a bearer token
API_PARTY_TOKEN=your-api-token
```

You can now reference them in your API configuration:

```ts
export default defineNuxtConfig({
apiParty: {
endpoints: {
myApi: {
url: process.env.API_PARTY_BASE_URL!,
token: process.env.API_PARTY_TOKEN!
}
}
}
})
```
8 changes: 6 additions & 2 deletions docs/guide/openapi-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ If your framework doesn't directly support it, there may also be an additional l

To take advantage of these type features, add the `schema` property to your endpoint config. It should be set to a file path or URL of the OpenAPI schema or an async function returning the parsed OpenAPI schema. The file can be in either JSON or YAML format.

The following schema will be used for the code examples on this page.
The following schema will be used for the code examples on this page:

::: details

```yaml
# `schemas/myApi.yaml`
Expand Down Expand Up @@ -82,6 +84,8 @@ components:
- bar
```
:::
Reference the schema file in your endpoint config:
```ts
Expand All @@ -98,7 +102,7 @@ export default defineNuxtConfig({

## Using the Types

For most usages, no further intervention is needed. Nuxt API Party will use the types generated from this config to infer the correct types automatically when `$myApi` and `useMyApiData` is used.
For most usages, no further intervention is needed. Nuxt API Party will use the types generated from this configuration to infer the correct types automatically when [`useFetch`-like](/api/use-fetch-like) and [`$fetch`-like](/api/dollarfetch-like) composables are used.

However, there may be a few things you may want to do now that you have type information.

Expand Down
Loading

0 comments on commit 68eb1be

Please sign in to comment.