Skip to content

Commit

Permalink
Merge pull request #322 from Yachef/multipart
Browse files Browse the repository at this point in the history
[API] Handle multipart
  • Loading branch information
gideruette authored Oct 31, 2023
2 parents af144de + a590835 commit 3ea0ac9
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 35 deletions.
2 changes: 1 addition & 1 deletion TopModel.Core/EndpointExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public static class EndpointExtensions
{
public static IProperty? GetBodyParam(this Endpoint endpoint)
{
var bodyParams = endpoint.Params.Where(param => param is CompositionProperty || param is IFieldProperty { Domain.BodyParam: true });
var bodyParams = endpoint.Params.Where(param => param is CompositionProperty || param is IFieldProperty { Domain.BodyParam: true }).Where(p => p.Domain?.MediaType != "multipart/form-data");
return bodyParams.Count() > 1
? throw new ModelException(endpoint, $"L'endpoint '{endpoint.Name}' doit avoir une seule propriété dans le body. Propriétés trouvées : {string.Join(", ", bodyParams)}")
: bodyParams.SingleOrDefault();
Expand Down
53 changes: 47 additions & 6 deletions TopModel.Generator.Javascript/AngularApiClientGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,23 @@ protected override void HandleFile(string filePath, string fileName, string tag,
WriteEndpoint(endpoint, fw);
}

var hasForm = endpoints.Any(endpoint => endpoint.Params.Any(p => p is IFieldProperty fp && Config.GetType(fp).Contains("File")));
if (hasForm)
{
fw.WriteLine(@"
private fillFormData(data: any, formData: FormData, prefix = """") {
if (Array.isArray(data)) {
data.forEach((item, i) => this.fillFormData(item, formData, prefix + (typeof item === ""object"" && !(item instanceof File) ? `[${i}]` : """")));
} else if (typeof data === ""object"" && !(data instanceof File)) {
for (const key in data) {
this.fillFormData(data[key], formData, (prefix ? `${prefix}.` : """") + key);
}
} else {
formData.append(prefix, data);
}
}");
}

fw.WriteLine("}");
}

Expand Down Expand Up @@ -130,14 +147,38 @@ private void WriteEndpoint(Endpoint endpoint, FileWriter fw)

if (hasForm)
{
fw.WriteLine(2, "let formData: FormData = new FormData();");
fw.WriteLine(2, "if (file) {");
fw.WriteLine(3, "formData.append('file', file);");
fw.WriteLine(2, "}");
fw.WriteLine(" const formData = new FormData();");
fw.WriteLine(" this.fillFormData(");
fw.WriteLine(" {");
foreach (var param in endpoint.Params)
{
if (param is IFieldProperty)
{
fw.Write($@" {param.GetParamName()}");
}
else
{
fw.Write($@" ...{param.GetParamName()}");
}

if (endpoint.Params.IndexOf(param) < endpoint.Params.Count - 1)
{
fw.WriteLine(",");
}
else
{
fw.WriteLine();
}
}

fw.WriteLine(" },");
fw.WriteLine(" formData");
fw.WriteLine(" );");

fw.WriteLine(2, $@"return this.http.{endpoint.Method.ToLower()}<{returnType}>(`/{endpoint.FullRoute}`, formData);");
fw.WriteLine(1, "}");
fw.WriteLine("}");
return;
}
}

if (endpoint.GetQueryParams().Any())
{
Expand Down
50 changes: 22 additions & 28 deletions TopModel.Generator.Jpa/SpringServerApiGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,9 @@ private IEnumerable<string> GetTypeImports(IEnumerable<Endpoint> endpoints, stri
.SelectMany(c => c.GetKindImports(Config, tag)));
}

private void WriteEndPointMethod(JavaWriter fw, Endpoint endpoint, string tag)
private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag)
{
fw.WriteLine();
fw.WriteDocStart(1, endpoint.Description);

foreach (var param in endpoint.Params)
Expand All @@ -98,7 +99,6 @@ private void WriteEndPointMethod(JavaWriter fw, Endpoint endpoint, string tag)
returnType = Config.GetType(endpoint.Returns);
}

var hasForm = endpoint.Params.Any(p => Config.GetType(p) == "MultipartFile");
{
var produces = string.Empty;
if (endpoint.Returns != null && endpoint.Returns is IFieldProperty fp && fp.Domain.MediaType != null)
Expand All @@ -107,7 +107,6 @@ private void WriteEndPointMethod(JavaWriter fw, Endpoint endpoint, string tag)
}

var consumes = string.Empty;

if (endpoint.Params.Any(p => p is IFieldProperty fdp && fdp.Domain.MediaType != null))
{
consumes = @$", consumes = {{ {string.Join(", ", endpoint.Params.Where(p => p is IFieldProperty fdp && fdp.Domain.MediaType != null).Select(p => $@"""{((IFieldProperty)p).Domain.MediaType}"""))} }}";
Expand Down Expand Up @@ -143,39 +142,34 @@ private void WriteEndPointMethod(JavaWriter fw, Endpoint endpoint, string tag)
}

var bodyParam = endpoint.GetBodyParam();
var formParam = endpoint.Params.FirstOrDefault(p => p.Domain?.MediaType == "multipart/form-data", null);

Check warning on line 145 in TopModel.Generator.Jpa/SpringServerApiGenerator.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
if (bodyParam != null)
{
var ann = string.Empty;
ann += @$"@RequestBody @Valid ";
fw.AddImport("org.springframework.web.bind.annotation.RequestBody");
fw.AddImport(Config.PersistenceMode.ToString().ToLower() + ".validation.Valid");
if (formParam != null)
{
if (formParam != bodyParam)
{
ann += @$"@ModelAttribute ";
fw.AddImport("org.springframework.web.bind.annotation.ModelAttribute");
}
else
{
ann += @$"@RequestPart(value = ""{bodyParam.GetParamName()}"", required = {(bodyParam is not IFieldProperty fp || fp.Required).ToString().ToFirstLower()}) ";
fw.AddImport("org.springframework.web.bind.annotation.RequestPart");
}
}
else
{
ann += @$"@RequestBody @Valid ";
fw.AddImport("org.springframework.web.bind.annotation.RequestBody");
fw.AddImport(Config.PersistenceMode.ToString().ToLower() + ".validation.Valid");
}

methodParams.Add($"{ann}{Config.GetType(bodyParam)} {bodyParam.GetParamName()}");
}

fw.WriteLine(1, $"{returnType} {endpoint.NameCamel}({string.Join(", ", methodParams)});");

var methodCallParams = new List<string>();
foreach (var param in endpoint.GetRouteParams().OfType<IFieldProperty>())
{
methodCallParams.Add($"{param.GetParamName()}");
}

foreach (var param in endpoint.GetQueryParams().OfType<IFieldProperty>())
{
methodCallParams.Add($"{param.GetParamName()}");
}

if (bodyParam != null && bodyParam is CompositionProperty)
{
methodCallParams.Add($"{bodyParam.GetParamName()}");
}
}

private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag)
{
fw.WriteLine();
WriteEndPointMethod(fw, endpoint, tag);
}

private void WriteImports(IEnumerable<Endpoint> endpoints, JavaWriter fw, string tag)
Expand Down

0 comments on commit 3ea0ac9

Please sign in to comment.