@koj/svelte-api-client

Koj's Fetch-powered API client for webapps

Usage no npm install needed!

<script type="module">
  import kojSvelteApiClient from 'https://cdn.skypack.dev/@koj/svelte-api-client';
</script>

README

🥅 Koj Svelte API Client

This repository contains Koj's Fetch API-powered client for interacting with our API. It is very opinionated, so usage is only recommended in Koj's Svelte projects.

| | Status | | - | - | | Build | Node CI Dependencies GitHub release (latest by date) Snyk Vulnerabilities for GitHub Repo | | Health | CLA Assistant Pull Request Labeler | | PRs | PR Generator CI Merge PRs |

⭐️ Features

  • Wrapper around the native Fetch API (95%+ support)
  • Tracks logged in users and their permissions
  • Authorization helper can based on logged in scopes
  • Built-in refreshing expired access tokens before requests
  • Response caching in IndexedDB or local storage
  • Error handling (text responses from error codes)
  • Supports different request/responses:
    • Responses can be JSON or Blob objects
    • Requests can be JSON or FormData

💻 Getting started

Install the dependency from npm:

npm install @koj/svelte-api-client

Import the api method and use it like so:

import { api } from "@koj/svelte-api-client";
import type { User } from "@koj/types";

let user: User | undefined = undefined;
const getUser = async () => {
  user = await api<User>({
    method: "GET",
    url: "/users/12345",
    onCachedResponse: (data) => (user = data),
  });
};

In the above example, the api method expects a type parameter which determines its response time. Note that JSON responses are automatically parsed. The onCachedResponse function is used to get a "faster" responses from a client side-stored cache, using the stale-while-revalidate pattern.

📄 License

MIT © Koj

Koj

An open source project by Koj.
Furnish your home in style, for as low as CHF175/month →