OpenAPI: Persist authorization field

This commit is contained in:
fuma-nama
2024-08-23 14:18:39 +08:00
parent 0a1f931798
commit 6cf5535a0a
3 changed files with 26 additions and 2 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'fumadocs-openapi': minor
---
Persist `authorization` field
+3 -2
View File
@@ -76,7 +76,7 @@ export interface APIPlaygroundProps {
route: string;
method: string;
bodyType: 'json' | 'form-data';
authorization?: PrimitiveRequestField;
authorization?: PrimitiveRequestField & { authType: string };
path?: PrimitiveRequestField[];
query?: PrimitiveRequestField[];
header?: PrimitiveRequestField[];
@@ -133,7 +133,7 @@ export function Playground({
function getAuthorizationField(
method: MethodInformation,
ctx: RenderContext,
): PrimitiveRequestField | undefined {
): (PrimitiveRequestField & { authType: string }) | undefined {
const security = method.security ?? ctx.document.security ?? [];
if (security.length === 0) return;
const singular = security.find(
@@ -146,6 +146,7 @@ function getAuthorizationField(
return {
type: 'string',
name: 'Authorization',
authType: scheme.type,
defaultValue:
scheme.type === 'oauth2' ||
(scheme.type === 'http' && scheme.scheme === 'bearer')
+18
View File
@@ -5,6 +5,7 @@ import {
useMemo,
useRef,
useState,
useEffect,
} from 'react';
import { Controller, useForm, useWatch } from 'react-hook-form';
import useSWRImmutable from 'swr/immutable';
@@ -136,6 +137,23 @@ export function APIPlayground({
},
);
useEffect(() => {
if (!authorization) return;
const key = `__fumadocs_authorization_${authorization.authType}`;
const cached = localStorage.getItem(key);
if (cached) form.setValue('authorization', cached);
const subscription = form.watch((value, { name }) => {
if (name !== 'authorization' || !value.authorization) return;
localStorage.setItem(key, value.authorization);
});
return () => {
subscription.unsubscribe();
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- mounted only once
}, []);
const onSubmit = form.handleSubmit((value) => {
setInput(value);
});