From 3a34afb3ded4000fa84726776b381bef55225eae Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Sun, 3 May 2020 12:40:48 +0300 Subject: [PATCH] codegen: generate interfaces containing basic types for typescript --- package.json | 2 +- src/codegen/languages/ts.ts | 26 +++++++++++++++++++++----- test/Schema.ts | 11 +++++++++++ 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 1f42da7c..9c50630f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@colyseus/schema", - "version": "0.5.38", + "version": "0.5.39", "description": "Schema-based binary serializer / de-serializer.", "main": "lib/index.js", "types": "lib/index.d.ts", diff --git a/src/codegen/languages/ts.ts b/src/codegen/languages/ts.ts index d22b4069..01fd92ae 100644 --- a/src/codegen/languages/ts.ts +++ b/src/codegen/languages/ts.ts @@ -1,4 +1,4 @@ -import { Class, Property, File, getCommentHeader, getInheritanceTree, Context } from "../types"; +import { Class, Property, File, getCommentHeader, getInheritanceTree, Context, Interface } from "../types"; import { GenerateOptions } from "../api"; const typeMaps = { @@ -20,10 +20,16 @@ const typeMaps = { const distinct = (value, index, self) => self.indexOf(value) === index; export function generate (context: Context, options: GenerateOptions): File[] { - return context.classes.map(klass => ({ - name: klass.name + ".ts", - content: generateClass(klass, options.namespace, context.classes) - })); + return [ + ...context.classes.map(structure => ({ + name: structure.name + ".ts", + content: generateClass(structure, options.namespace, context.classes) + })), + ...context.interfaces.map(structure => ({ + name: structure.name + ".ts", + content: generateInterface(structure, options.namespace, context.classes), + })) + ]; } function generateClass(klass: Class, namespace: string, allClasses: Class[]) { @@ -100,3 +106,13 @@ function generateProperty(prop: Property) { return `@type(${typeArgs}) public ${prop.name}: ${langType}${(initializer) ? ` = ${initializer}` : ""};` } + + +function generateInterface(structure: Interface, namespace: string, allClasses: Class[]) { + return `${getCommentHeader()} + +export interface ${structure.name} { +${structure.properties.map(prop => ` ${prop.name}: ${prop.type};`).join("\n")} +} +`; +} \ No newline at end of file diff --git a/test/Schema.ts b/test/Schema.ts index 94ccb52b..d21d5005 100644 --- a/test/Schema.ts +++ b/test/Schema.ts @@ -1,5 +1,16 @@ import { Schema, type, ArraySchema, MapSchema, filter } from "../src"; +// interface IUser { +// name: string; +// } + +// interface ResponseMessage { +// user: IUser, +// str: string; +// n: number; +// shortcode: {[id: string]: string}; +// } + /** * No filters example */