data extraction from openapi defintion

This commit is contained in:
2021-11-19 12:39:46 +01:00
parent e616a7cb60
commit 590e9da904
4 changed files with 176 additions and 32 deletions

View File

@ -3,12 +3,13 @@ from Cheetah.Template import Template
import glob
import argparse
import os
import re
from yaml.loader import SafeLoader
from generateHelper import CsOperationNameConverter, OpenApiExtractRefType
parser = argparse.ArgumentParser(description="generate.py")
parser.add_argument('--api', '-a',
parser.add_argument('--apiDefinitionFile', '-a',
help='API definition file. Default: openapi.yaml in the current folder.',
required=False,
default='./openapi.yaml')
@ -20,35 +21,35 @@ with an additional .tmpl extension. Default: all template files recursively from
args = parser.parse_args()
with open(args.api) as schemaFile:
schema = yaml.load(schemaFile, Loader=SafeLoader)
with open(args.apiDefinitionFile) as apiDefinitionFile:
apiDefinition = yaml.load(apiDefinitionFile, Loader=SafeLoader)
schema["GENERATED_SQL_COMMENT"] = """
apiDefinition["GENERATED_SQL_COMMENT"] = """
-- ----------------------------------------
-- THIS FILE HAS BEEN GENERATED
-- DO NOT EDIT MANUALLY
-- ----------------------------------------
"""
schema["GENERATED_PYTHON_COMMENT"] = """
apiDefinition["GENERATED_PYTHON_COMMENT"] = """
# -----------------------------------------
# THIS FILE HAS BEEN GENERATED
# DO NOT EDIT MANUALLY
# -----------------------------------------
"""
schema["GENERATED_YAML_COMMENT"] = """
apiDefinition["GENERATED_YAML_COMMENT"] = """
# -----------------------------------------
# THIS FILE HAS BEEN GENERATED
# DO NOT EDIT MANUALLY
# -----------------------------------------
"""
schema["GENERATED_TS_COMMENT"] = """
apiDefinition["GENERATED_TS_COMMENT"] = """
// -----------------------------------------
// THIS FILE HAS BEEN GENERATED
// DO NOT EDIT MANUALLY
// -----------------------------------------
"""
schema["GENERATED_CS_COMMENT"] = """
apiDefinition["GENERATED_CS_COMMENT"] = """
// -----------------------------------------
// THIS FILE HAS BEEN GENERATED
// DO NOT EDIT MANUALLY
@ -56,34 +57,78 @@ schema["GENERATED_CS_COMMENT"] = """
"""
packageName = os.environ["PACKAGE_NAME"]
schema["env"] = { "packagename": packageName }
apiDefinition["env"] = { "packagename": packageName }
statementFinder = re.compile('STATEMENTBEGIN (.*) STATEMENTEND')
statementChecker = {
'get': re.compile('^select', re.IGNORECASE),
'put': re.compile('^update', re.IGNORECASE),
'delete': re.compile('^delete', re.IGNORECASE),
'post': re.compile('^insert', re.IGNORECASE)
}
operations = []
for path in schema['paths'].values():
for path in apiDefinition['paths'].values():
for (method, operation) in path.items():
#print(f"{method=}")
#print(f"{CsOperationNameConverter(operation['operationId'])=}")
# if 200 in
content = operation['responses'][200]['content']['application/json']['schema']
if ('type' in content) and (content['type'] == 'array'):
isList = True
typ = OpenApiExtractRefType(content['items']['$ref'])
resultType = OpenApiExtractRefType(content['items']['$ref'])
else:
isList = False
typ = OpenApiExtractRefType(content['$ref'])
resultType = OpenApiExtractRefType(content['$ref'])
#print(f"{content=}")
#print(f"{typ=}")
#print(f"{resultType=}")
description = None
statement = None
if 'description' in operation:
description = operation['description']
statementFinderResult = statementFinder.search(description)
if statementFinderResult:
statement = statementFinderResult.group(1)
if not statementChecker[method].match(statement):
raise Exception(f"Invalid statement {statement} for method {method}")
inputType = None
if 'requestBody' in operation:
inputType = OpenApiExtractRefType(operation['requestBody']['content']['application/json']['schema']['$ref'])
operations.append({
'description': description,
'method':method,
'func':CsOperationNameConverter(operation['operationId']),
'isList': isList,
'type': typ
'resultType': { 'apiName': resultType, 'csName': CsOperationNameConverter(resultType) } if resultType else {},
'allSelector': operation['operationId'].endswith('all'),
'byIdSelector': operation['operationId'].endswith('byid'),
'statement': statement,
'inputType': { 'apiName': inputType, 'csName': CsOperationNameConverter(inputType) } if inputType else {}
})
#print(f"{operations=}")
schema["operations"] = operations
print(f"{operations=}")
apiDefinition["operations"] = operations
types = {}
for (typeName, typeDefinition) in apiDefinition['components']['schemas'].items():
#print(f"{typeName=}")
typeProperties = []
for itemName in typeDefinition['properties']:
#print(f"{itemName=}")
typeProperties.append({
'sqlName': itemName,
'csName': itemName.capitalize()
})
types[typeName] = {
'sqlName': typeName,
'csName': typeName.capitalize(),
'properties': typeProperties
}
print(f"{types=}")
apiDefinition['types'] = types
for f in glob.glob(args.template, recursive=True):
print(f"process {f}")
tmpl = Template(file=f, searchList=[schema])
tmpl = Template(file=f, searchList=[apiDefinition])
with open(f[:-5], 'w') as outFile:
outFile.write(str(tmpl))