Skip to content

Commit

Permalink
codegen: generate interfaces containing basic types for typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
endel committed May 3, 2020
1 parent 5c4f58a commit 3a34afb
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
26 changes: 21 additions & 5 deletions src/codegen/languages/ts.ts
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -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[]) {
Expand Down Expand Up @@ -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")}
}
`;
}
11 changes: 11 additions & 0 deletions test/Schema.ts
Original file line number Diff line number Diff line change
@@ -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
*/
Expand Down

0 comments on commit 3a34afb

Please sign in to comment.