Skip to content

feat: openapi spec driven management api reference #790

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 25 commits into from
Apr 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 170 additions & 0 deletions components/ApiReference/ApiReference.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"use client";

import Link from "next/link";
import { ApiReferenceProvider } from "../../components/ApiReference/ApiReferenceContext";
import { ApiReferenceSection } from "../../components/ApiReference";
import MinimalHeader from "../../components/Header/MinimalHeader";
import Sidebar from "../../components/Sidebar";
import { Page } from "../../layouts/Page";
import { useEffect, useLayoutEffect } from "react";
import { useRouter } from "next/router";
import { StainlessConfig } from "../../lib/openApiSpec";
import { OpenAPIV3 } from "@scalar/openapi-types";
import { getSidebarContent } from "./helpers";
import { SidebarSection } from "../../data/types";

type Props = {
name: string;
openApiSpec: OpenAPIV3.Document;
stainlessSpec: StainlessConfig;
preContent?: React.ReactNode;
preSidebarContent?: SidebarSection[];
resourceOrder: string[];
};

function onElementClick(e: Event) {
e.preventDefault();
e.stopPropagation();
}

function ApiReference({
name,
openApiSpec,
stainlessSpec,
preContent,
preSidebarContent,
resourceOrder = [],
}: Props) {
const router = useRouter();
const basePath = router.pathname.split("/")[1];

useEffect(() => {
const path = router.asPath;

const resourcePath = path.replace(`/${basePath}`, "");
const element = document.querySelector(
`[data-resource-path="${resourcePath}"]`,
);

element?.scrollIntoView();
}, [router.asPath, basePath]);

useLayoutEffect(() => {
document
.querySelector(".sidebar a")
?.addEventListener("click", onElementClick);

const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const resourcePath =
entry.target.getAttribute("data-resource-path");

const lastActiveElements =
document.querySelectorAll(".sidebar .active");

const newActiveElement = document.querySelector(
`.sidebar a[href*='/${basePath}${resourcePath}']`,
)?.parentElement;

if (lastActiveElements.length > 0) {
lastActiveElements.forEach((element) => {
element.parentElement?.parentElement?.classList.remove(
"sidebar-subsection--active",
);

element.classList.remove("active");
});
}

if (newActiveElement) {
newActiveElement.parentElement?.parentElement?.classList.add(
"sidebar-subsection--active",
);

newActiveElement.classList.add("active");
newActiveElement.scrollIntoView({
behavior: "smooth",
block: "center",
});
}

if (resourcePath) {
window.history.replaceState(
null,
"",
`/${basePath}${resourcePath}`,
);
}
}
});
},
{
threshold: 0.1,
rootMargin: "-64px 0px -80% 0px",
},
);

// Observe all elements with data-resource-path
document.querySelectorAll("[data-resource-path]").forEach((element) => {
observer.observe(element);
});

// Cleanup observer on unmount
return () => observer.disconnect();
}, [basePath]);

return (
<ApiReferenceProvider
openApiSpec={openApiSpec}
stainlessConfig={stainlessSpec}
>
<div className="wrapper">
<Page
header={<MinimalHeader pageType="API" />}
sidebar={
<Sidebar
content={getSidebarContent(
openApiSpec,
stainlessSpec,
resourceOrder,
basePath,
preSidebarContent,
)}
>
<Link
href="/"
passHref
className="text-sm block font-medium text-gray-500 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-100"
>
&#8592; Back to docs
</Link>
</Sidebar>
}
metaProps={{
title: `Knock ${name} Reference | Knock`,
description: `Complete reference documentation for the Knock ${name}.`,
}}
>
<div className="w-full max-w-5xl lg:flex mx-auto relative">
<div className="w-full flex-auto">
<div className="docs-content api-docs-content">
{preContent}
{resourceOrder.map((resourceName) => (
<ApiReferenceSection
key={resourceName}
resourceName={resourceName}
resource={stainlessSpec.resources[resourceName]}
/>
))}
</div>
</div>
</div>
</Page>
</div>
</ApiReferenceProvider>
);
}

export default ApiReference;
59 changes: 59 additions & 0 deletions components/ApiReference/ApiReferenceContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { createContext, useContext, ReactNode } from "react";
import { OpenAPIV3 } from "@scalar/openapi-types";
import { StainlessConfig } from "../../lib/openApiSpec";
import { buildSchemaReferences } from "./helpers";
import { useRouter } from "next/router";

interface ApiReferenceContextType {
openApiSpec: OpenAPIV3.Document;
stainlessConfig: StainlessConfig;
baseUrl: string;
schemaReferences: Record<string, string>;
}

const ApiReferenceContext = createContext<ApiReferenceContextType | undefined>(
undefined,
);

interface ApiReferenceProviderProps {
children: ReactNode;
openApiSpec: OpenAPIV3.Document;
stainlessConfig: StainlessConfig;
}

