Skip to content

Commit

Permalink
chore: initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Oct 7, 2022
0 parents commit 8f37b4e
Show file tree
Hide file tree
Showing 23 changed files with 7,220 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
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
3 changes: 3 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "@antfu"
}
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
custom: ['https://paypal.me/jschopplich']
33 changes: 33 additions & 0 deletions .github/workflows/release.yml
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 }}
51 changes: 51 additions & 0 deletions .gitignore
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
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
shamefully-hoist=true
strict-peer-dependencies=false
5 changes: 5 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"dbaeumer.vscode-eslint"
]
}
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"prettier.enable": false,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
21 changes: 21 additions & 0 deletions LICENSE
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.
210 changes: 210 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
# nuxt-api-party

[![npm version](https://img.shields.io/npm/v/nuxt-api-party?color=a1b858&label=)](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)
Loading

0 comments on commit 8f37b4e

Please sign in to comment.