Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): generate typescript models from swagger/openapi project #447

Merged
merged 6 commits into from
Jul 1, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(core): update project generator to include codegen
  • Loading branch information
AgentEnder committed Jul 1, 2022
commit e6435142c72c8b371afdce50b615f1ce8f209519
12 changes: 12 additions & 0 deletions demo/apps/web-frontend/src/app/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ import styles from './app.module.scss';

import { WeatherForecast } from '@nx-dotnet/demo-libs-generated-webapi-types';

const x: WeatherForecast = {
date: 'TAOSNAPS',
forecaster: {
employer: { employees: [] },
},
summary: 'My weather forecast',
temperature: {
temperatureC: 12,
temperatureF: 53
}
};

export function App() {
return (
<>
Expand Down
2 changes: 1 addition & 1 deletion demo/apps/webapi/Controllers/WeatherForecastController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public IEnumerable<WeatherForecast> Get()
{
TemperatureC = Random.Shared.Next(-20, 55),
},
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
Summary = Random.Shared.Next(Summaries.Length)
})
.ToArray();
}
Expand Down
2 changes: 1 addition & 1 deletion demo/apps/webapi/NxDotnet.Test.Webapi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

<ImplicitUsings>enable</ImplicitUsings>

<OutputPath>../../dist/test/webapi</OutputPath>
<OutputPath>../../../dist/demo/apps/webapi</OutputPath>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion demo/apps/webapi/WeatherForecast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public class WeatherForecast

public Temperature? Temperature { get; set; }

public string? Summary { get; set; }
public int? Summary { get; set; }

public Person? Forecaster { get; set; }
}
Expand Down
16 changes: 16 additions & 0 deletions demo/libs/generated/webapi-swagger/project.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
{
"root": "demo/libs/generated/webapi-swagger",
"targets": {
"build": {
"executor": "@nrwl/workspace:run-commands",
"outputs": [],
"options": {
"commands": []
}
},
"codegen": {
"executor": "@nx-dotnet/core:openapi-codegen",
"options": {
"openapiJsonPath": "demo/libs/generated/webapi-swagger/swagger.json",
"outputProject": "demo-libs-generated-webapi-types"
}
}
},
"implicitDependencies": ["demo-apps-webapi"]
}
3 changes: 2 additions & 1 deletion demo/libs/generated/webapi-types/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@
}
}
},
"tags": []
"tags": [],
"implicitDependencies": ["demo-libs-generated-webapi-swagger"]
}
18 changes: 18 additions & 0 deletions nx.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@
{
"target": "prebuild",
"projects": "dependencies"
},
{
"target": "codegen",
"projects": "dependencies"
},
{
"target": "codegen",
"projects": "self"
}
],
"codegen": [
{
"target": "swagger",
"projects": "dependencies"
},
{
"target": "swagger",
"projects": "self"
}
]
},
Expand Down
5 changes: 5 additions & 0 deletions packages/core/executors.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
"implementation": "./src/executors/update-swagger/executor",
"schema": "./src/executors/update-swagger/schema.json",
"description": "Generates a swagger document for an API project"
},
"openapi-codegen": {
"implementation": "./src/executors/openapi-codegen/executor",
"schema": "./src/executors/openapi-codegen/schema.json",
"description": "openapi-codegen executor"
}
}
}
11 changes: 11 additions & 0 deletions packages/core/src/executors/openapi-codegen/executor.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { OpenapiCodegenExecutorSchema } from './schema';
import executor from './executor';

const options: OpenapiCodegenExecutorSchema = {};

describe('OpenapiCodegen Executor', () => {
it('can run', async () => {
const output = await executor(options);
expect(output.success).toBe(true);
});
});
32 changes: 32 additions & 0 deletions packages/core/src/executors/openapi-codegen/executor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { getPackageManagerCommand, logger, workspaceRoot } from '@nrwl/devkit';
import { exec } from 'child_process';
import { OpenapiCodegenExecutorSchema } from './schema';

export default function runExecutor(
options: OpenapiCodegenExecutorSchema,
): Promise<{ success: boolean }> {
return new Promise((resolve, reject) => {
exec(
`${
getPackageManagerCommand().exec
} nx g @nx-dotnet/core:swagger-typescript --openapiJsonPath="${
options.openapiJsonPath
}" --outputProject="${options.outputProject}"`,
{ cwd: workspaceRoot },
(error, stdout) => {
if (error) {
logger.error(error);
reject({
success: false,
error,
});
} else {
logger.info(stdout);
resolve({
success: true,
});
}
},
);
});
}
4 changes: 4 additions & 0 deletions packages/core/src/executors/openapi-codegen/schema.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface OpenapiCodegenExecutorSchema {
openapiJsonPath: string;
outputProject: string;
}
18 changes: 18 additions & 0 deletions packages/core/src/executors/openapi-codegen/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "http://json-schema.org/schema",
"cli": "nx",
"title": "OpenapiCodegen executor",
"description": "",
"type": "object",
"properties": {
"openapiJsonPath": {
"type": "string",
"description": "Path to OpenAPI spec file"
},
"outputProject": {
"type": "string",
"description": "Which project should hold the generated code?"
}
},
"required": ["outputProject", "openapiJsonPath"]
}
7 changes: 7 additions & 0 deletions packages/core/src/executors/update-swagger/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,20 @@ export default async function runExecutor(
nxProjectConfiguration,
);

