Skip to content

Usage with Runtypes

Hadrien Milano edited this page Dec 23, 2018 · 1 revision

Rest.ts works best with runtypes.
If you define your DTOs with runtypes, then rest-ts-express automatically takes care of validating the incoming data against the expected type. This helps you prevent bugs and vulnerabilities by not trusting user input and enforcing type checking at the boundary.

import * as rt from 'runtypes';
import { defineAPI, GET, POST } from 'rest-ts-core';

const Flower = rt.Record({
   name: rt.String,
   color: rt.String,
   id: rt.String
});

// Note how runtypes makes it less awkward to define union types
const FlowerIndexedAttribute = rt.Union('color', 'name');

export const flowerAPI = defineAPI({
    listFlowers: GET `/flowers`
        .query({
            'sortBy': FlowerIndexedAttribute,
            'filterBy': FlowerIndexedAttribute
        })
        .response(rt.Array(Flower))

    addFlower: POST `/flowers`
        // POST body data will be validated by the server. If it doesn't
        // conform to the expected type, a 400 error is returned.
        .body(Flower)
        .response(rt.Record({
            id: rt.String
        }))
});
Clone this wiki locally