Newer
Older
ServerGenerator / src / app.ts
import { Collection } from "./MySchema";
import { join } from "path";
import * as fs from "fs";
import { generateModel } from "./ModelGenerator";
import { generateDataAccess } from "./DataAccessGenerator";
import { generateOpenAPI } from "./OpenApiGenerator";
import { generateMiddlewares } from "./MiddlewareGenerator";

interface Options {
    typeScriptOutputFolder: string;
    openapiOutput: string;
}
export interface Description {
    collections: Collection[];
}
export interface FileWrite {
    location: string;
    content: string;
}

function describeTestOutput(): Description {
    return {
        collections: [
            {
                name: "Characters"
                , entities: {
                    name: "Character",
                    properties: [
                        { key: "name", type: "string", isNullable: false },
                        { key: "backstory", type: "string", isNullable: false }
                    ]
                }
            }
        ]
    }
}

/**
 * Central function, that contains all the (pure) logic.
 * @param options parameters for the generators
 * @param description The supplied data model description
 */
function generate(options: Options, description: Description): FileWrite[] {
    // generate model files
    const modelWrites = generateModel(description.collections);
    modelWrites.forEach(w => { w.location = join(options.typeScriptOutputFolder, w.location) });

    // generate data access files
    const dataAccessWrites = generateDataAccess(description.collections);
    dataAccessWrites.forEach(w => { w.location = join(options.typeScriptOutputFolder, w.location) });

    // generate openapi file
    const openapiDoc = generateOpenAPI(description);
    const openapiWrites: FileWrite = { location: options.openapiOutput, content: JSON.stringify(openapiDoc, null, "\t") };

    // generate middleware file
    const middlewareWrites = generateMiddlewares(description);
    middlewareWrites.forEach(w => { w.location = join(options.typeScriptOutputFolder, w.location) });

    // TODO create json schema file for the storage

    return [
        ...modelWrites,
        ...dataAccessWrites,
        ...middlewareWrites,
        openapiWrites,
    ];
}

function execute() {
    const example = describeTestOutput();
    const options: Options = {
        openapiOutput: join(__dirname, "..", "src", "TestOutput", "openapi.json"),
        typeScriptOutputFolder: join(__dirname, "..", "src", "TestOutput")
    };
    const writes = generate(options, example);
    for (const write of writes) {
        fs.writeFileSync(write.location, write.content);
        console.log(`Written file '${write.location}'`)
    }
}

execute();