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-typed-api

v0.3.0

Published

This **[Astro integration][astro-integration]** offers a way to create type-safe API routes with no set-up and minimal concepts to learn.

Downloads

100

Readme

astro-typed-api ⌨️

This Astro integration offers a way to create type-safe API routes with no set-up and minimal concepts to learn.

https://github.com/lilnasy/gratelets/assets/69170106/570bcf7b-8331-4a83-8731-a3628d8c80de

Why astro-typed-api?

Astro's API routes are a great way to serve dynamic content. However, they are completely detached from your front-end code. The responsibility of serializing and deserializing data is left to the developer, and there is no indication whether a refactor in API design is going to break some UI feature. This integration aims to solve these problems by providing a type-safe api object that is aware of the input and return types of your API routes. Inline with the Astro philosophy, it does this while introducing minimum concepts to learn.

Installation

Manual Install

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

npm install astro-typed-api

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

  // astro.config.mjs
  import { defineConfig } from 'astro/config';
+ import typedApi from 'astro-typed-api';

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

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-typed-api/server"

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

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-typed-api/client:

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

    const message = await api.hello.GET.fetch("lilnasy")
    console.log(message) // "Hello, lilnasy!"
</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-typed-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 Validation

defineApiRoute() also accepts a zod schema in the definition.

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

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

When provided, the schema is used to validate the input passed to the fetch method. If the arguments are invalid, the API route returns a 500 response and the client-side call will throw. Additionally, the input type will be inferred from the schema.

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-typed-api/server"

export const POST = defineApiRoute({
    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-typed-api/server"

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

Adding response headers

The TypedAPIContext 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-typed-api/server"

export const GET = defineApiRoute({
    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-typed-api/client"
    
    const message = await api.cached.GET.fetch(undefined, {
        headers: {
            "Cache-Control": "no-cache",
        }
    })
</script>

Usage with React

Typed API does not include a hook of its own. However, it can be used with any React hook library that works with async functions. The following examples shows its usage with swr.

import useSWR from 'swr'
 
function Profile() {
  const { data, error, isLoading } = useSWR('getUser', api.user.GET.fetch)
 
  if (error) return <div>failed to load</div>
  if (isLoading) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}

Troubleshooting

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

Contributing

This package is maintained by lilnasy independently from Astro. The integration code is located at packages/typed-api/integration.ts. You're welcome to contribute by opening a PR or submitting an issue!

Changelog

See CHANGELOG.md for a history of changes to this integration.