Skip to content

Commit

Permalink
feat(cli): add fastify platform option
Browse files Browse the repository at this point in the history
  • Loading branch information
Romakita committed Feb 2, 2025
1 parent 7d0818f commit 1ea6abb
Show file tree
Hide file tree
Showing 28 changed files with 353 additions and 167 deletions.
30 changes: 30 additions & 0 deletions packages/cli-core/src/services/Renderer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,36 @@ describe("Renderer", () => {
expect(Consolidate.handlebars).toHaveBeenCalledWith("/tmpl/init/src/controllers/pages/IndexController.ts.hbs", {});
expect(FakeCliFs.getKeys()).toEqual(["/home/src/pages", "/home/src/pages/index.controller.ts"]);
});
it("should render a file from given option (with replaces, output, baseDir)", async () => {
const service = new RootRendererService();

const props = {
path: "/generate/src/server/express/server.hbs",
basename: "Server.ts",
replaces: ["server/express"]
};

const data = {};

const options = {
baseDir: "/generate",
...props
};

configuration().set("project", {
rootDir: "/home",
srcDir: "/src"
});

service.templateDir = "/tmpl";

// @ts-ignore
Consolidate.handlebars.mockReturnValue("content");

await service.render(props.path, data, options);

expect(FakeCliFs.getKeys()).toEqual(["/home/src", "/home/src/Server.ts"]);
});
});
describe("loadPartials()", () => {
it("should load partials", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,16 @@ export class GenerateHttpClientCmd implements CommandProvider {
return platform.PlatformKoa;
}
} catch (er) {}
throw new Error("Unsupported platform. Please use Express.js or Koa.js platform.");

try {
// @ts-ignore
const platform = await import("@tsed/platform-fastify");

if (platform) {
return platform.PlatformFastify;
}
} catch (er) {}
throw new Error("Unsupported platform. Please use Express.js, Koa.js or Fastify.js platform.");
}

private async generate($ctx: GenerateHttpClientCtx) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ export class GenerateSwaggerCmd implements CommandProvider {
}
} catch (er) {}

try {
// @ts-ignore
const platform = await import("@tsed/platform-fastify");

if (platform) {
return platform.PlatformFastify;
}
} catch (er) {}

