Skip to content
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

fix: api definition endpoint as post request #1679

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 25 additions & 1 deletion packages/ui/app/src/hooks/useApiRouteSWR.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as ApiDefinition from "@fern-api/fdr-sdk/api-definition";
import useSWR, { Fetcher, SWRConfiguration, SWRResponse } from "swr";
import useSWRImmutable from "swr/immutable";
import { withSkewProtection } from "../util/withSkewProtection";
Expand All @@ -23,5 +24,28 @@ export function useApiRouteSWR<T>(route: FernDocsApiRoute, options?: Options<T>)

export function useApiRouteSWRImmutable<T>(route: FernDocsApiRoute, options?: Options<T>): SWRResponse<T> {
const key = useApiRoute(route);
return useSWRImmutable(options?.disabled ? null : key, createFetcher(options?.request), options);
return useSWRImmutable([options?.disabled ? null : key], createFetcher(options?.request), options);
}

// TODO: this fetcher is a little bit precarious, since it's not type-safe and was created hastily to resolve a specific issue. should be refactored.
// context: sometimes forward proxies will decode %2F to /, which will cause the api endpoint to not match the correct route.
// in that case, we needed to change the "GET" request to a "POST" request to get the correct endpoint.
export function useApiDefinitionSWR(
api: string | undefined,
endpointId: string | undefined,
type: "endpoint" | "websocket" | "webhook",
options?: Options<ApiDefinition.ApiDefinition>,
): SWRResponse<ApiDefinition.ApiDefinition> {
const route = useApiRoute("/api/fern-docs/api-definition");
return useSWRImmutable(
options?.disabled || api == null || endpointId == null ? null : [route, api, endpointId, type],
(): Promise<ApiDefinition.ApiDefinition> => {
return createFetcher<ApiDefinition.ApiDefinition>({
...options?.request,
method: "POST",
body: JSON.stringify({ api, [type]: endpointId }),
})(route);
},
options,
);
}
11 changes: 5 additions & 6 deletions packages/ui/app/src/playground/hooks/useEndpointContext.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { createEndpointContext, type ApiDefinition, type EndpointContext } from "@fern-api/fdr-sdk/api-definition";
import { createEndpointContext, type EndpointContext } from "@fern-api/fdr-sdk/api-definition";
import type * as FernNavigation from "@fern-api/fdr-sdk/navigation";
import { useMemo } from "react";
import { useWriteApiDefinitionAtom } from "../../atoms";
import { useApiRouteSWRImmutable } from "../../hooks/useApiRouteSWR";
import { useApiDefinitionSWR } from "../../hooks/useApiRouteSWR";

