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

@jcwillox/typebox-x

v1.3.0

Published

Tools for working with TypeBox

Downloads

244

Readme

TypeBox Extensions

License Version Bundle Size Publish Size Code style

TypeBox extensions (typebox-x) is a utility library based around the sinclairzx81/typebox schema builder and validation library.

Features

  • Validate and coerce environment variables (like t3-env).
  • Additional kinds and shorthands, e.g. t.UUID.
  • Built in configuration for common formats, e.g. date, email, uri.
  • Built in support for NestJS

Install

pnpm add @jcwillox/typebox-x @sinclair/typebox

Load envs

First import the createEnv function, then pass it a typebox schema.

The createEnv function uses the clean, convert, default and decode function from typebox to parse you environment variables.

This means that it will strip extra keys, set default values, attempt to convert values to the destination type, e.g. "true" -> true, and then decode/check the value.

import { createEnv } from "@jcwillox/typebox-x";

const env = createEnv(
  t.Object({
    APP_ENV: t.Optional(t.String()),
    NODE_ENV: t.String({ default: "development" }),
    BOOL_FLAG: t.Boolean(),
  }),
);

console.log(env.BOOL_FLAG === true); // -> true

Variants

Nullable

  • Wraps schema in a union with null.
    t.Nullable(t.String());
    // t.Union([t.String(), t.Null()]);

Nullish

  • Wraps schema in an optional union with null.
    t.Nullish(t.String());
    // t.Optional(t.Union([t.String(), t.Null()]));

UUID

  • Shorthand for string of format uuid.
    t.UUID();
    // t.String({ format: "uuid" })

DateString

  • Uses Transform to convert a string to a Date object when decoding and from a Date object to a string when encoding.
    t.DateString();

RecordString

  • A replacement for t.Record that uses t.String as the key type, and adds the additionalProperties property, for backwards compatibility with OpenAPI 3.0.
    t.RecordString(t.Object({ one: t.String() }));
    // Record<string, {a: string}>
    Equivalent to:
    t.Record(t.String(), schema, {
      additionalProperties: schema,
    });

StringEnum

  • Creates a union of strings with a enum schema representation
    t.StringEnum(["one", "two"]);

LiteralEnum

  • Drop-in replacement for t.Literal that adds the type and enum properties, for backwards compatibility with OpenAPI 3.0.
  • You should override Literal with this function, for OpenAPI 3.0 compatibility.
    t.LiteralEnum("one");

Formats

Simply import @jcwillox/typebox-x/formats before you perform any validations, usually you'll want to do this in you entrypoint. If a format is already defined with the same name, it will not be overwritten.

import "@jcwillox/typebox-x/formats";

NestJS

Use the typebox prefixed method decorators and provide the corresponding schemas.

import { Controller } from "@nestjs/common";
import { t } from "@jcwillox/typebox-x";
import { TypeboxGet } from "@jcwillox/typebox-x/nestjs";
// or if you prefer we also export non-prefixed methods
// import { Get } from "@jcwillox/typebox-x/nestjs";

@Controller()
export class AppController {
  @TypeboxGet(":my_id", {
    query: t.Object({
      limit: t.Optional(t.Integer({ default: 10 })),
    }),
    params: {
      my_id: t.UUID(),
    },
    response: t.Object({
      message: t.String(),
    }),
  })
  getHello() {
    return { message: "Hello World!" };
  }
}

You'll likely want to define your schemas outside the @TypeboxGet decorator, so you can also infer types from them, using Static<typeof schema>.

import { Controller, Param, Query } from "@nestjs/common";
import { t } from "@jcwillox/typebox-x";
import { TypeboxGet } from "@jcwillox/typebox-x/nestjs";
import { Static } from "@sinclair/typebox";

type Query = Static<typeof QuerySchema>;
const QuerySchema = t.Object({
  limit: t.Optional(t.Integer({ default: 10 })),
});

type Response = Static<typeof ResponseSchema>;
const ResponseSchema = t.Object({
  message: t.String(),
});

@Controller()
export class AppController {
  @TypeboxGet(":my_id", {
    query: QuerySchema,
    params: { my_id: t.UUID() },
    response: ResponseSchema,
  })
  getHello(@Param("my_id") myId: string, @Query() query: Query): Response {
    return { message: "Hello World!" };
  }
}