throw new Error("Unsupported platform. Please use Express.js or Koa.js platform.");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,6 @@ import {InteractionsController} from "./controllers/oidc/InteractionsController.
acceptMimes: ["application/json"],
httpPort: process.env.PORT || 8083,
httpsPort: false, // CHANGE
disableComponentsScan: true,
ajv: {
returnsCoercedValues: true
},
mount: {
"/rest": [
...Object.values(rest)
Expand All @@ -103,10 +99,7 @@ import {InteractionsController} from "./controllers/oidc/InteractionsController.
extensions: {
ejs: "ejs"
}
},
exclude: [
"**/*.spec.ts"
]
}
})
export class Server {
protected app = application();
Expand Down Expand Up @@ -191,10 +184,6 @@ import {InteractionsController} from "./controllers/oidc/InteractionsController.
acceptMimes: ["application/json"],
httpPort: process.env.PORT || 8083,
httpsPort: false, // CHANGE
disableComponentsScan: true,
ajv: {
returnsCoercedValues: true
},
mount: {
"/rest": [
...Object.values(rest)
Expand Down Expand Up @@ -223,10 +212,7 @@ import {InteractionsController} from "./controllers/oidc/InteractionsController.
extensions: {
ejs: "ejs"
}
},
exclude: [
"**/*.spec.ts"
]
}
})
export class Server {
protected app = application();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ import * as rest from "./controllers/rest/index.js";
acceptMimes: ["application/json"],
httpPort: process.env.PORT || 8083,
httpsPort: false, // CHANGE
disableComponentsScan: true,
ajv: {
returnsCoercedValues: true
},
mount: {
"/rest": [
...Object.values(rest)
Expand All @@ -40,10 +36,7 @@ import * as rest from "./controllers/rest/index.js";
extensions: {
ejs: "ejs"
}
},
exclude: [
"**/*.spec.ts"
]
}
})
export class Server {
protected app = application();
Expand All @@ -60,6 +53,9 @@ const pkg = JSON.parse(readFileSync("./package.json", {encoding: "utf8"}));
export const config: Partial<TsED.Configuration> = {
version: pkg.version,
envs,
ajv: {
returnsCoercedValues: true
},
logger: loggerConfig,
graphql: {
default: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@ import * as rest from "./controllers/rest/index.js";
acceptMimes: ["application/json"],
httpPort: process.env.PORT || 8083,
httpsPort: false, // CHANGE
disableComponentsScan: true,
ajv: {
returnsCoercedValues: true
},
mount: {
"/rest": [
...Object.values(rest)
Expand All @@ -37,10 +33,7 @@ import * as rest from "./controllers/rest/index.js";
extensions: {
ejs: "ejs"
}
},
exclude: [
"**/*.spec.ts"
]
}
})
export class Server {
protected app = application();
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/bin/tsed.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import {register} from "node:module";
import {join} from "node:path";
import {fileURLToPath, pathToFileURL} from "node:url";
import {pathToFileURL} from "node:url";

const EXT = process.env.CLI_MODE === "ts" ? "ts" : "js";

Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/commands/generate/GenerateCmd.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ describe("GenerateCmd", () => {
symbolPathBasename: "Test",
type: "controller",
express: false,
fastify: false,
koa: false,
platformSymbol: undefined,
barrels: '["./src/controllers/rest"]',
Expand Down Expand Up @@ -168,6 +169,7 @@ describe("GenerateCmd", () => {
type: "controller",
express: false,
koa: false,
fastify: false,
platformSymbol: undefined,
barrels: '["./src/controllers/rest"]',
imports: [
Expand Down
40 changes: 22 additions & 18 deletions packages/cli/src/commands/generate/GenerateCmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,22 @@ import {normalizePath} from "@tsed/normalize-path";
import {kebabCase, pascalCase} from "change-case";
import {globbySync} from "globby";

import type {PlatformType} from "../../interfaces/index.js";
import {ProjectConvention} from "../../interfaces/ProjectConvention.js";
import {ClassNamePipe} from "../../pipes/ClassNamePipe.js";
import {OutputFilePathPipe} from "../../pipes/OutputFilePathPipe.js";
import {RoutePipe} from "../../pipes/RoutePipe.js";
import {ProvidersInfoService} from "../../services/ProvidersInfoService.js";
import {fillImports} from "../../utils/fillImports.js";
import {getFrameworksPrompt} from "../init/prompts/getFeaturesPrompt.js";
import {PROVIDER_TYPES} from "./ProviderTypes.js";

export interface GenerateCmdContext extends CliDefaultOptions {
type: string;
name: string;
route: string;
directory: string;
platform: string;
platform: PlatformType;
templateType: string;
middlewarePosition: "before" | "after";
symbolName: string;
Expand Down Expand Up @@ -132,24 +134,13 @@ export class GenerateCmd implements CommandProvider {
when: !initialOptions.name
},
{
...getFrameworksPrompt(),
message: "Which platform?",
type: "list",
name: "platform",
when(state: any) {
return ["server"].includes(state.type || initialOptions.type);
},
choices: [
{
name: "Express.js",
checked: true,
value: "express"
},
{
name: "Koa.js",
checked: false,
value: "koa"
}
]
}
},
{
type: "input",
Expand Down Expand Up @@ -234,15 +225,28 @@ export class GenerateCmd implements CommandProvider {
if (this.providersList.isMyProvider(ctx.type, GenerateCmd)) {
const type = [ctx.type, ctx.templateType].filter(Boolean).join(".");

const template = `generate/${type}.hbs`;
let template = `generate/${type}.hbs`;

if (ctx.type === "server") {
template = `generate/server/${ctx.platform}/server.hbs`;
}

return [
{
title: `Generate ${ctx.type} file to '${symbolPath}.ts'`,
task: () =>
this.srcRenderService.render(template, ctx, {
task: () => {
if (ctx.type === "server") {
return this.srcRenderService.render(template, ctx, {
baseDir: "generate",
basename: `${symbolPath}.ts`,
replaces: [`server/${ctx.platform}`]
});
}

return this.srcRenderService.render(template, ctx, {
output: `${symbolPath}.ts`
})
});
}
},
{
title: `Update bin/index`,
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/init/InitCmd.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe("InitCmd", () => {
platform: "wrong"
} as any);
});
expect(result?.message).toEqual("Invalid selected platform: wrong. Possible values: express, koa.");
expect(result?.message).toEqual("Invalid selected platform: wrong. Possible values: express, koa, fastify.");
});

it("should throw error (architecture)", async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/init/InitCmd.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ import {getFeaturesPrompt} from "./prompts/getFeaturesPrompt.js";
"-p, --platform <platform>": {
type: String,
defaultValue: PlatformType.EXPRESS,
description: "Set the default platform for Ts.ED (express or koa)"
description: "Set the default platform for Ts.ED (express, koa or fastify)"
},
"--features <features...>": {
type: Array,
Expand Down
20 changes: 13 additions & 7 deletions packages/cli/src/commands/init/config/FeaturesPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,16 @@ export enum FeatureType {
export const FeaturesMap: Record<string, Feature> = {
[PlatformType.EXPRESS]: {
name: "Express.js",
checked: (options: any) => options.platform !== PlatformType.KOA
checked: (options: any) => options.platform === PlatformType.EXPRESS || !options.platform
},
[PlatformType.KOA]: {
name: "Koa.js",
checked: (options: any) => options.platform === PlatformType.KOA
},
[PlatformType.FASTIFY]: {
name: "Fastify.js (beta)",
checked: (options: any) => options.platform === PlatformType.FASTIFY
},
[FeatureType.GRAPHQL]: {
name: "TypeGraphQL",
dependencies: {
Expand Down Expand Up @@ -297,13 +301,15 @@ export const FeaturesMap: Record<string, Feature> = {
}
};

export const FrameworksPrompt = {
message: "Choose the target Framework:",
type: "list",
name: "platform",
choices: [PlatformType.EXPRESS, PlatformType.KOA, PlatformType.FASTIFY]
};

export const FeaturesPrompt = (availableRuntimes: string[], availablePackageManagers: string[]) => [
{
message: "Choose the target Framework:",
type: "list",
name: "platform",
choices: [PlatformType.EXPRESS, PlatformType.KOA]
},
FrameworksPrompt,
{
message: "Choose the architecture for your project:",
type: "list",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ describe("getFeaturesPrompt", () => {
"name": "Koa.js",
"value": "koa",
},
{
"checked": false,
"name": "Fastify.js (beta)",
"value": "fastify",
},
],
"message": "Choose the target Framework:",
"name": "platform",
Expand Down
17 changes: 15 additions & 2 deletions packages/cli/src/commands/init/prompts/getFeaturesPrompt.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {cleanObject, isFunction} from "@tsed/core";

import {FeaturesMap, FeaturesPrompt} from "../config/FeaturesPrompt.js";
import {FeaturesMap, FeaturesPrompt, FrameworksPrompt} from "../config/FeaturesPrompt.js";
import type {InitOptions} from "../interfaces/InitOptions.js";

function mapChoices(item: any, options: Partial<InitOptions>) {
Expand All @@ -16,10 +16,23 @@ function mapChoices(item: any, options: Partial<InitOptions>) {
}

export function getFeaturesPrompt(runtimes: string[], availablePackageManagers: string[], options: Partial<InitOptions>) {
return FeaturesPrompt(runtimes, availablePackageManagers).map((item: any) => {
return FeaturesPrompt(runtimes, availablePackageManagers).map((item: any, index) => {
return cleanObject({
...item,
choices: item.choices?.length ? mapChoices(item, options) : undefined
});
});
}

export function getFrameworksPrompt() {
return {
...FrameworksPrompt,
choices: FrameworksPrompt.choices.map((choice: string, index) => {
return cleanObject({
...FeaturesMap[choice],
checked: index === 0,
value: choice
});
})
};
}
2 changes: 1 addition & 1 deletion packages/cli/src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const {path, packageJson} = readPackageUpSync({

export const PKG = packageJson;
export const MINIMAL_TSED_VERSION = "8";
export const DEFAULT_TSED_TAGS = "latest";
export const DEFAULT_TSED_TAGS = "beta";
export const IGNORE_VERSIONS = ["6.0.0"];
export const IGNORE_TAGS: false | RegExp = false; // /alpha|beta/
export const TEMPLATE_DIR = join(dirname(path), "templates");
Loading

0 comments on commit 1ea6abb

Please sign in to comment.