0.0.9 • Published 11 days ago

openapi-fetch-typescript v0.0.9

Weekly downloads
-
License
ISC
Repository
-
Last release
11 days ago

Usage:

npx openapi-fetch-typescript [openapi-url or path] [output-path] [client]

Only openapi url or filepath is required. Outputs a nice Typescript SDK for your OpenAPI.

Tip: use this as the fetcher for your SDK:

import { operationUrlObject, operations } from "./your-client";
import path from "path";

export const createClient = (config: {
  timeoutSeconds?: number;
  /**
   * Server URL without slash at the end
   */
  baseUrl?: string;
  headers: { [key: string]: string };
}) => {
  const db = async <K extends keyof operations>(
    operation: K,
    body?: operations[K]["requestBody"]["content"]["application/json"],

    /** NB: always use `getPersonConfig` for this! */
    customConfiguration?: {
      baseUrl?: string;
      headers?: { [key: string]: string };
    },
  ): Promise<
    operations[K]["responses"][200]["content"]["application/json"]
  > => {
    const details = operationUrlObject[operation];
    const { headers, baseUrl } = customConfiguration || config;

    if (!details) {
      throw new Error(`No details found for operation: ${operation}`);
    }
    if (!baseUrl) {
      throw new Error("No baseUrl found");
    }

    const fullUrl = `${baseUrl}${details.path}`;

    try {
      const abortController = new AbortController();
      const id = setTimeout(
        () => abortController.abort(),
        (config.timeoutSeconds || 30) * 1000,
      );

      const response = await fetch(fullUrl, {
        method: details.method,
        signal: abortController.signal,
        headers,
        body: body ? JSON.stringify(body) : undefined,
      })
        .then(async (response) => {
          if (!response.ok) {
            console.log(
              "Response not ok",
              response.status,
              response.statusText,
            );
          }
          if (!response.headers.get("Content-Type")?.includes("json")) {
            const headers = Array.from(response.headers.keys()).map((key) => ({
              [key]: response.headers.get(key),
            }));

            console.log("No JSON?", headers);
          }
          const responseText = await response.text();

          try {
            return JSON.parse(responseText);
          } catch (e) {
            console.log(`couldn't parse JSON`, {
              responseText,
              operation,
              body,
              customConfiguration,
            });
          }
        })
        .catch((error) => {
          console.log({
            explanation: `Your request could not be executed, you may be disconnected or the server may not be available. `,
            error,
            errorStatus: error.status,
            errorString: String(error),
            operation,
            body,
            customConfiguration,
          });

          return {
            isSuccessful: false,
            isNotConnected: true,
            message:
              "Could not connect to any API. Please see your API configuration.",
          };
        });

      clearTimeout(id);
      return response;
    } catch (e) {
      return {
        isSuccessful: false,
        isNotConnected: true,
        message:
          "The API didn't resolve, and the fetch crashed because of it: " +
          String(e),
      } as any;
    }
  };
  return db;
};

export const db = createClient({
  baseUrl: "http://localhost:42000",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    Authorization: `Bearer ${process.env.YOUR_AUTHTOKEN}`,
  },
  timeoutSeconds: 60,
});
0.0.9

11 days ago

0.0.8

11 days ago

0.0.7

11 days ago

0.0.5

22 days ago

0.0.6

22 days ago

0.0.4

4 months ago

0.0.3

4 months ago

0.0.2

4 months ago

0.0.1

4 months ago