diff --git a/docs/content/2.setup.md b/docs/content/2.setup.md index d987f95b..6ccae033 100644 --- a/docs/content/2.setup.md +++ b/docs/content/2.setup.md @@ -26,7 +26,6 @@ export default { } ``` - ## Options Defaults: @@ -37,7 +36,11 @@ Defaults: prefix: '/api', version: 'v4', cookie: {}, - cookieName: 'strapi_jwt' + cookieName: 'strapi_jwt', + auth: {}, + apiToken: process.env.STRAPI_API_TOKEN || '', + defaultToken: 'user', + devtools: false } ``` @@ -111,6 +114,25 @@ Configure the `fields` query param of the `/users/me` route. > Learn more on [Field Selection documentation](https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest/populating-fields.html#field-selection). +### `apiToken` + +::badge +v1.9.0+ +:: + +API token used for your requests. When provided, this will be used when the jwt token is unavailable or [`defaultToken`](#defaulttoken) is set to `api`. + +Environment variable `STRAPI_API_TOKEN` can be used to override this option. + +> Learn more on [API Tokens](https://docs.strapi.io/dev-docs/configurations/api-tokens). +### `defaultToken` + +::badge +v1.9.0+ +:: + +Default token used for the [`useStrapi`](/usage#usestrapi) and [`useStrapiClient`](/usage#usestrapiclient) composables. Value can be either `user` or `api`. + ### `devtools` ::badge diff --git a/docs/content/3.usage.md b/docs/content/3.usage.md index 4a43ccd7..2478c3a6 100644 --- a/docs/content/3.usage.md +++ b/docs/content/3.usage.md @@ -25,7 +25,7 @@ All examples below are demonstrated with http calls in script setup. However, to When using the composable, you can pass in a default data model for all methods. ```ts -const { find } = useStrapi() +const { findOne } = useStrapi() // typed to Course findOne('courses', '123') @@ -34,12 +34,30 @@ findOne('courses', '123') If you prefer not to use a default data type and want to override the default, you can pass the data model on individual methods as well. ```ts -const { find } = useStrapi() +const { findOne } = useStrapi() // typed to SpecialCourse findOne('courses', '123') ``` +### Options + +You can pass an object to the composable to override defaults. + +```ts +const config = useRuntimeConfig() +const options = { + token: config.customToken +} +const { findOne } = useStrapi(options) +// This will now use your customToken for requests. +findOne('courses', '123') +``` + +::alert{type="warning"} +Currently the only option you can override is `token`. +:: + ### `find` Get entries. Returns entries matching the query filters (see [parameters](https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest-api.html#api-parameters) documentation). @@ -244,6 +262,10 @@ const restaurant = await client('/restaurants', { method: 'POST', bo ``` +::alert{type="info"} +You can pass the same [`options`](#options) object to this composable as you can in `useStrapi`. +:: + ## `useStrapiUrl` This composable is an helper to get the strapi url endpoint. It is used internally to reach the api in the `useStrapiClient` composable. diff --git a/src/module.ts b/src/module.ts index bf98e021..49388d35 100644 --- a/src/module.ts +++ b/src/module.ts @@ -55,6 +55,20 @@ export interface ModuleOptions { */ auth?: AuthOptions + /** + * Strapi API Token + * @default '' + * @type string | undefined + */ + apiToken?: string, + + /** + * Default Token for Requests + * @default 'user' + * @type 'api' | 'user' + */ + defaultToken?: 'api' | 'user', + /** * Add Strapi Admin in Nuxt Devtools * @@ -78,11 +92,17 @@ export default defineNuxtModule({ prefix: '/api', version: 'v4', cookie: {}, - auth: {}, cookieName: 'strapi_jwt', + auth: {}, + apiToken: process.env.STRAPI_API_TOKEN || '', + defaultToken: 'user', devtools: false }, setup (options, nuxt) { + if (options.defaultToken === 'api' && !options.apiToken) { + throw new Error('Missing `STRAPI_API_TOKEN` in `.env`') + } + // Default runtimeConfig nuxt.options.runtimeConfig.public.strapi = defu(nuxt.options.runtimeConfig.public.strapi, options) nuxt.options.runtimeConfig.strapi = defu(nuxt.options.runtimeConfig.strapi, options) diff --git a/src/runtime/composables-v3/useStrapi.ts b/src/runtime/composables-v3/useStrapi.ts index 922f8b59..0e2d0a14 100644 --- a/src/runtime/composables-v3/useStrapi.ts +++ b/src/runtime/composables-v3/useStrapi.ts @@ -11,6 +11,8 @@ interface StrapiV3Client { delete(contentType: string, id?: string | number): Promise } -export const useStrapi = (): StrapiV3Client => { - return useStrapi3() +export const useStrapi = (options?: { + token?: string +}): StrapiV3Client => { + return useStrapi3(options) } diff --git a/src/runtime/composables-v3/useStrapi3.ts b/src/runtime/composables-v3/useStrapi3.ts index 4d3784bf..36b832ab 100644 --- a/src/runtime/composables-v3/useStrapi3.ts +++ b/src/runtime/composables-v3/useStrapi3.ts @@ -4,8 +4,10 @@ import { useStrapiVersion, useStrapiClient } from '#imports' /** * @deprecated use `useStrapi` for correct types */ -export const useStrapi3 = () => { - const client = useStrapiClient() +export const useStrapi3 = (options?: { + token?: string +}) => { + const client = useStrapiClient(options) const version = useStrapiVersion() if (version !== 'v3') { // eslint-disable-next-line no-console diff --git a/src/runtime/composables-v4/useStrapi.ts b/src/runtime/composables-v4/useStrapi.ts index d178a01b..a7674ad0 100644 --- a/src/runtime/composables-v4/useStrapi.ts +++ b/src/runtime/composables-v4/useStrapi.ts @@ -10,6 +10,8 @@ interface StrapiV4Client { delete(contentType: string, id?: string | number): Promise> } -export const useStrapi = (): StrapiV4Client => { - return useStrapi4() +export const useStrapi = (options?: { + token?: string +}): StrapiV4Client => { + return useStrapi4(options) } diff --git a/src/runtime/composables-v4/useStrapi4.ts b/src/runtime/composables-v4/useStrapi4.ts index ca569223..b74d8215 100644 --- a/src/runtime/composables-v4/useStrapi4.ts +++ b/src/runtime/composables-v4/useStrapi4.ts @@ -4,8 +4,10 @@ import { useStrapiVersion, useStrapiClient } from '#imports' /** * @deprecated use `useStrapi` for correct types */ -export const useStrapi4 = () => { - const client = useStrapiClient() +export const useStrapi4 = (options?: { + token?: string +}) => { + const client = useStrapiClient(options) const version = useStrapiVersion() if (version !== 'v4') { // eslint-disable-next-line no-console diff --git a/src/runtime/composables/useStrapiClient.ts b/src/runtime/composables/useStrapiClient.ts index 11439297..c34ea85b 100644 --- a/src/runtime/composables/useStrapiClient.ts +++ b/src/runtime/composables/useStrapiClient.ts @@ -1,6 +1,6 @@ import type { FetchError, FetchOptions } from 'ohmyfetch' import { stringify } from 'qs' -import { useNuxtApp } from '#app' +import { useNuxtApp, useRuntimeConfig } from '#app' import type { Strapi4Error } from '../types/v4' import type { Strapi3Error } from '../types/v3' import { useStrapiUrl } from './useStrapiUrl' @@ -23,17 +23,24 @@ const defaultErrors = (err: FetchError) => ({ } }) -export const useStrapiClient = () => { +export const useStrapiClient = (options?: { + token?: string +}) => { const nuxt = useNuxtApp() const baseURL = useStrapiUrl() const version = useStrapiVersion() - const token = useStrapiToken() + const userToken = useStrapiToken() + const config = useRuntimeConfig() return async (url: string, fetchOptions: FetchOptions = {}): Promise => { const headers: HeadersInit = {} - if (token && token.value) { - headers.Authorization = `Bearer ${token.value}` + if (options?.token) { + headers.Authorization = `Bearer ${options.token}` + } else if (config.strapi.defaultToken === 'user' && userToken.value) { + headers.Authorization = `Bearer ${userToken.value}` + } else if ((config.strapi.defaultToken === 'api' && config.strapi.apiToken) || config.strapi.apiToken) { + headers.Authorization = `Bearer ${config.strapi.apiToken}` } // Map params according to strapi v3 and v4 formats