This commit is contained in:
Wolfgang Ludger Hottgenroth 2021-11-18 19:27:39 +01:00
commit e616a7cb60
Signed by: wn
GPG Key ID: 6C1E5E531E0D5D7F
7 changed files with 229 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
output/
__pycache__
regular.cs

1
ENV Normal file
View File

@ -0,0 +1 @@
PACKAGE_NAME=KROHNE.PdbApiService

90
generate.py Normal file
View File

@ -0,0 +1,90 @@
import yaml
from Cheetah.Template import Template
import glob
import argparse
import os
from yaml.loader import SafeLoader
from generateHelper import CsOperationNameConverter, OpenApiExtractRefType
parser = argparse.ArgumentParser(description="generate.py")
parser.add_argument('--api', '-a',
help='API definition file. Default: openapi.yaml in the current folder.',
required=False,
default='./openapi.yaml')
parser.add_argument('--template', '-t',
help="""Template file, templates files must be named as the final output file
with an additional .tmpl extension. Default: all template files recursively from the current folder.""",
required=False,
default="**/*.tmpl")
args = parser.parse_args()
with open(args.api) as schemaFile:
schema = yaml.load(schemaFile, Loader=SafeLoader)
schema["GENERATED_SQL_COMMENT"] = """
-- ----------------------------------------
-- THIS FILE HAS BEEN GENERATED
-- DO NOT EDIT MANUALLY
-- ----------------------------------------
"""
schema["GENERATED_PYTHON_COMMENT"] = """
# -----------------------------------------
# THIS FILE HAS BEEN GENERATED
# DO NOT EDIT MANUALLY
# -----------------------------------------
"""
schema["GENERATED_YAML_COMMENT"] = """
# -----------------------------------------
# THIS FILE HAS BEEN GENERATED
# DO NOT EDIT MANUALLY
# -----------------------------------------
"""
schema["GENERATED_TS_COMMENT"] = """
// -----------------------------------------
// THIS FILE HAS BEEN GENERATED
// DO NOT EDIT MANUALLY
// -----------------------------------------
"""
schema["GENERATED_CS_COMMENT"] = """
// -----------------------------------------
// THIS FILE HAS BEEN GENERATED
// DO NOT EDIT MANUALLY
// -----------------------------------------
"""
packageName = os.environ["PACKAGE_NAME"]
schema["env"] = { "packagename": packageName }
operations = []
for path in schema['paths'].values():
for (method, operation) in path.items():
#print(f"{method=}")
#print(f"{CsOperationNameConverter(operation['operationId'])=}")
content = operation['responses'][200]['content']['application/json']['schema']
if ('type' in content) and (content['type'] == 'array'):
isList = True
typ = OpenApiExtractRefType(content['items']['$ref'])
else:
isList = False
typ = OpenApiExtractRefType(content['$ref'])
#print(f"{content=}")
#print(f"{typ=}")
operations.append({
'method':method,
'func':CsOperationNameConverter(operation['operationId']),
'isList': isList,
'type': typ
})
#print(f"{operations=}")
schema["operations"] = operations
for f in glob.glob(args.template, recursive=True):
print(f"process {f}")
tmpl = Template(file=f, searchList=[schema])
with open(f[:-5], 'w') as outFile:
outFile.write(str(tmpl))

12
generateHelper.py Normal file
View File

@ -0,0 +1,12 @@
def JsNameConverter(i):
return ''.join([x.capitalize() for x in i.split('_')])
def CsOperationNameConverter(i):
return ''.join([x.capitalize() for x in i.split('.')])
def OpenApiExtractRefType(i):
e = i.split('/')
if e[:-1] == ['#', 'components', 'schemas']:
return e[-1]
else:
raise Exception("illegal ref type definition in response content")

58
openapi.yaml Normal file
View File

@ -0,0 +1,58 @@
openapi: 3.0.0
info:
title: PDB API
version: "0.0.2"
paths:
/pdb/v2/test1:
get:
tags: [ "Regular" ]
operationId: Regular.test1all
summary: Returns all entries from table test1
responses:
200:
description: Here are your test1 items
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Test1"
404:
description: No test1 items available
/pdb/v2/test1/{id}:
get:
tags: [ "Regular" ]
operationId: Regular.test2byid
summary: Returns one entry from table test1 by id
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
200:
description: Here is your test1 item
content:
application/json:
schema:
$ref: "#/components/schemas/Test1"
404:
description: No such test1 item available
components:
schemas:
Test1:
description: A test1 item
type: object
required:
- id
properties:
id:
type: integer
txt:
type: string
nr:
type: integer

31
readme.md Normal file
View File

@ -0,0 +1,31 @@
Details on OpenAPI spec: https://swagger.io/specification/
Generate server stubs:
docker run -it --rm -v $PWD:/work -u $UID openapitools/openapi-generator:cli-v5.1.0 \
generate -i /work/openapi.yaml -g aspnetcore -o /work/output \
--package-name $PACKAGE_NAME \
--additional-properties="packageVersion=0.0.1,aspnetCoreVersion=5.0,operationIsAsync=true,modelPropertyNaming=camelCase,\
generateBody=false,classModifier=abstract,operationModifier=abstract"
Configuration details for generator: https://openapi-generator.tech/docs/generators/aspnetcore/
Build and run the stub webservice:
docker run -it --rm -p 8080:8080 -v $PWD:/work \
devnexus.krohne.com:18079/repository/docker-krohne/dotnetcoresdkenv:5.0 \
bash
ATTENTION: This won't work with a set UID
Build:
sh build.sh
Run:
dotnet run -p src/KROHNE.ManufacturingCycleReportWebService/KROHNE.ManufacturingCycleReportWebService.csproj

34
regular.cs.tmpl Normal file
View File

@ -0,0 +1,34 @@
$GENERATED_CS_COMMENT
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.SwaggerGen;
using Newtonsoft.Json;
using ${env['packagename']}.Attributes;
using ${env['packagename']}.Models;
using ${env['packagename']}.Controllers;
namespace ${env['packagename']}.Implementations
{
public class RegularApiImplementation : RegularApiController
{
#for $operation in $operations
public override IActionResult ${operation['func']}() {
return new ObjectResult();
}
#end for
public override IActionResult CyclesStartCycle([FromBody]MCycle mCycle) {
return StatusCode(200, default(MCycle));
}
public override IActionResult CyclesStopCycle([FromBody]CycleId cycleId) {
throw new NotImplementedException();
}
}
}