interface LoadableEndpointContext {
context: EndpointContext | undefined;
Expand All @@ -14,10 +14,9 @@ interface LoadableEndpointContext {
* It should be refactored to store the resulting endpoint in a global state, so that it can be shared between components.
*/
export function useEndpointContext(node: FernNavigation.EndpointNode | undefined): LoadableEndpointContext {
const { data: apiDefinition, isLoading } = useApiRouteSWRImmutable<ApiDefinition>(
`/api/fern-docs/api-definition/${encodeURIComponent(node?.apiDefinitionId ?? "")}/endpoint/${encodeURIComponent(node?.endpointId ?? "")}`,
{ disabled: node == null },
);
const { data: apiDefinition, isLoading } = useApiDefinitionSWR(node?.apiDefinitionId, node?.id, "endpoint", {
disabled: node == null,
});
const context = useMemo(() => createEndpointContext(node, apiDefinition), [node, apiDefinition]);
useWriteApiDefinitionAtom(apiDefinition);

Expand Down
11 changes: 5 additions & 6 deletions packages/ui/app/src/playground/hooks/useWebSocketContext.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { ApiDefinition, WebSocketContext } from "@fern-api/fdr-sdk/api-definition";
import type { WebSocketContext } from "@fern-api/fdr-sdk/api-definition";
import { createWebSocketContext } from "@fern-api/fdr-sdk/api-definition";
import type * as FernNavigation from "@fern-api/fdr-sdk/navigation";
import { useSetAtom } from "jotai";
import { useEffect, useMemo } from "react";
import { WRITE_API_DEFINITION_ATOM } from "../../atoms";
import { useApiRouteSWRImmutable } from "../../hooks/useApiRouteSWR";
import { useApiDefinitionSWR } from "../../hooks/useApiRouteSWR";

interface LoadableWebSocketContext {
context: WebSocketContext | undefined;
Expand All @@ -16,10 +16,9 @@ interface LoadableWebSocketContext {
* It should be refactored to store the resulting endpoint in a global state, so that it can be shared between components.
*/
export function useWebSocketContext(node: FernNavigation.WebSocketNode): LoadableWebSocketContext {
const { data: apiDefinition, isLoading } = useApiRouteSWRImmutable<ApiDefinition>(
`/api/fern-docs/api-definition/${encodeURIComponent(node.apiDefinitionId)}/websocket/${encodeURIComponent(node.webSocketId)}`,
{ disabled: node == null },
);
const { data: apiDefinition, isLoading } = useApiDefinitionSWR(node.apiDefinitionId, node.id, "websocket", {
disabled: node == null,
});
const context = useMemo(() => createWebSocketContext(node, apiDefinition), [node, apiDefinition]);

const set = useSetAtom(WRITE_API_DEFINITION_ATOM);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { getDocsDomainNode } from "@/server/xfernhost/node";
import * as ApiDefinition from "@fern-api/fdr-sdk/api-definition";
import { getFeatureFlags } from "@fern-ui/fern-docs-edge-config";
import { ApiDefinitionLoader } from "@fern-ui/fern-docs-server";
import { getMdxBundler } from "@fern-ui/ui/bundlers";
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import { z } from "zod";

const schema = z.object({
api: z.string(),
endpoint: z.string().optional(),
websocket: z.string().optional(),
webhook: z.string().optional(),
});

const resolveApiHandler: NextApiHandler = async (
req: NextApiRequest,
res: NextApiResponse<ApiDefinition.ApiDefinition>,
) => {
const xFernHost = getDocsDomainNode(req);
if (req.method !== "POST") {
res.status(400).end();
return;
}

const body = schema.safeParse(req.body);

if (!body.success) {
// eslint-disable-next-line no-console
console.error(body.error);
res.status(400).end();
return;
}

const { api, endpoint, websocket, webhook } = body.data;

const flags = await getFeatureFlags(xFernHost);

// TODO: pass in other tsx/mdx files to serializeMdx options
const engine = flags.useMdxBundler ? "mdx-bundler" : "next-mdx-remote";
const serializeMdx = await getMdxBundler(engine);

// TODO: authenticate the request in FDR
const loader = ApiDefinitionLoader.create(xFernHost, ApiDefinition.ApiDefinitionId(api))
.withFlags(flags)
.withMdxBundler(serializeMdx, engine)
// .withPrune({ type: "endpoint", endpointId: ApiDefinition.EndpointId(endpoint) })
.withResolveDescriptions()
.withEnvironment(process.env.NEXT_PUBLIC_FDR_ORIGIN);

if (endpoint != null) {
loader.withPrune({ type: "endpoint", endpointId: ApiDefinition.EndpointId(endpoint) });
}

if (websocket != null) {
loader.withPrune({ type: "webSocket", webSocketId: ApiDefinition.WebSocketId(websocket) });
}

if (webhook != null) {
loader.withPrune({ type: "webhook", webhookId: ApiDefinition.WebhookId(webhook) });
}

const apiDefinition = await loader.load();

if (!apiDefinition) {
return res.status(404).end();
}

// Cache the response in Vercel's Data Cache for 1 hour, and allow it to be served stale for up to 24 hours
res.setHeader("Cache-Control", "public, s-maxage=3600, stale-while-revalidate=86400");

return res.status(200).json(apiDefinition);
};

export default resolveApiHandler;
Loading