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

Add support for enums in Elm operations #2982

Merged
merged 1 commit into from
May 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -567,44 +567,56 @@ private String toOptionalValue(String value) {
return "(Just " + value + ")";
}

private Optional<String> paramToStringMapper(final String paramName, final CodegenProperty property) {
if (property.isEnum) {
return Optional.of(toVarName(paramName) + "ToString");
} else if (property.isString || property.isBinary || property.isByteArray) {
return Optional.empty();
} else if (property.isBoolean) {
return Optional.of("(\\val -> if val then \"true\" else \"false\")");
} else if (property.isDateTime) {
return Optional.of("DateTime.toString");
} else if (property.isDate) {
return Optional.of("DateOnly.toString");
} else if (property.isUuid) {
return Optional.of("Uuid.toString");
} else if (ElmVersion.ELM_018.equals(elmVersion)) {
return Optional.of("toString");
} else if (property.isInteger || property.isLong) {
return Optional.of("String.fromInt");
} else if (property.isFloat || property.isDouble) {
return Optional.of("String.fromFloat");
}
throw new RuntimeException("Parameter '" + paramName + "' cannot be converted to a string. Please report the issue.");
}

private CodegenProperty paramToProperty(final CodegenParameter parameter) {
final CodegenProperty property = new CodegenProperty();
property.isEnum = parameter.isEnum;
property.isString = parameter.isString;
property.isBinary = parameter.isBinary;
property.isByteArray = parameter.isByteArray;
property.isBoolean = parameter.isBoolean;
property.isDateTime = parameter.isDateTime;
property.isDate = parameter.isDate;
property.isUuid = parameter.isUuid;
property.isInteger = parameter.isInteger;
property.isLong = parameter.isLong;
property.isFloat = parameter.isFloat;
property.isDouble = parameter.isDouble;
return property;
}

