Newer
Older
ServerGenerator / src / ModelGenerator.ts
import { FileWrite } from "./app";
import { Collection, Entity } from "./MySchema";

export function generateModel(collections: Collection[]): FileWrite[]
{
    return collections.map(generateModelFile);
}

function generateModelFile(collection: Collection): FileWrite
{
    const fileName = collection.name + "Model.ts";
    const definitions: string[] = [
        defineCollection(collection),
        defineEntity(collection.entities),
        definePayload(collection),
        defineFindFunction(collection),
    ];
    return {
        location: fileName,
        content: definitions.join("\n\n") + "\n",
    };
}

function defineCollection(collection: Collection): string {
    return `export interface ${collection.name} {
    items: ${collection.entities.name}[];
    nextId: number;
}`;
}

function defineEntity(entity: Entity): string
{
    const propDefinitions = entity.properties.map(p => `\t${p.key}: ${p.type};`).join("\n");
    return `export interface ${entity.name} {
    id: number;
${propDefinitions}
}`;
}

function definePayload(collection: Collection): string {
    const entity = collection.entities;
    return `export interface ${entity.name}Payload extends ${entity.name} {
    ref: string;
}

export function toPayload(item: ${entity.name}): ${entity.name}Payload {
    return {
        ...item,
        ref: \`/${collection.name.toLowerCase()}/\${item.id}\`,
    }
}`;
}

function defineFindFunction(collection: Collection): string {
    return `export function findSingle(collection: ${collection.name}, id: number) {
    return collection.items.find(n => n.id === id);
}`;
}