npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

svelte-http-client

v0.1.1

Published

HTTP client returning svelte stores

Downloads

1

Readme

svelte-http-client

HTTP client returning svelte stores

Install

You can install via npm

npm i svelte-http-client

Usage

fetch$

The main method exported is fetch$, a wrapper for the Fetch API that returns a Promisable, a custom svelte store that mimics the Promise pattern. On subscription, it unwraps the Promise so it can be used like this:

<script>
    import { fetch$ } from 'svelte-http-client';

    let value$ = fetch$('https://www.my.api/myendpoint')
        .then$((res) => {
            if(!res.ok) throw new Error();
            return res;
        })
        .then$((res) => res.json())
        .catch$((err) => {
            console.error(err);
            return 'default value';
        });
</script>

<p>{$value$}</p>

HTTP verbs methods

The library exports also methods for the main HTTP verbs returning Promisable (ending with $) and Promise, each of them with a version that extract the json body:

  • get$, getJson$, get and getJson
  • post$, postJson$, post and postJson
  • put$, putJson$, put and putJson
  • patch$, patchJson$ ,patch and patchJson
  • del$, delJson$, del and delJson

These methods are also designed to throw an HttpError if the fetch Response is not ok.

The previous example, using the verbs methods, can be written as:

<script>
    import { getJson$ } from 'svelte-http-client';

    let value$ = getJson$('https://www.my.api/myendpoint')
        .catch$((err) => {
            console.error(err);
            return 'default value';
        });
</script>

<p>{$value$}</p>

SvelteHttpClient

The library exports a class to create an api client with default base URL and fetch init options, having all the methods described before:

<script>
    import { SvelteHttpClient } from 'svelte-http-client';

    const client = new SvelteHttpClient('https://www.my.api/', {
        headers: { myheader: 'myHeaderValue' }
    });

    let value$ = client.getJson$('myendpoint')
        .catch$((err) => {
            console.error(err);
            return 'default value';
        });
    let anotherValue$ = client.getJson$('myotherendpoint')
        .catch$((err) => {
            console.error(err);
            return 'default value';
        });
</script>

<p>{$value$}</p>
<p>{$anotherValue$}</p>

Promisable

The object returned by the library methods is a Promisable

interface Promisable<T, U> extends Readable<T | U> {
    then$<V>(onfulfilled?: ((value: U) => V | PromiseLike<V>) | undefined | null): Promisable<T, V>;
    catch$<V>(
        onrejected?: ((reason: any) => V | PromiseLike<V>) | undefined | null
    ): Promisable<T, U | V>;
    finally$(onfinally?: (() => void) | undefined | null): Promisable<T, U>;
    startWith$<V>(initialValue: V): Promisable<V, U>;
}

T is the initial value of the Readable, while U is the value returned by the Promise. The fetch$ method returns a Promisable<undefined, Response>. You can set the inital value chaining the startWith$ method of Promisable.

(note: contrary to the original then, the then$ method accepts onfulfilled only to enforce the use of catch$)

Here's an example using typescript:

<script lang="ts">
    import { SvelteHttpClient } from 'svelte-http-client';

    const client = new SvelteHttpClient('https://www.my.api/');

    interface Post {
        title: string;
        body: string;
    }

    function refreshPosts() {
        return client
            .getJson$<Post[]>('posts')
            .catch$<Post[]>((err) => {
                console.error(err);
                return [];
            })
            .startWith$<Post[]>([]);
    }

    let loading = false;
    let post: Post = {
        title: '',
        body: '',
    };
    let posts$ = refreshPosts();

    function add() {
        loading = true;
        client
            .post$('posts', post)
            .then$(() => {
                posts$ = refreshPosts();
            })
            .catch$((err) => alert('error: ' + err.message))
            .finally$(() => (loading = false));
    }
</script>

{#if loading}
    <div class="overlay">loading</div>
{/if}
<label class="block" for="title"> Title</label>
<input class="block" id="title" bind:value={post.title} />
<label class="block" for="body"> Post</label>
<textarea class="block" id="body" bind:value={post.body} />
<button on:click={add}>post</button>

<ul>
    {#each $posts$ as { title, body }}
        <li>
            <h2>{title}</h2>
            <p>{body}</p>
        </li>
    {/each}
</ul>

<style>
    .overlay {
        position: absolute;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100vw;
        height: 100vh;
        top: 0;
        left: 0;
        background-color: rgba(255, 255, 255, 0.8);
    }

    .block {
        margin: 10px;
        display: block;
    }
</style>