use of cz.habarta.typescript.generator.TsType in project typescript-generator by vojtechhabarta.
the class Emitter method emitProperty.
private void emitProperty(TsPropertyModel property) {
emitComments(property.getComments());
emitDecorators(property.getDecorators());
final TsType tsType = property.getTsType();
final String staticString = property.modifiers.isStatic ? "static " : "";
final String readonlyString = property.modifiers.isReadonly ? "readonly " : "";
final String questionMark = tsType instanceof TsType.OptionalType ? "?" : "";
final String defaultString = property.getDefaultValue() != null ? " = " + property.getDefaultValue().format(settings) : "";
writeIndentedLine(staticString + readonlyString + quoteIfNeeded(property.getName(), settings) + questionMark + ": " + tsType.format(settings) + defaultString + ";");
}
use of cz.habarta.typescript.generator.TsType in project typescript-generator by vojtechhabarta.
the class RequiredPropertyConstructorExtension method getPredefinedValueForProperty.
private static Optional<TsExpression> getPredefinedValueForProperty(TsPropertyModel property, TsModel model) {
if (property.tsType instanceof TsType.UnionType) {
List<TsType> unionTypeElements = ((TsType.UnionType) property.tsType).types;
if (unionTypeElements.size() != 1) {
return Optional.empty();
}
TsType onlyElement = unionTypeElements.iterator().next();
if (!(onlyElement instanceof TsType.StringLiteralType)) {
return Optional.empty();
}
TsType.StringLiteralType onlyValue = (TsType.StringLiteralType) onlyElement;
TsStringLiteral expression = new TsStringLiteral(onlyValue.literal);
return Optional.of(expression);
}
if (property.tsType instanceof TsType.EnumReferenceType) {
Symbol symbol = ((TsType.EnumReferenceType) property.tsType).symbol;
Optional<TsEnumModel> enumModelOption = model.getOriginalStringEnums().stream().filter(candidate -> candidate.getName().getFullName().equals(symbol.getFullName())).findAny();
if (!enumModelOption.isPresent()) {
return Optional.empty();
}
TsEnumModel enumModel = enumModelOption.get();
if (enumModel.getMembers().size() != 1) {
return Optional.empty();
}
EnumMemberModel singleElement = enumModel.getMembers().iterator().next();
Object enumValue = singleElement.getEnumValue();
TsStringLiteral expression = new TsStringLiteral((String) enumValue);
return Optional.of(expression);
}
return Optional.empty();
}
use of cz.habarta.typescript.generator.TsType in project typescript-generator by vojtechhabarta.
the class ModelCompiler method javaToTypeScript.
public TsModel javaToTypeScript(Model model) {
final SymbolTable symbolTable = new SymbolTable(settings);
final List<Extension.TransformerDefinition> extensionTransformers = getExtensionTransformers();
model = applyExtensionModelTransformers(symbolTable, model, extensionTransformers);
TsModel tsModel = processModel(symbolTable, model);
tsModel = addCustomTypeAliases(symbolTable, tsModel);
tsModel = removeInheritedProperties(symbolTable, tsModel);
tsModel = addImplementedProperties(symbolTable, tsModel);
tsModel = sortPropertiesDeclarations(symbolTable, tsModel);
if (settings.generateConstructors) {
tsModel = addConstructors(symbolTable, tsModel);
}
// REST
if (settings.isGenerateRest()) {
final Symbol responseSymbol = createRestResponseType(symbolTable, tsModel);
final TsType optionsType = settings.restOptionsType != null ? new TsType.VerbatimType(settings.restOptionsType) : null;
final TsType.GenericVariableType optionsGenericVariable = settings.restOptionsTypeIsGeneric ? new TsType.GenericVariableType(settings.restOptionsType) : null;
final List<RestApplicationModel> restApplicationsWithInterface = model.getRestApplications().stream().filter(restApplication -> restApplication.getType().generateInterface.apply(settings)).collect(Collectors.toList());
final List<RestApplicationModel> restApplicationsWithClient = model.getRestApplications().stream().filter(restApplication -> restApplication.getType().generateClient.apply(settings)).collect(Collectors.toList());
if (!restApplicationsWithInterface.isEmpty()) {
createRestInterfaces(tsModel, symbolTable, restApplicationsWithInterface, responseSymbol, optionsGenericVariable, optionsType);
}
if (!restApplicationsWithClient.isEmpty()) {
createRestClients(tsModel, symbolTable, restApplicationsWithClient, responseSymbol, optionsGenericVariable, optionsType);
}
}
// dates
tsModel = transformMaps(symbolTable, tsModel);
// dates
tsModel = transformDates(symbolTable, tsModel);
// enums
tsModel = applyExtensionTransformers(symbolTable, model, tsModel, TransformationPhase.BeforeEnums, extensionTransformers);
tsModel = addEnumValuesToJavadoc(tsModel);
if (settings.enumMemberCasing != null && settings.enumMemberCasing != IdentifierCasing.keepOriginal) {
tsModel = transformEnumMembersCase(tsModel);
}
if (!settings.areDefaultStringEnumsOverriddenByExtension()) {
if (settings.mapEnum == null || settings.mapEnum == EnumMapping.asUnion || settings.mapEnum == EnumMapping.asInlineUnion) {
tsModel = transformEnumsToUnions(tsModel);
}
if (settings.mapEnum == EnumMapping.asInlineUnion) {
tsModel = inlineEnums(tsModel, symbolTable);
}
if (settings.mapEnum == EnumMapping.asNumberBasedEnum) {
tsModel = transformEnumsToNumberBasedEnum(tsModel);
}
}
// after enum transformations transform Maps with rest of the enums (not unions) used in keys
tsModel = transformNonStringEnumKeyMaps(symbolTable, tsModel);
// tagged unions
tsModel = createAndUseTaggedUnions(symbolTable, tsModel);
// nullable types and optional properties
tsModel = makeUndefinablePropertiesAndParametersOptional(symbolTable, tsModel);
tsModel = transformNullableTypes(symbolTable, tsModel);
tsModel = eliminateUndefinedFromOptionalPropertiesAndParameters(symbolTable, tsModel);
tsModel = transformOptionalProperties(symbolTable, tsModel);
tsModel = applyExtensionTransformers(symbolTable, model, tsModel, TransformationPhase.BeforeSymbolResolution, extensionTransformers);
symbolTable.resolveSymbolNames();
tsModel = sortTypeDeclarations(symbolTable, tsModel);
tsModel = applyExtensionTransformers(symbolTable, model, tsModel, TransformationPhase.AfterDeclarationSorting, extensionTransformers);
return tsModel;
}
use of cz.habarta.typescript.generator.TsType in project typescript-generator by vojtechhabarta.
the class ModelCompiler method processRestMethod.
private TsMethodModel processRestMethod(TsModel tsModel, SymbolTable symbolTable, String pathPrefix, Symbol responseSymbol, RestMethodModel method, boolean createLongName, TsType optionsType, boolean implement) {
final String path = Utils.joinPath(pathPrefix, method.getPath());
final PathTemplate pathTemplate = PathTemplate.parse(path);
final List<String> comments = Utils.concat(method.getComments(), Arrays.asList("HTTP " + method.getHttpMethod() + " /" + path, "Java method: " + method.getOriginClass().getName() + "." + method.getName()));
final List<TsParameterModel> parameters = new ArrayList<>();
// path params
for (MethodParameterModel parameter : method.getPathParams()) {
parameters.add(processParameter(symbolTable, method, parameter));
}
// entity param
if (method.getEntityParam() != null) {
parameters.add(processParameter(symbolTable, method, method.getEntityParam()));
}
// query params
final List<RestQueryParam> queryParams = method.getQueryParams();
final TsParameterModel queryParameter;
if (queryParams != null && !queryParams.isEmpty()) {
final List<TsType> types = new ArrayList<>();
if (queryParams.stream().anyMatch(param -> param instanceof RestQueryParam.Map)) {
types.add(new TsType.IndexedArrayType(TsType.String, TsType.Any));
} else {
final List<TsProperty> currentSingles = new ArrayList<>();
final Runnable flushSingles = () -> {
if (!currentSingles.isEmpty()) {
types.add(new TsType.ObjectType(currentSingles));
currentSingles.clear();
}
};
for (RestQueryParam restQueryParam : queryParams) {
if (restQueryParam instanceof RestQueryParam.Single) {
final MethodParameterModel queryParam = ((RestQueryParam.Single) restQueryParam).getQueryParam();
final TsType type = typeFromJava(symbolTable, queryParam.getType(), method.getName(), method.getOriginClass());
currentSingles.add(new TsProperty(queryParam.getName(), restQueryParam.required ? type : new TsType.OptionalType(type)));
}
if (restQueryParam instanceof RestQueryParam.Bean) {
final BeanModel queryBean = ((RestQueryParam.Bean) restQueryParam).getBean();
flushSingles.run();
final Symbol queryParamsSymbol = symbolTable.getSymbol(queryBean.getOrigin(), "QueryParams");
if (tsModel.getBean(queryParamsSymbol) == null) {
tsModel.getBeans().add(new TsBeanModel(queryBean.getOrigin(), TsBeanCategory.Data, /*isClass*/
false, queryParamsSymbol, /*typeParameters*/
null, /*parent*/
null, /*extendsList*/
null, /*implementsList*/
null, processProperties(symbolTable, null, queryBean), /*constructor*/
null, /*methods*/
null, /*comments*/
null));
}
types.add(new TsType.ReferenceType(queryParamsSymbol));
}
}
flushSingles.run();
}
boolean allQueryParamsOptional = queryParams.stream().noneMatch(queryParam -> queryParam.required);
TsType.IntersectionType queryParamType = new TsType.IntersectionType(types);
queryParameter = new TsParameterModel("queryParams", allQueryParamsOptional ? new TsType.OptionalType(queryParamType) : queryParamType);
parameters.add(queryParameter);
} else {
queryParameter = null;
}
if (optionsType != null) {
final TsParameterModel optionsParameter = new TsParameterModel("options", new TsType.OptionalType(optionsType));
parameters.add(optionsParameter);
}
// return type
final TsType returnType = typeFromJava(symbolTable, method.getReturnType(), method.getName(), method.getOriginClass());
final TsType wrappedReturnType = new TsType.GenericReferenceType(responseSymbol, returnType);
// method name
final String nameSuffix;
if (createLongName) {
nameSuffix = "$" + method.getHttpMethod() + "$" + pathTemplate.format("", "", false).replaceAll("/", "_").replaceAll("\\W", "");
} else {
nameSuffix = "";
}
// implementation
final List<TsStatement> body;
if (implement) {
body = new ArrayList<>();
body.add(new TsReturnStatement(new TsCallExpression(new TsMemberExpression(new TsMemberExpression(new TsThisExpression(), "httpClient"), "request"), new TsObjectLiteral(new TsPropertyDefinition("method", new TsStringLiteral(method.getHttpMethod())), new TsPropertyDefinition("url", processPathTemplate(pathTemplate)), queryParameter != null ? new TsPropertyDefinition("queryParams", new TsIdentifierReference("queryParams")) : null, method.getEntityParam() != null ? new TsPropertyDefinition("data", new TsIdentifierReference(method.getEntityParam().getName())) : null, optionsType != null ? new TsPropertyDefinition("options", new TsIdentifierReference("options")) : null))));
} else {
body = null;
}
// method
final TsMethodModel tsMethodModel = new TsMethodModel(method.getName() + nameSuffix, TsModifierFlags.None, null, parameters, wrappedReturnType, body, comments);
return tsMethodModel;
}
use of cz.habarta.typescript.generator.TsType in project typescript-generator by vojtechhabarta.
the class ModelCompiler method transformDates.
private TsModel transformDates(SymbolTable symbolTable, TsModel tsModel) {
final TsAliasModel dateAsNumber = new TsAliasModel(null, symbolTable.getSyntheticSymbol("DateAsNumber"), null, TsType.Number, null);
final TsAliasModel dateAsString = new TsAliasModel(null, symbolTable.getSyntheticSymbol("DateAsString"), null, TsType.String, null);
final LinkedHashSet<TsAliasModel> typeAliases = new LinkedHashSet<>(tsModel.getTypeAliases());
final TsModel model = transformBeanPropertyTypes(tsModel, new TsType.Transformer() {
@Override
public TsType transform(TsType.Context context, TsType type) {
if (type == TsType.Date) {
if (settings.mapDate == DateMapping.asNumber) {
typeAliases.add(dateAsNumber);
return new TsType.ReferenceType(dateAsNumber.getName());
}
if (settings.mapDate == DateMapping.asString) {
typeAliases.add(dateAsString);
return new TsType.ReferenceType(dateAsString.getName());
}
}
return type;
}
});
return model.withTypeAliases(new ArrayList<>(typeAliases));
}
Aggregations