UNPKG

@jsonjoy.com/json-type

Version:

High-performance JSON Pointer implementation

83 lines (82 loc) 2.39 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TypeRouter = void 0; const TypeSystem_1 = require("./TypeSystem"); const toText_1 = require("../typescript/toText"); class TypeRouter { constructor(options) { this.system = options.system; this.t = this.system.t; this.routes = options.routes; // this.system.importTypes(this.routes); } merge(router) { return new TypeRouter({ system: this.system, routes: { ...this.routes, ...router.routes, }, }); } extend(routes) { const router = new TypeRouter({ system: this.system, routes: routes(this) }); return this.merge(router); } fn(name, type) { this.routes[name] = type; return this; } fn$(name, type) { this.routes[name] = type; return this; } toTypeScriptAst() { const node = { node: 'TypeLiteral', members: [], }; for (const [name, type] of Object.entries(this.routes)) { const schema = type.getSchema(); const property = { node: 'PropertySignature', name, type: type.toTypeScriptAst(), }; if (schema.title) property.comment = schema.title; node.members.push(property); } return node; } toTypeScriptModuleAst() { const node = { node: 'ModuleDeclaration', name: 'Router', export: true, statements: [ { node: 'TypeAliasDeclaration', name: 'Routes', type: this.toTypeScriptAst(), export: true, }, ], }; for (const alias of this.system.aliases.values()) node.statements.push({ ...alias.toTypeScriptAst(), export: true }); return node; } toTypeScript() { return (0, toText_1.toText)(this.toTypeScriptModuleAst()); } } exports.TypeRouter = TypeRouter; TypeRouter.create = (routes) => { const system = new TypeSystem_1.TypeSystem(); const router = new TypeRouter({ system, routes: {}, }); return routes ? router.extend(routes) : router; };