Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

http-schemas

Package Overview
Dependencies
Maintainers
1
Versions
50
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

http-schemas

Strongly-typed HTTP schemas

  • 0.13.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
382
increased by32.64%
Maintainers
1
Weekly downloads
 
Created
Source

http-schemas

Use http-schemas to describe the 'shape' of a HTTP API in a way that is enforced both at build time and at runtime. In TypeScript source code, HTTP requests in the client code, and route handlers in the server code, will be statically checked against the schema, so usage errors are caught early. At runtime the schema is used to ensure that request and response payloads match the schema. Response payloads are also trimmed of any excess properties to prevent accidental information leaks. A schema may be shared by both client-side and server-side code, giving a single source of truth and ensuring the client and server always agree on their shared API.

http-schemas uses the rtti library for specifying and enforcing schemas.

Installation

npm install http-schemas

Example Shared Code (use in both client and server)

NOTE: The v0.10 API is deprecated but still supported.

import {createHttpSchema, t} from 'http-schemas';

// Declare the http schema to be used by both client and server
export const apiSchema = createHttpSchema({
    'POST /sum': {
        requestBody: t.array(t.number),
        responseBody: t.number,
    },
    'GET /greet/:name': {
        responseBody: t.string,
    },
});

Example Client-Side Code

import {createHttpClient} from 'http-schemas/client';
import {apiSchema} from '<path-to-shared-schema>';

// Create a strongly-typed http client. These are cheap to create - it's fine to have many of them.
const client = createHttpClient(apiSchema, {baseURL: '/api'});

// Some valid request examples
let res1 = client.post('/sum', {body: [1, 2]});                 // res1: Promise<number>
let res2 = client.get('/greet/:name', {params: {name: 'Bob'}}); // res2: Promise<string>

// Some invalid request examples
let res3 = client.get('/sum', {body: [1, 2]});                  // tsc build error & runtime error
let res4 = client.post('/sum', {body: 'foo'});                  // tsc build error & runtime error
let res5 = client.post('/blah');                                // tsc build error & runtime error

Example Server-Side Code

NOTE: The v0.10 API is deprecated but still supported.

import * as express from 'express';
import {createRequestHandler, decorateExpressRouter} from 'http-schemas/server';
import {apiSchema} from '<path-to-shared-schema>';

// Create a strongly-typed express router.
const apiRouter = decorateExpressRouter({schema: apiSchema});

// Create a normal express app and mount the strongly-typed router.
const app = express();
app.use(express.json()); // it's a normal express app; mount whatever middleware you want
app.use('/api', apiRouter); // `apiRouter` is just middleware; mount it wherever you want

// Add a request handler directly to the router
apiRouter.post('/sum', (req, res) => {
    let result = req.body.reduce((sum, n) => sum + n, 0);
    res.send(result);
});

// Declare a request handler separately, then add it to the router
const greetHandler = createRequestHandler(apiSchema, 'GET', '/greet/:name', (req, res) => {
    res.send(`Hello, ${req.params.name}!`);
});
apiRouter.get('/greet/:name', greetHandler);

// Some invalid route handler examples
apiRouter.post('/blah', (req, res) => {/*...*/});           // tsc build error & runtime error
apiRouter.post('/sum', (req, res) => { req.body.foo[0] });  // tsc build error & runtime error
apiRouter.post('/sum', (req, res) => { res.send('foo') });  // tsc build error & runtime error

app.listen(8000);

Full production-like webserver demo

The best way to see http-schemas in action is to see it in a real demonstration with documentation. Take a look at http-schemas-webserver-demo, read the docs, run it and play with it yourself.

FAQs

Package last updated on 07 Mar 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc