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

astro-typesafe-api

v0.0.6

Published

<div width="100%" align="center"> <img alt="GitHub" src="https://img.shields.io/github/license/Letsmoe/astro-typesafe-api?label=License"> <img alt="GitHub issues" src="https://img.shields.io/github/issues/Letsmoe/astro-typesafe-api?label=Issues">

Downloads

13

Readme

Astro Typesafe API

[!NOTE] This package is a fork of astro-typed-api from lilnasy's GitHub. However, a lot of things were changed to make it suit to my needs and more versatile than the original package.

Why astro-typesafe-api?

Astro's API routes offer a powerful way to serve dynamic content. However, they operate independently of your front-end code. This means developers must handle data serialization and deserialization manually, with no guarantee that changes in API design won't disrupt UI functionality.

This integration addresses these issues by providing a type-safe api object that understands the input and return types of your API routes. Aligned with Astro's philosophy, it achieves this with minimal additional concepts to learn.

Installation

Manual Install

First, install the astro-typesafe-api package using your package manager. If you're using npm or aren't sure, run this in the terminal:

npm install astro-typesafe-api

Then, apply this integration to your astro.config.* file using the integrations property:

  // astro.config.mjs
  import { defineConfig } from 'astro/config';
+ import astroTypesafeAPI from 'astro-typesafe-api';

  export default defineConfig({
    // ...
    integrations: [astroTypesafeAPI()],
    //             ^^^^^^^^
  });

Usage

Typed API routes are created using the defineApiRoute() function, which are then exported the same way that normal API routes are in Astro.

// src/pages/api/hello.ts
import { defineApiRoute } from "astro-typesafe-api/server"
import { z } from "zod"

export const GET = defineApiRoute({
	fetch: (name: string) => `Hello, ${name}!`,
	input: z.string(),
	output: z.string()
)

The defineApiRoute() function takes an object with a fetch method. The fetch method will be called when an HTTP request is routed to the current endpoint. Parsing the request for structured data and converting the returned value to a response is handled automatically. Once defined, the API route becomes available for browser-side code to use on the api object exported from astro-typesafe-api/client:

---
// src/pages/index.astro
---
<script>
    import { api } from "astro-typesafe-api/client"

    const message = await api.hello.GET.fetch("Letsmoe")
    console.log(message) // "Hello, Letsmoe!"
</script>

When the fetch method is called on the browser, the arguments passed to it are serialized as query parameters and a GET HTTP request is made to the Astro server. The result is deserialized from the response and returned by the call.

Note that only endpoints within the src/pages/api directory are exposed on the api object. Additionally, the endpoints must all be typescript files. For example, src/pages/x.ts and src/pages/api/x.js will not be made available to astro-typesafe-api/client.

Type-safety

Types for newly created endpoints are automatically added to the api object while astro dev is running. You can also run astro sync to update the types.

Typed API stores the generated types inside .astro directory in the root of your project. The files here are automatically created, updated and used.

Input and output validation.

If defineApiRoute() is provided with a zod schema as the input and output property, the input and output of the API route will be validated against the schema automatically.

// src/pages/api/validatedHello.ts
import { defineApiRoute } from "astro-typesafe-api/server"
import { z } from "zod"

export const GET = defineApiRoute({
	input: z.object({
		user: z.string(),
	}),
	output: z.string(),
	fetch: ({ user }) => `Hello, ${user}!`,
)

Using middleware locals

The fetch() method is provided Astro's APIContext as its second argument. This allows you to read any locals that have been set in a middleware.

// src/pages/api/adminOnly.ts
import { defineApiRoute } from "astro-typesafe-api/server"

export const POST = defineApiRoute({
	input: z.string(),
	fetch: (name: string, { locals }) => {
		const { user } = locals
		if (!user) throw new Error("Visitor is not logged in.")
		if (!user.admin) throw new Error("User is not an admin.")
		...
	}
)

Setting cookies

The APIContext object also includes a set of utility functions for managing cookies which has the same interface as Astro.cookies.

// src/pages/api/setPreferences.ts
import { defineApiRoute } from "astro-typesafe-api/server"

export const PATCH = defineApiRoute({
	input: z.object({
		theme: z.enum(["light", "dark"]),
	}),
	fetch: ({ theme }, { cookies }) => {
		cookies.set("theme", theme)
	}
)

Adding response headers

The TypesafeAPIContext object extends APIContext by also including a response property which can be used to send additional headers to the browser and CDNs.

// src/pages/api/cached.ts
import { defineApiRoute } from "astro-typesafe-api/server"

export const GET = defineApiRoute({
	output: z.string(),
	fetch: (_, { response }) => {
		response.headers.set("Cache-Control", "max-age=3600")
		return "Hello, world!"
	}
)

Adding request headers

The client-side fetch() method on the api object accepts the same options as the global fetch as its second argument. It can be used to set request headers.

---
// src/pages/index.astro
---
<script>
	import { api } from "astro-typesafe-api/client"

	const message = await api.cached.GET.fetch(undefined, {
		headers: {
			"Cache-Control": "no-cache",
		}
	})
</script>

Troubleshooting

For help, check out the Discussions tab on the GitHub repo.

Contributing

This package is maintained by letsmoe independently from Astro. You're welcome to contribute by opening a PR or submitting an issue!