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

svetch.ts

v2.1.46

Published

End-to-End typesafe fetch client for your API

Downloads

1,552

Readme

npm svetch-chan (1)

🚀 Svetch.ts: Zero-Effort client/types/schema/OpenAPI Schema/Docs generator for your API endpoints

Typesafety, Minus the typing

👉 Check it out @ (https://svetch-dev.vercel.app/) Effortlessly generate a typesafe Fetch client for your Svelte/Sveltekit applications, complete with automatic input/output zod validation and autogenerated types & API Docs.

What is this?

Svetch automatically scans your +server.ts files in /src/routes/api (or whatever directory you specify) and generates a typesafe Fetch client that has intellisense for path, query, body parameters & all the possible responses (and errors)

🧙‍♂️ Automatic Detection

  • Query Params => Detected using any declarations of url.searchParams.get
  • 📂 Path Params => Detected from the file directory
  • 📦 Payload Definition => inferred from const payload: X = await request.json or as X
  • 💬 Response Definition => inferred from any return statement with json(X) (sveltekit utility) or new Response(X)
  • 📛 Error Definitions => inferred from any throw statement with throw error() or throw new Error or return error(HTTP_CODE, error_message)

⏬ How to run

$ npx svetch.ts@latest

Make sure you have a path alias for src in your svelte.config.js

import adapter from '@sveltejs/adapter-auto';
import { vitePreprocess } from '@sveltejs/kit/vite';

/** @type {import('@sveltejs/kit').Config} */
const config = {
	// Consult https://kit.svelte.dev/docs/integrations#preprocessors
	// for more information about preprocessors
	preprocess: vitePreprocess(),
	kit: {
		// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
		// If your environment is not supported or you settled on a specific environment, switch out the adapter.
		// See https://kit.svelte.dev/docs/adapters for more information about adapters.
		adapter: adapter(),
+		alias: {
+			"src": "./src",
		},
	}
};

export default config;

🌟 Advantages

  • 😍 ALMOST no code changes required to your existing API code
  • 🚀 Almost no learning curve, Augments a regular FETCH client with data and error along with the rest of the fetch client properties, you can use it just like a regular fetch client.
  • 🔎 Intellisense for your api paths.
  • ✅ Typesafety for api inputs & outputs.
  • 📚 Generates an OpenAPI Schema for your API, alongside with Swagger docs.
  • 📃 Can use JSDocs to add more info to the endpoint documentation (WIP)
  • 🤖 Handles multiple possible responses per http code.

Autogenerated Docs

The library will generate an OpenAPI compatible schema, alongside with swagger docs, by default in /docs/+page.svelte

⚙ Config

.svetchrc

{
  "framework": "sveltekit", // currently the only option
  "input": "src/routes/api", // the directory you want the generator to traverse
  "out": "src/lib/api", // the directory to output the types & the client to
  "docs": "src/routes/docs", // where to output docs
  "tsconfig": "tsconfig.json" // your tsconfig directory
}

🔎 Detection

  1. Svetch will traverse your input directory, will scan for any +server.ts with exported GET/POST/PUT/DELETE functions.
  2. For each endpoint it will detect...
    1. path parameters: based on the file name, e.g. user/[user_id].ts will have a path parameter of user_id
    2. query parameters: based on any parameters instantiated like url.searchParams.get('param')
    3. body parameters: based on the type of the payload Must be assigned to a const called payload ⚠ IMPORTANT
    4. response types: will pickup any top-level return statement that is instantiated like json(xxx) or new Response(xxx) along with status code

In client code

import { Svetch } from "src/lib/api/client"; // or wherever you chose to generate the client

const svetch = new Svetch({
  baseUrl: "/api", // default is '/api'
  fetch, // default is window.fetch, pass the global fetch to it in node, etc...
  validate: false, // default is false, uses Zod to validate payload + response (ON CLIENT THIS CAN MAKE THE IMPORT SIZE HUGE)
});

await svetch
  .post("user/[user_id]", {
    path: {
      user_id: 1,
    },
    body: {
      text: foodInput,
      journalId: $journal.id,
      today: new Date(),
    },
  })
  .then((response) => {
    if (response.error) throw new Error(response.error);
    food = response.data;
    loading = false;
  })
  .catch((error) => {
    throw new Error(error);
  });

In load functions

import { Svetch } from "src/lib/api/client"; // or wherever you chose to generate the client

const svetch = new Svetch({
  baseUrl: "/api", // default is '/api'
  fetch, // pass the load function's fetch to it
});

export async function load({ fetch, session }) {
  const user = await svetch.get("user").then((response) => {
    if (response.error) throw new Error(response.error);
    return response.data;
  });
  return {
    props: {
      user,
    },
  };
}

License

This library is Free for personal use, If it's useful to you, please consider purchasing a license @ https://petrasolutions.lemonsqueezy.com/checkout/buy/19210e05-ae3c-41a0-920c-324e3083618d Redistribution/Forking is Not Allowed.