-
-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 8f37b4e
Showing
23 changed files
with
7,220 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
root = true | ||
|
||
[*] | ||
charset = utf-8 | ||
indent_style = space | ||
indent_size = 2 | ||
end_of_line = lf | ||
insert_final_newline = true | ||
trim_trailing_whitespace = true | ||
|
||
[*.md] | ||
trim_trailing_whitespace = false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
{ | ||
"extends": "@antfu" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
custom: ['https://paypal.me/jschopplich'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
name: Release | ||
|
||
on: | ||
push: | ||
tags: | ||
- 'v*' | ||
|
||
jobs: | ||
release: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- uses: actions/checkout@v3 | ||
with: | ||
fetch-depth: 0 | ||
|
||
- uses: actions/setup-node@v3 | ||
with: | ||
node-version: 16 | ||
registry-url: https://registry.npmjs.org/ | ||
|
||
- run: corepack enable | ||
|
||
- name: Install | ||
run: pnpm i | ||
|
||
- name: Publish to npm | ||
run: npm publish --access public | ||
env: | ||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} | ||
|
||
- run: npx changelogithub | ||
env: | ||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
# Dependencies | ||
node_modules | ||
|
||
# Logs | ||
*.log* | ||
|
||
# Temp directories | ||
.temp | ||
.tmp | ||
.cache | ||
|
||
# Yarn | ||
**/.yarn/cache | ||
**/.yarn/*state* | ||
|
||
# Generated dirs | ||
dist | ||
|
||
# Nuxt | ||
.nuxt | ||
.output | ||
.vercel_build_output | ||
.build-* | ||
.env | ||
.netlify | ||
|
||
# Env | ||
.env | ||
|
||
# Testing | ||
reports | ||
coverage | ||
*.lcov | ||
.nyc_output | ||
|
||
# VSCode | ||
# .vscode | ||
|
||
# Intellij idea | ||
*.iml | ||
.idea | ||
|
||
# OSX | ||
.DS_Store | ||
.AppleDouble | ||
.LSOverride | ||
.AppleDB | ||
.AppleDesktop | ||
Network Trash Folder | ||
Temporary Items | ||
.apdisk |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
shamefully-hoist=true | ||
strict-peer-dependencies=false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"recommendations": [ | ||
"dbaeumer.vscode-eslint" | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"prettier.enable": false, | ||
"editor.codeActionsOnSave": { | ||
"source.fixAll.eslint": true | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2022 Johann Schopplich <https://github.com/johannschopplich> | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,210 @@ | ||
# nuxt-api-party | ||
|
||
[](https://www.npmjs.com/package/nuxt-api-party) | ||
|
||
This module provides composables to fetch data from an API of your choice securely. | ||
|
||
You can customize the composable names! Given `json-placeholder` set as the module option `name` in your Nuxt config, the composables `$jsonPlaceholder` and `useJsonPlaceholderData` will be available globally. | ||
|
||
## Features | ||
|
||
- 🪅 Dynamic composable names | ||
- 🔒 Protect your API credentials in the client | ||
- 🪢 Token-based authentication built-in or bring your own headers | ||
- 🍱 Handle request similar to [`useFetch`](https://v3.nuxtjs.org/api/composables/use-fetch) | ||
- 🗃 Cached responses | ||
- 🦾 Strongly typed | ||
|
||
## Setup | ||
|
||
```bash | ||
# pnpm | ||
pnpm add -D nuxt-api-party | ||
|
||
# npm | ||
npm i -D nuxt-api-party | ||
``` | ||
|
||
## How It Works | ||
|
||
Composables will initiate a POST request to the Nuxt server route `/api/__api_party__`, which then fetches the actual data for a given route from your API and passes the response back to the template/client. This proxy behaviour has the benefit of 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. | ||
|
||
> ℹ️ Responses are cached and hydrated to the client. Subsequent calls will return cached responses, saving duplicated requests. | ||
## Basic Usage | ||
|
||
Add `nuxt-api-party` to your Nuxt config and tell the module options the name of your API: | ||
|
||
```ts | ||
// `nuxt.config.ts` | ||
export default defineNuxtConfig({ | ||
modules: ['nuxt-api-party'], | ||
|
||
apiParty: { | ||
// Needed for the names of the composables | ||
name: 'json-placeholder' | ||
} | ||
}) | ||
``` | ||
|
||
Set the following environment variables in your project's `.env` file: | ||
|
||
```bash | ||
API_PARTY_BASE_URL=https://jsonplaceholder.typicode.com | ||
# Optionally, add a bearer token | ||
# API_PARTY_TOKEN=test | ||
``` | ||
|
||
If you were to call your API `json-placeholder`, the generated composables are: | ||
|
||
- `$jsonPlaceholder` – Returns the response data, similar to `$fetch` | ||
- `useJsonPlaceholderData` – Returns [multiple values](#usepartydata) similar to `useFetch` | ||
|
||
Finally, fetch data from your API in your template: | ||
|
||
```vue | ||
<script setup lang="ts"> | ||
interface JsonPlaceholderPost { | ||
userId: number | ||
id: number | ||
title: string | ||
body: string | ||
} | ||
// `data` will be typed as `Ref<JsonPlaceholderPost | null>` | ||
const { data, pending, refresh, error } = await useJsonPlaceholderData<JsonPlaceholderPost>('posts/1') | ||
</script> | ||
<template> | ||
<div> | ||
<h1>{{ data?.title }}</h1> | ||
<pre>{{ JSON.stringify(data, undefined, 2) }}</pre> | ||
</div> | ||
</template> | ||
``` | ||
|
||
## Composables | ||
|
||
> ℹ️ The headings of the following sections aren't available as-is. As an example, the module option `name` is set to `party`. | ||
### `$party` | ||
|
||
Returns the API response data. | ||
|
||
**Types** | ||
|
||
```ts | ||
function $party<T = any>( | ||
uri: string, | ||
opts: ApiFetchOptions = {}, | ||
): Promise<T> | ||
|
||
type ApiFetchOptions = Pick< | ||
FetchOptions, | ||
'onRequest' | 'onRequestError' | 'onResponse' | 'onResponseError' | 'headers' | ||
> | ||
``` | ||
**Example** | ||
```vue | ||
<script setup lang="ts"> | ||
const data = await $party( | ||
'posts/1', | ||
{ | ||
async onRequest({ request }) { | ||
console.log(request) | ||
}, | ||
async onResponse({ response }) { | ||
console.log(response) | ||
}, | ||
async onRequestError({ error }) { | ||
console.log(error) | ||
}, | ||
async onResponseError({ error }) { | ||
console.log(error) | ||
}, | ||
} | ||
) | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<h1>{{ data?.title }}</h1> | ||
</div> | ||
</template> | ||
``` | ||
|
||
### `usePartyData` | ||
|
||
Return values: | ||
|
||
- **data**: the response of the API request | ||
- **pending**: a boolean indicating whether the data is still being fetched | ||
- **refresh**: a function that can be used to refresh the data returned by the handler function | ||
- **error**: an error object if the data fetching failed | ||
|
||
By default, Nuxt waits until a `refresh` is finished before it can be executed again. Passing `true` as parameter skips that wait. | ||
|
||
**Types** | ||
|
||
```ts | ||
export function usePartyData<T = any>( | ||
uri: MaybeComputedRef<string>, | ||
opts: UseApiDataOptions<T> = {}, | ||
): AsyncData<T, FetchError | null | true> | ||
|
||
type UseApiDataOptions<T> = Pick< | ||
UseFetchOptions<T>, | ||
// Pick from `AsyncDataOptions` | ||
| 'lazy' | ||
| 'default' | ||
| 'watch' | ||
| 'initialCache' | ||
| 'immediate' | ||
// Pick from `FetchOptions` | ||
| 'onRequest' | ||
| 'onRequestError' | ||
| 'onResponse' | ||
| 'onResponseError' | ||
// Pick from `globalThis.RequestInit` | ||
| 'headers' | ||
> | ||
``` | ||
The composable infers most of the [`useAsyncData` options](https://v3.nuxtjs.org/api/composables/use-async-data/#params). | ||
**Example** | ||
```vue | ||
<script setup lang="ts"> | ||
const { data, pending, error, refresh } = await usePartyData('posts/1') | ||
</script> | ||
|
||
<template> | ||
<div> | ||
<h1>{{ data?.result?.title }}</h1> | ||
<button @click="refresh()"> | ||
Refresh | ||
</button> | ||
</div> | ||
</template> | ||
``` | ||
|
||
## 💻 Development | ||
|
||
1. Clone this repository | ||
2. Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10) | ||
3. Install dependencies using `pnpm install` | ||
4. Run `pnpm run dev:prepare` | ||
5. Start development server using `pnpm run dev` | ||
|
||
## Special Thanks | ||
|
||
- [Dennis Baum](https://github.com/dennisbaum) for sponsoring this package! | ||
|
||
## License | ||
|
||
[MIT](./LICENSE) License © 2022 [Johann Schopplich](https://github.com/johannschopplich) |
Oops, something went wrong.