https://github.com/dzucconi/glass-cube
Runtime type generation
https://github.com/dzucconi/glass-cube
codegen runtime-typechecking runtime-typing runtypes
Last synced: 2 months ago
JSON representation
Runtime type generation
- Host: GitHub
- URL: https://github.com/dzucconi/glass-cube
- Owner: dzucconi
- Created: 2020-05-19T21:58:26.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2021-05-29T16:13:39.000Z (almost 5 years ago)
- Last Synced: 2025-10-20T17:50:08.319Z (6 months ago)
- Topics: codegen, runtime-typechecking, runtime-typing, runtypes
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/glass-cube
- Size: 223 KB
- Stars: 2
- Watchers: 0
- Forks: 0
- Open Issues: 7
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# glass-cube
Generate [Runtypes](https://github.com/pelotom/runtypes) from JSON responses, merge Runtypes, and generate code from Runtypes. Use it to generate a comprehensive Runtype for a given API endpoint by reducing Runtypes from disparate API responses.
## Getting Started
```sh
yarn add glass-cube --dev
```
-----
```ts
import { jsonToRuntype, runtypeToCode, mergeRuntypes, writeRuntype } from "glass-cube";
const responseA = {
foo: "bar",
bar: 1,
baz: null,
qux: { foo: [1, 2, 3, "four"], nested: true },
};
const RuntypeA = jsonToRuntype(responseA);
RuntypeA.check(responseA); // ✅ => responseA
RuntypeA.check({ foo: "bar" }); // ❌ => Uncaught ValidationError: Expected number, but was undefined
runtypeToCode(RuntypeA); // => 'R.Record({ "foo": R.String, "bar": R.Number, "baz": R.Null, "qux": R.Record({ "foo": R.Array(R.Number.Or(R.String)), "nested": R.Boolean }) })'
const responseB = {
foo: "baz",
bar: 2,
baz: "foo",
qux: null,
};
const RuntypeB = jsonToRuntype(responseB);
const RuntypeC = mergeRuntypes(RuntypeA, RuntypeB);
RuntypeB.check(responseB); // ✅
RuntypeB.check(responseA); // ❌
RuntypeC.check(responseA); // ✅
RuntypeC.check(responseB); // ✅
runtypeToCode(RuntypeC); // => 'R.Record({ "foo": R.String, "bar": R.Number, "baz": R.String.Or(R.Null), "qux": R.Null.Or(R.Record({ "foo": R.Array(R.Number.Or(R.String)), "nested": R.Boolean })) })'
writeRuntype({ object: RuntypeC, name: 'Example', path: '.' }) // => Wrote: ./Example.ts
/**
* Example.ts:
*
* import * as R from "runtypes";
*
* export const Example = R.Record({
* foo: R.String,
* bar: R.Number,
* baz: R.String.Or(R.Null),
* qux: R.Null.Or(
* R.Record({ foo: R.Array(R.Number.Or(R.String)), nested: R.Boolean })
* ),
* });
*
* export type Example = R.Static;
*/
```