export function ApiReferenceProvider({
children,
openApiSpec,
stainlessConfig,
}: ApiReferenceProviderProps) {
const router = useRouter();
const basePath = router.pathname.split("/")[1];

const baseUrl = stainlessConfig.environments.production;
const schemaReferences = buildSchemaReferences(
openApiSpec,
stainlessConfig,
Object.keys(stainlessConfig.resources),
`/${basePath}`,
);

return (
<ApiReferenceContext.Provider
value={{ openApiSpec, stainlessConfig, baseUrl, schemaReferences }}
>
{children}
</ApiReferenceContext.Provider>
);
}

export function useApiReference() {
const context = useContext(ApiReferenceContext);
if (context === undefined) {
throw new Error(
"useApiReference must be used within an ApiReferenceProvider",
);
}
return context;
}

export default ApiReferenceContext;
140 changes: 140 additions & 0 deletions components/ApiReference/ApiReferenceMethod/ApiReferenceMethod.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import type { OpenAPIV3 } from "@scalar/openapi-types";
import { useState } from "react";
import Markdown from "react-markdown";

import { Endpoint } from "../../Endpoints";
import { ContentColumn, ExampleColumn, Section } from "../../ApiSections";
import { CodeBlock } from "../../CodeBlock";
import { useApiReference } from "../ApiReferenceContext";
import { SchemaProperties } from "../SchemaProperties";
import OperationParameters from "../OperationParameters/OperationParameters";
import { PropertyRow } from "../SchemaProperties/PropertyRow";
import MultiLangExample from "../MultiLangExample";
import { augmentSnippetsWithCurlRequest } from "../helpers";
import Link from "next/link";

type Props = {
methodName: string;
methodType: "get" | "post" | "put" | "delete";
endpoint: string;
};

function ApiReferenceMethod({ methodName, methodType, endpoint }: Props) {
const { openApiSpec, baseUrl, schemaReferences } = useApiReference();
const [isResponseExpanded, setIsResponseExpanded] = useState(false);
const method = openApiSpec.paths?.[endpoint]?.[methodType];

if (!method) {
return null;
}

const parameters = method.parameters || [];
const responses = method.responses || {};
const response = responses[Object.keys(responses)[0]];

const pathParameters = parameters.filter(
(p) => p.in === "path",
) as OpenAPIV3.ParameterObject[];
const queryParameters = parameters.filter(
(p) => p.in === "query",
) as OpenAPIV3.ParameterObject[];

const responseSchema: OpenAPIV3.SchemaObject | undefined =
response?.content?.["application/json"]?.schema;
const requestBody: OpenAPIV3.SchemaObject | undefined =
method.requestBody?.content?.["application/json"]?.schema;

return (
<Section title={method.summary} slug={method.summary}>
<ContentColumn>
<Markdown>{method.description ?? ""}</Markdown>

<h3 className="!text-sm font-medium">Endpoint</h3>

<Endpoint
method={methodType.toUpperCase()}
path={`${endpoint}`}
name={methodName}
/>

{pathParameters.length > 0 && (
<>
<h3 className="!text-base font-medium">Path parameters</h3>
<OperationParameters parameters={pathParameters} />
</>
)}

{queryParameters.length > 0 && (
<>
<h3 className="!text-base font-medium">Query parameters</h3>
<OperationParameters parameters={queryParameters} />
</>
)}

{requestBody && (
<>
<h3 className="!text-base font-medium">Request body</h3>
<SchemaProperties schema={requestBody} />
</>
)}

<h3 className="!text-base font-medium">Returns</h3>

{responseSchema && (
<PropertyRow.Wrapper>
<PropertyRow.Container>
<PropertyRow.Header>
<PropertyRow.Type
href={schemaReferences[responseSchema.title ?? ""]}
>
{responseSchema.title}
</PropertyRow.Type>
</PropertyRow.Header>
<PropertyRow.Description>
<Markdown>{responseSchema.description ?? ""}</Markdown>
</PropertyRow.Description>

{responseSchema.properties && (
<>
<PropertyRow.ExpandableButton
isOpen={isResponseExpanded}
onClick={() => setIsResponseExpanded(!isResponseExpanded)}
>
{isResponseExpanded ? "Hide properties" : "Show properties"}
</PropertyRow.ExpandableButton>

{isResponseExpanded && (
<PropertyRow.ChildProperties>
<SchemaProperties schema={responseSchema} hideRequired />
</PropertyRow.ChildProperties>
)}
</>
)}
</PropertyRow.Container>
</PropertyRow.Wrapper>
)}
</ContentColumn>
<ExampleColumn>
<MultiLangExample
title={`${method.summary} (example)`}
examples={augmentSnippetsWithCurlRequest(
method["x-stainless-snippets"],
{
baseUrl,
methodType,
endpoint,
body: requestBody?.example,
},
)}
/>
{responseSchema?.example && (
<CodeBlock title="Response" language="json" languages={["json"]}>
{JSON.stringify(responseSchema?.example, null, 2)}
</CodeBlock>
)}
</ExampleColumn>
</Section>
);
}

export default ApiReferenceMethod;
1 change: 1 addition & 0 deletions components/ApiReference/ApiReferenceMethod/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "./ApiReferenceMethod";
Loading
Loading