console.log(nxProjectConfiguration, csProjFilePath);

const options = normalizeOptions(
schema,
nxProjectConfiguration,
csProjFilePath,
context.projectName as string,
);

console.log('BEFORE ENSURE DIR');
ensureDirSync(dirname(options.output));

if (!options.skipInstall) {
console.log('BEFORE ENSURE TOOL');
ensureSwaggerToolInstalled(
context,
dotnetClient,
Expand All @@ -112,7 +117,9 @@ function ensureSwaggerToolInstalled(
dotnetClient: DotNetClient,
version: string,
) {
console.log({ workspaceRoot });
const manifestPath = join(workspaceRoot, './.config/dotnet-tools.json');
console.log({ manifestPath });
const manifest = existsSync(manifestPath)
? readJsonFile(manifestPath)
: undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import {
addProjectConfiguration,
getWorkspaceLayout,
joinPathFragments,
ProjectConfiguration,
readProjectConfiguration,
Tree,
updateProjectConfiguration,
} from '@nrwl/devkit';
import { libraryGenerator } from '@nrwl/js/src/generators/library/library';
import { getSwaggerExecutorConfiguration } from '../../models/swagger-executor-configuration';
import { AddSwaggerJsonExecutorSchema } from './schema';

Expand All @@ -28,11 +30,37 @@ export default async function generateSwaggerSetup(
} else {
throw new Error('Either specify --output or --swagger-project');
}
} else {
if (options.codegenProject) {
project.targets.codegen = {
executor: '@nx-dotnet/core:openapi-codegen',
options: {
openapiJsonPath: options.output,
outputProject: options.codegenProject,
},
};
}
}
project.targets[options.target || 'swagger'] = {
...getSwaggerExecutorConfiguration(options.output),
};
updateProjectConfiguration(host, options.project, project);

if (options.codegenProject) {
await libraryGenerator(host, {
name: options.codegenProject,
directory: 'generated',
buildable: true,
});
const codegenProjectConfiguration = readProjectConfiguration(
host,
`generated-${options.codegenProject}`,
);
codegenProjectConfiguration.implicitDependencies ??= [];
codegenProjectConfiguration.implicitDependencies.push(
options.swaggerProject ? options.swaggerProject : options.project,
);
}
}

function swaggerProjectRoot(host: Tree, swaggerProject: string) {
Expand All @@ -45,10 +73,24 @@ function swaggerProjectRoot(host: Tree, swaggerProject: string) {

function generateShellProject(
host: Tree,
options: { project: string; swaggerProject: string },
options: { project: string; swaggerProject: string; codegenProject?: string },
) {
const targets: ProjectConfiguration['targets'] = {};
if (options.codegenProject) {
targets.codegen = {
executor: '@nx-dotnet/core:openapi-codegen',
options: {
openapiJsonPath: `${swaggerProjectRoot(
host,
options.swaggerProject,
)}/swagger.json`,
outputProject: `generated-${options.codegenProject}`,
},
};
}
addProjectConfiguration(host, options.swaggerProject, {
root: swaggerProjectRoot(host, options.swaggerProject),
targets,
implicitDependencies: [options.project],
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export type AddSwaggerJsonExecutorSchema = {
startupAssembly?: string;
target?: string;
swaggerProject?: string;
codegenProject?: string;
};
4 changes: 4 additions & 0 deletions packages/core/src/generators/add-swagger-target/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@
"type": "string",
"description": "What should the project created to hold the swagger files be called?"
},
"codegenProject": {
"type": "string",
"description": "What project should hold the generated types? If null, no codegen target will be added."
},
"target": {
"type": "string",
"description": "What should the project be called?",
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/generators/utils/generate-project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ export async function GenerateProject(
generateSwaggerSetup(host, {
project: normalizedOptions.projectName,
swaggerProject: `${normalizedOptions.projectName}-swagger`,
codegenProject: `${normalizedOptions.projectName}-types`,
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ export function buildStartupAssemblyPath(
if (!existsSync(outputDirectory)) {
execSync(`${getPackageManagerCommand().exec} nx ${target} ${projectName}`);
}
console.log('before dll name');
const dllName = basename(csProjFilePath).replace(
/(?:\.csproj|\.vbproj|\.fsproj)$/,
'.dll',
);
console.log('dll name', dllName, outputDirectory);
return joinPathFragments(
outputDirectory,
sync(`**/${dllName}`, { cwd: outputDirectory })[0],
Expand Down
Loading