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

compact-json-schema

v0.0.9

Published

Write less code without losing functionality. Full type support is also included in flight ✈️

Downloads

254

Readme

Compact JSON Schema

Write less code without losing functionality. Full type support is also included in flight ✈️

import { unfoldSchema } from 'compact-json-schema'

const schema = unfoldSchema({ name: "string", surname: "string?" })

Converts to

{
  type: "object",
  properties: {
    name: {
      type: "string"
    },
    surname: {
      type: "string"
    }
  },
  required: [ "name" ]
}

Using

There are 5 basic types, which are typed as a relevant string:

"string" | "boolean" | "number" | "integer" | "object" | "array"

Each type can also be undefined or nullable:

"string?"    // Undefined type
"string??"   // Nullable or undefined type

You have two ways to write the schema, full or shorthand:

const fullSchema = schema({ name: { type: "string" } })
const shortSchema = schema({ name: "string" })
// fullSchema is equal to shortSchema

The schema for objects can also be written in two ways:

const fullSchema = schema({ user: { type: "object", props: { name: "string" } } })
const shortSchema = schema({ user: { name: "string" } })
// fullSchema is equal to shortSchema

As you can guess, the full path also allows you to specify the necessary settings for validation, while the short path just uses the defaults.

Compact form for union types

You can use array of items for shorthand enum or oneOf types:

const body = schema({ name: [ "file" ], filename: "string" })
const body2 = schema({ name: [ "image" ], size: "number" })

const schema = unfoldSchema([ body, body2 ])

Schema converts to

{
  oneOf: [
    {
      type: "object",
      properties: { 
        name: { type: "string",  const: "file" },
        filename: { type: "string" }
      },
      required: [ "name", "filename" ]
    },
    {
      type: "object",
      properties: { 
        name: { type: "string",  const: "image" },
        size: { type: "number" }
      },
      required: [ "name", "size" ]
    }
  ]
}

What's up with the types?

Example fastify:

import { schema, sc, SchemaType, unfoldSchema } from 'compact-json-schema'

const params = schema({ itemId: "number" })
const body = schema({ name: "string", surname: "string?", features: { type: "array", items: "string" } })

fastify.post("/user/:userId", { schema: { params: unfoldSchema(params), body: unfoldSchema(body) } }, async (req) => {
  const { userId } = req.params as SchemaType<typeof params>      // typeof userId === "number"
  const userData = req.body as SchemaType<typeof body>  
  /*
    userData: {
      name: string
      surname: string | undefined
      features: Array<string>
    }
  */
})

About fastify integration

Since this library was intended more for use with the fastify framework, this package has a sc utility that allows you to abbreviate writing `{ schema: { params ... } } in your endpoints.

It works a little tricky, allowing you to write a minimum of code. It is based on the fact that in most cases schemas are needed for "params" and for "body". If you want to change a key, pass it as the last argument to sc.

It is applied as follows:

sc(schema({ userId: "number" })) -> { schema: { params: { type: "object", properties: { userId: { type: "number" } } } }}

sc(schema({ userId: "number" }, "query")) -> { schema: { querystring: { type: "object", properties: { userId: { type: "number" } } } }}

sc(schema({ userId: "number" }, { age: "number" })) -> { 
  schema: { 
    params: { type: "object", properties: { userId: { type: "number" } } },
    body: { type: "object", properties: { age: { type: "number" } } },
  }
}

sc(schema({ userId: "number" }, { age: "number" }), "query") -> { 
  schema: { 
    params: { type: "object", properties: { userId: { type: "number" } } },
    querystring: { type: "object", properties: { age: { type: "number" } } },
  }
}

Alternatively, you can pass an object to schema in which you specify the required parameters:

sc({ body: schema({ userId: "number" }) }) -> { schema: { body: { type: "object", properties: { userId: { type: "number" } } } }}

Fastify Type Provider

Fastify also gives you the option of specifying a TypeProvider so that the schema is applied automatically:

import { schema, sc, SchemaType, CompactJsonSchemaProvider } from 'compact-json-schema'

const params = schema({ itemId: "number" })
const body = schema({ name: "string", surname: "string?", features: { type: "array", items: "string" } })

const app = fastify().withTypeProvider<CompactJsonSchemaProvider>()

app.post("/user/:userId", sc({ params, body }), async (req) => {
  const { userId } = req.params         // typeof userId === "number"
  const userData = req.body
  /*
    userData: {
      name: string
      surname: string | undefined
      features: Array<string>
    }
  */
})

And there's a little bit of a hack if you want to propagate Schema Provider globally. To do this, add the code:

declare module 'fastify' {
  interface FastifyTypeProviderDefault {
    output: this['input'] extends SchemaItem? SchemaType<this['input']>: any,
  }
}