private String paramToString(final String prefix, final CodegenParameter param, final boolean useMaybe, final String maybeMapResult) {
final String paramName = (ElmVersion.ELM_018.equals(elmVersion) ? "" : prefix + ".") + param.paramName;
if (!useMaybe) {
param.required = true;
}

String mapFn = null;
if (param.isString || param.isBinary || param.isByteArray) {
mapFn = "";
} else if (param.isBoolean) {
mapFn = "(\\val -> if val then \"true\" else \"false\")";
} else if (param.isDateTime) {
mapFn = "DateTime.toString";
} else if (param.isDate) {
mapFn = "DateOnly.toString";
} else if (param.isUuid) {
mapFn = "Uuid.toString";
} else if (ElmVersion.ELM_018.equals(elmVersion)) {
mapFn = "toString";
} else if (param.isInteger || param.isLong) {
mapFn = "String.fromInt";
} else if (param.isFloat || param.isDouble) {
mapFn = "String.fromFloat";
} else if (param.isListContainer) {
// TODO duplicate ALL types from parameter to property...
if (param.items.isString || param.items.isUuid || param.items.isBinary || param.items.isByteArray) {
mapFn = "String.join \",\"";
}
}
if (mapFn == null) {
throw new RuntimeException("Parameter '" + param.paramName + "' cannot be converted to a string. Please report the issue.");
}
final String mapFn = param.isListContainer
? "(String.join \",\"" + paramToStringMapper(param.paramName, param.items).map(mapper -> " << List.map " + mapper).orElse("") + ")"
: paramToStringMapper(param.paramName, paramToProperty(param)).orElse("");

if (param.isListContainer) {
if (!param.required) {
mapFn = "(" + mapFn + ")";
}
}
String mapResult = "";
if (maybeMapResult != null) {
if ("".equals(mapFn)) {
Expand Down
29 changes: 26 additions & 3 deletions modules/openapi-generator/src/main/resources/elm/api.mustache
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
{{>licenseInfo}}

module Request.{{classname}} exposing ({{#operations}}{{#operation}}{{^-first}}, {{/-first}}{{operationId}}{{/operation}}{{/operations}})
module Request.{{classname}} exposing ({{#operations}}{{#operation}}{{^-first}}, {{/-first}}{{operationId}}{{#allParams}}{{#isEnum}}, {{enumName}}(..){{/isEnum}}{{/allParams}}{{/operation}}{{/operations}})

{{>imports}}import Dict
import Http
import Json.Decode as Decode
import Url.Builder as Url


{{#operations}}
{{#operation}}
{{#allParams}}
{{#isEnum}}
type {{enumName}}
{{#allowableValues.enumVars}} {{#-first}}= {{/-first}}{{^-first}}| {{/-first}}{{name}}
{{/allowableValues.enumVars}}

{{paramName}}ToString : {{enumName}} -> String
{{paramName}}ToString value =
case value of
{{#allowableValues.enumVars}} {{name}} ->
{{{value}}}

{{/allowableValues.enumVars}}


{{/isEnum}}
{{/allParams}}
{{/operation}}
{{/operations}}


{{^enableCustomBasePaths}}basePath : String
basePath =
"{{basePath}}"
Expand All @@ -29,8 +52,8 @@ basePath =
{{#enableCustomBasePaths}} , basePath : String{{/enableCustomBasePaths}}
{{#enableHttpRequestTrackers}} , tracker : Maybe String{{/enableHttpRequestTrackers}}
{{#bodyParam}} , body : {{^required}}Maybe {{/required}}{{dataType}}{{/bodyParam}}
{{#pathParams}} , {{paramName}} : {{#isListContainer}}List {{/isListContainer}}{{dataType}}{{/pathParams}}
{{#queryParams}} , {{paramName}} : {{^required}}Maybe ({{/required}}{{#isListContainer}}List {{/isListContainer}}{{dataType}}{{^required}}){{/required}}{{/queryParams}}
{{#pathParams}} , {{paramName}} : {{#isListContainer}}List {{/isListContainer}}{{#datatypeWithEnum}}{{datatypeWithEnum}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{dataType}}{{/datatypeWithEnum}}{{/pathParams}}
{{#queryParams}} , {{paramName}} : {{^required}}Maybe ({{/required}}{{#isListContainer}}List {{/isListContainer}}{{#datatypeWithEnum}}{{datatypeWithEnum}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{dataType}}{{/datatypeWithEnum}}{{^required}}){{/required}}{{/queryParams}}
}
-> Cmd msg
{{operationId}} {{#headerParams.0}}headers {{/headerParams.0}}params =
Expand Down
25 changes: 22 additions & 3 deletions samples/client/petstore/elm/src/Request/Pet.elm
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
-}


module Request.Pet exposing (addPet, deletePet, findPetsByStatus, findPetsByTags, getPetById, updatePet, updatePetWithForm, uploadFile)
module Request.Pet exposing (Status(..), addPet, deletePet, findPetsByStatus, findPetsByTags, getPetById, updatePet, updatePetWithForm, uploadFile)

import Data.ApiResponse as ApiResponse exposing (ApiResponse)
import Data.Pet as Pet exposing (Pet)
Expand All @@ -20,6 +20,25 @@ import Json.Decode as Decode
import Url.Builder as Url


type Status
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@eriktim for Elm, is there any naming convention for enum?

In other languages, we may add a prefix/suffix (e.g. StatusEnum). This can help avoid naming conflicts with model names.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @wing328
You have point here but custom types (as these would be called in Elm) are so common I'd rather not suffix them with Enum. Your remark does remind me I should actually start using Data.Status for all imported types to avoid conflicts. I'll do that in another PR.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👌

= Available
| Pending
| Sold


statusToString : Status -> String
statusToString value =
case value of
Available ->
"available"

Pending ->
"pending"

Sold ->
"sold"


basePath : String
basePath =
"http://petstore.swagger.io/v2"
Expand Down Expand Up @@ -72,7 +91,7 @@ deletePet headers params =
-}
findPetsByStatus :
{ onSend : Result Http.Error (List Pet) -> msg
, status : List String
, status : List Status
}
-> Cmd msg
findPetsByStatus params =
Expand All @@ -82,7 +101,7 @@ findPetsByStatus params =
, url =
Url.crossOrigin basePath
[ "pet", "findByStatus" ]
(List.filterMap identity [ Just (Url.string "status" <| String.join "," params.status) ])
(List.filterMap identity [ Just (Url.string "status" <| (String.join "," << List.map statusToString) params.status) ])
, body = Http.emptyBody
, expect = Http.expectJson params.onSend (Decode.list Pet.decoder)
, timeout = Just 30000
Expand Down