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

ts-route-schema

v1.1.1

Published

Strictly typed, isomorphic routes.

Downloads

54

Readme

ts-route-schema

CI GitHub Repository Typedoc

Strictly typed, isomorphic routes.

Introduction

Current Node.js server libraries and web frameworks are not very type safe. The type systems are hard to use and also easy to misuse. Furthermore, they are often not coupled with frontend code at all, making it easy for frontend code to make incorrect requests to the backend server that could have been avoided by the type compiler in the first place.

This library helps you write isomorphic code, so your backend routes and frontend HTTP requests can stay in sync. We currently only support the Express framework.

Getting Started

We assume you have an isomorphic TypeScript project set up. For best experience, operate in strict mode. Install this library using npm:

$ npm install ts-route-schema

Defining Route Schemas

First, we have to define route schemas. These are objects that describes all the HTTP methods and route type information that should be made available to both backend and frontend code:

// shared/routeSchemas.ts

import {
  RouteSchema,
  MethodSchema,
  RequestData,
  ResponseData,
} from 'ts-route-schema'

/**
 * Creates a greeting for the given name.
 */
export const HelloRouteSchema = RouteSchema('/hello/:name', {
  get: MethodSchema<
    RequestData<{
      params: {
        /**
         * The name of the person to be greeted.
         */
        name: string
      }
      query: {
        /**
         * The greeting to use.
         *
         * @default 'Hello World'
         */
        greeting?: string
      }
    }>,
    ResponseData<{
      body: {
        /**
         * The requested greeting.
         */
        message: string
      }
    }>
  >(),
})

Implementing Routes

On the backend, you can implement routes based on the previously defined route schema:

// backend/routes.ts

import { ExpressRouteImpl } from 'ts-route-schema'
import { HelloRouteSchema } from '../shared/routeSchemas'

export const HelloRoute = ExpressRouteImpl(HelloRouteSchema, {
  async get(data) {
    let greeting = data.query.greeting ?? 'Hello World'
    let message = `${greeting}, ${data.params.name}`

    return {
      body: {
        message,
      },
    }
  },
})

You can easily mount your route implementation on your Express router:

// backend/main.ts

import * as express from 'express'
import { HelloRoute } from './routes'

const app = express()

app.use(express.json())
HelloRoute.mountOn(app)

app.listen(3000)

Requesting Routes

You can request the route from the frontend as follows:

// frontend/fetchGreeting.ts

import { RouteFetcher } from 'ts-route-schema'
import { HelloRouteSchema } from '../shared/routeSchemas'

export async function fetchGreeting(
  name: string,
  greeting: string
): Promise<string> {
  let response = await RouteFetcher(HelloRouteSchema).get({
    params: { name },
    query: { greeting },
  })

  // Equivalent to:
  //
  // await fetch(
  //   `/hello/${encodeURIComponent(name)}?greeting=${encodeURIComponent(
  //     greeting
  //   )}`
  // )

  if (response.status !== 200) {
    throw new Error('Failed to get greeting')
  }

  return response.body.message
}

We're using fetch-ponyfill which is an isomorphic library, i.e. RouteFetcher also works on the backend. On the backend, you might want to set the pathPrefix option.

Building & Testing

To run the tests, execute as usual:

$ npm test

To build the project, use the build npm script:

$ npm run build

Make sure you have formatted all files using Prettier beforehand:

$ npm run format

To build the documentation, execute:

$ npm run docs