openapi-svelte-query Svelte Themes

Openapi Svelte Query

openapi-svelte-query

⚠️ openapi-svelte-query is a work-in-progress port of openapi-react-query for Svelte.

openapi-svelte-query is a type-safe tiny wrapper (1 kb) around @tanstack/svelte-query to work with OpenAPI schema.

It works by using openapi-fetch and openapi-typescript so you get all the following features:

  • ✅ No typos in URLs or params.
  • ✅ All parameters, request bodies, and responses are type-checked and 100% match your schema
  • ✅ No manual typing of your API
  • ✅ Eliminates any types that hide bugs
  • ✅ Eliminates as type overrides that can also hide bugs

Setup

Install this library along with openapi-fetch and openapi-typescript:

npm i @enchartpa/openapi-svelte-query openapi-fetch
npm i -D openapi-typescript typescript

Next, generate TypeScript types from your OpenAPI schema using openapi-typescript:

npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts

Usage

Once your types have been generated from your schema, you can create a fetch client, a svelte-query client and start querying your API.

<script lang="ts">
  import createFetchClient from "openapi-fetch";
  import createClient from "openapi-svelte-query";
  import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript

  const fetchClient = createFetchClient<paths>({
    baseUrl: "https://myapi.dev/v1/",
  });

  const api = createClient(fetchClient);

  const query = api.createQuery(
    "get",
    "/blogposts/{post_id}",
    {
      params: {
        path: { post_id: 5 },
      },
    }
  );
</script>

{#if $query.isPending || !$query.data}
  Loading...
{:else if $query.error}
  An error occurred: {$query.error.message}
{:else}
  <div>{$query.data.title}</div>
{/if}

📝 TODO

  • Write documentation for functions
  • Add support for fetchQuery and fetchInfiniteQuery
  • Add tests for prefetchQuery and prefetchInfiniteQuery
  • Add documentation for prefetchQuery and prefetchInfiniteQuery

Top categories

Loading Svelte Themes