@devlearning/swagger-generator 1.0.19 → 1.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/autogen/identity/api/identity_api.dart +25 -8
  2. package/autogen/identity/models/auth_activate_command.dart +2 -2
  3. package/autogen/identity/models/auth_app_authenticate_command.dart +3 -3
  4. package/autogen/identity/models/auth_generate_reset_password_code_command.dart +3 -3
  5. package/autogen/identity/models/auth_refresh_token_command.dart +2 -2
  6. package/autogen/identity/models/auth_reset_password_command.dart +4 -4
  7. package/autogen/identity/models/auth_user_authenticate_command.dart +2 -2
  8. package/autogen/identity/models/auth_user_dto.dart +2 -2
  9. package/autogen/identity/models/authentication_token.dart +5 -5
  10. package/autogen/mvc/models/problem_details.dart +1 -1
  11. package/autogen/user_profile/api/user_profile_api.dart +22 -8
  12. package/autogen/user_profile/models/test_save_command.dart +1 -1
  13. package/dist/generator.js +20 -19
  14. package/dist/generators-writers/angular/model-angular-writer.js +4 -1
  15. package/dist/generators-writers/dart/api-dart-writer.js +8 -1
  16. package/dist/generators-writers/dart/model-dart-writer.js +1 -38
  17. package/dist/generators-writers/dart/normalizator.js +35 -6
  18. package/dist/generators-writers/nextjs/model-nextjs-writer.js +4 -1
  19. package/package.json +1 -1
  20. package/src/generator.ts +20 -21
  21. package/src/generators-writers/angular/model-angular-writer.ts +4 -1
  22. package/src/generators-writers/dart/api-dart-writer.ts +18 -4
  23. package/src/generators-writers/dart/model-dart-writer.ts +1 -42
  24. package/src/generators-writers/dart/normalizator.ts +38 -9
  25. package/src/generators-writers/dart/templates/api.mustache +11 -6
  26. package/src/generators-writers/nextjs/model-nextjs-writer.ts +4 -1
  27. package/src/models/swagger/swagger-component.ts +1 -0
  28. package/autogen/user_profile/models/test_list_query.dart +0 -13
  29. package/autogen/user_profile/models/test_read_query.dart +0 -14
@@ -16,7 +16,9 @@ class IdentityApi {
16
16
 
17
17
  IdentityApi() : _dio = getIt<Dio>();
18
18
 
19
- Future<AuthenticationToken> authAppToken(AuthAppAuthenticateCommand request) async {
19
+ Future<AuthenticationToken> authAppToken(AuthAppAuthenticateCommand request
20
+ Identity.AuthAppAuthenticateCommand request,
21
+ ) async {
20
22
  final response = await _dio.post(
21
23
  '/identity/auth/app/token',
22
24
  data: request.toJson(),
@@ -24,7 +26,9 @@ class IdentityApi {
24
26
  return AuthenticationToken.fromJson(response.data);
25
27
  }
26
28
 
27
- Future<AuthenticationToken> authUserToken(AuthUserAuthenticateCommand request) async {
29
+ Future<AuthenticationToken> authUserToken(AuthUserAuthenticateCommand request
30
+ Identity.AuthUserAuthenticateCommand request,
31
+ ) async {
28
32
  final response = await _dio.post(
29
33
  '/identity/auth/user/token',
30
34
  data: request.toJson(),
@@ -32,7 +36,9 @@ class IdentityApi {
32
36
  return AuthenticationToken.fromJson(response.data);
33
37
  }
34
38
 
35
- Future<AuthenticationToken> authRefreshToken(AuthRefreshTokenCommand request) async {
39
+ Future<AuthenticationToken> authRefreshToken(AuthRefreshTokenCommand request
40
+ Identity.AuthRefreshTokenCommand request,
41
+ ) async {
36
42
  final response = await _dio.post(
37
43
  '/identity/auth/refresh-token',
38
44
  data: request.toJson(),
@@ -40,7 +46,9 @@ class IdentityApi {
40
46
  return AuthenticationToken.fromJson(response.data);
41
47
  }
42
48
 
43
- Future<Result> authGenerateResetPasswordCode(AuthGenerateResetPasswordCodeCommand request) async {
49
+ Future<Result> authGenerateResetPasswordCode(AuthGenerateResetPasswordCodeCommand request
50
+ Identity.AuthGenerateResetPasswordCodeCommand request,
51
+ ) async {
44
52
  final response = await _dio.post(
45
53
  '/identity/auth/generate-reset-password-code',
46
54
  data: request.toJson(),
@@ -48,7 +56,9 @@ class IdentityApi {
48
56
  return Result.fromJson(response.data);
49
57
  }
50
58
 
51
- Future<Result> authResetPassword(AuthResetPasswordCommand request) async {
59
+ Future<Result> authResetPassword(AuthResetPasswordCommand request
60
+ Identity.AuthResetPasswordCommand request,
61
+ ) async {
52
62
  final response = await _dio.post(
53
63
  '/identity/auth/reset-password',
54
64
  data: request.toJson(),
@@ -56,7 +66,9 @@ class IdentityApi {
56
66
  return Result.fromJson(response.data);
57
67
  }
58
68
 
59
- Future<Result> authVerifyResetPasswordCode(AuthVerifyResetPasswordCodeCommand request) async {
69
+ Future<Result> authVerifyResetPasswordCode(AuthVerifyResetPasswordCodeCommand request
70
+ Identity.AuthVerifyResetPasswordCodeCommand request,
71
+ ) async {
60
72
  final response = await _dio.post(
61
73
  '/identity/auth/verify-reset-password-code',
62
74
  data: request.toJson(),
@@ -64,7 +76,9 @@ class IdentityApi {
64
76
  return Result.fromJson(response.data);
65
77
  }
66
78
 
67
- Future<Result> authActivate(AuthActivateCommand request) async {
79
+ Future<Result> authActivate(AuthActivateCommand request
80
+ Identity.AuthActivateCommand request,
81
+ ) async {
68
82
  final response = await _dio.post(
69
83
  '/identity/auth/activate',
70
84
  data: request.toJson(),
@@ -72,9 +86,12 @@ class IdentityApi {
72
86
  return Result.fromJson(response.data);
73
87
  }
74
88
 
75
- Future<AuthUserDto> authUserRead() async {
89
+ Future<AuthUserDto> authUserRead(
90
+ ) async {
76
91
  final response = await _dio.get(
77
92
  '/identity/auth-user/read',
93
+ queryParameters: {
94
+ },
78
95
  );
79
96
  return AuthUserDto.fromJson(response.data);
80
97
  }
@@ -6,8 +6,8 @@ part 'auth_activate_command.g.dart';
6
6
  @freezed
7
7
  abstract class AuthActivateCommand with _$AuthActivateCommand {
8
8
  const factory AuthActivateCommand({
9
- required String username,
10
- required String activationCode,
9
+ String? username,
10
+ String? activationCode,
11
11
  }) = _AuthActivateCommand;
12
12
 
13
13
  factory AuthActivateCommand.fromJson(Map<String, dynamic> json) => _$AuthActivateCommandFromJson(json);
@@ -6,9 +6,9 @@ part 'auth_app_authenticate_command.g.dart';
6
6
  @freezed
7
7
  abstract class AuthAppAuthenticateCommand with _$AuthAppAuthenticateCommand {
8
8
  const factory AuthAppAuthenticateCommand({
9
- required String appId,
10
- required String secret,
11
- required String audience,
9
+ String? appId,
10
+ String? secret,
11
+ String? audience,
12
12
  String? ipAddress,
13
13
  }) = _AuthAppAuthenticateCommand;
14
14
 
@@ -6,9 +6,9 @@ part 'auth_generate_reset_password_code_command.g.dart';
6
6
  @freezed
7
7
  abstract class AuthGenerateResetPasswordCodeCommand with _$AuthGenerateResetPasswordCodeCommand {
8
8
  const factory AuthGenerateResetPasswordCodeCommand({
9
- required String usernameOrEmail,
10
- required String host,
11
- required String urlResetPassword,
9
+ String? usernameOrEmail,
10
+ String? host,
11
+ String? urlResetPassword,
12
12
  }) = _AuthGenerateResetPasswordCodeCommand;
13
13
 
14
14
  factory AuthGenerateResetPasswordCodeCommand.fromJson(Map<String, dynamic> json) => _$AuthGenerateResetPasswordCodeCommandFromJson(json);
@@ -6,8 +6,8 @@ part 'auth_refresh_token_command.g.dart';
6
6
  @freezed
7
7
  abstract class AuthRefreshTokenCommand with _$AuthRefreshTokenCommand {
8
8
  const factory AuthRefreshTokenCommand({
9
- required String uniqueName,
10
- required String refreshToken,
9
+ String? uniqueName,
10
+ String? refreshToken,
11
11
  String? ipAddress,
12
12
  }) = _AuthRefreshTokenCommand;
13
13
 
@@ -6,10 +6,10 @@ part 'auth_reset_password_command.g.dart';
6
6
  @freezed
7
7
  abstract class AuthResetPasswordCommand with _$AuthResetPasswordCommand {
8
8
  const factory AuthResetPasswordCommand({
9
- required String usernameOrEmail,
10
- required String verificationCode,
11
- required String password,
12
- required String confirmPassword,
9
+ String? usernameOrEmail,
10
+ String? verificationCode,
11
+ String? password,
12
+ String? confirmPassword,
13
13
  }) = _AuthResetPasswordCommand;
14
14
 
15
15
  factory AuthResetPasswordCommand.fromJson(Map<String, dynamic> json) => _$AuthResetPasswordCommandFromJson(json);
@@ -6,8 +6,8 @@ part 'auth_user_authenticate_command.g.dart';
6
6
  @freezed
7
7
  abstract class AuthUserAuthenticateCommand with _$AuthUserAuthenticateCommand {
8
8
  const factory AuthUserAuthenticateCommand({
9
- required String username,
10
- required String password,
9
+ String? username,
10
+ String? password,
11
11
  String? ipAddress,
12
12
  }) = _AuthUserAuthenticateCommand;
13
13
 
@@ -10,8 +10,8 @@ abstract class AuthUserDto with _$AuthUserDto {
10
10
  required String uniqueId,
11
11
  String? username,
12
12
  String? email,
13
- String? activationDate,
14
- String? lockedDate,
13
+ DateTime? activationDate,
14
+ DateTime? lockedDate,
15
15
  }) = _AuthUserDto;
16
16
 
17
17
  factory AuthUserDto.fromJson(Map<String, dynamic> json) => _$AuthUserDtoFromJson(json);
@@ -6,11 +6,11 @@ part 'authentication_token.g.dart';
6
6
  @freezed
7
7
  abstract class AuthenticationToken with _$AuthenticationToken {
8
8
  const factory AuthenticationToken({
9
- required String uniqueName,
10
- required String accessToken,
11
- required double expiresIn,
12
- required String refreshToken,
13
- required double refreshTokenExpiresIn,
9
+ String? uniqueName,
10
+ String? accessToken,
11
+ int? expiresIn,
12
+ String? refreshToken,
13
+ int? refreshTokenExpiresIn,
14
14
  }) = _AuthenticationToken;
15
15
 
16
16
  factory AuthenticationToken.fromJson(Map<String, dynamic> json) => _$AuthenticationTokenFromJson(json);
@@ -8,7 +8,7 @@ abstract class ProblemDetails with _$ProblemDetails {
8
8
  const factory ProblemDetails({
9
9
  String? type,
10
10
  String? title,
11
- double? status,
11
+ int? status,
12
12
  String? detail,
13
13
  String? instance,
14
14
  }) = _ProblemDetails;
@@ -1,8 +1,6 @@
1
1
  import 'package:coqudo_app/core/di/injector.dart';
2
2
  import 'package:dio/dio.dart';
3
- import 'package:coqudo_app/autogen/user_profile/models/test_read_query.dart';
4
3
  import 'package:coqudo_app/autogen/service_defaults/models/result.dart';
5
- import 'package:coqudo_app/autogen/user_profile/models/test_list_query.dart';
6
4
  import 'package:coqudo_app/autogen/user_profile/models/test_save_command.dart';
7
5
  import 'package:coqudo_app/autogen/user_profile/models/user_general_info_save_command.dart';
8
6
 
@@ -11,23 +9,37 @@ class UserProfileApi {
11
9
 
12
10
  UserProfileApi() : _dio = getIt<Dio>();
13
11
 
14
- Future<Result> userGeneralInfoTestRead(TestReadQuery request) async {
12
+ Future<Result> userGeneralInfoTestRead(
13
+ String name,
14
+ DateTime? date,
15
+ int? integer,
16
+ ) async {
15
17
  final response = await _dio.get(
16
18
  '/user-profile/UserGeneralInfo/test/read',
17
- queryParameters: request.toJson(),
19
+ queryParameters: {
20
+ 'name': name,
21
+ if (date != null) 'date': date,
22
+ if (integer != null) 'integer': integer,
23
+ },
18
24
  );
19
25
  return Result.fromJson(response.data);
20
26
  }
21
27
 
22
- Future<Result> userGeneralInfoTestList(TestListQuery request) async {
28
+ Future<Result> userGeneralInfoTestList(
29
+ String name,
30
+ ) async {
23
31
  final response = await _dio.get(
24
32
  '/user-profile/UserGeneralInfo/test/list',
25
- queryParameters: request.toJson(),
33
+ queryParameters: {
34
+ 'name': name,
35
+ },
26
36
  );
27
37
  return Result.fromJson(response.data);
28
38
  }
29
39
 
30
- Future<Result> userGeneralInfoTestSave(TestSaveCommand request) async {
40
+ Future<Result> userGeneralInfoTestSave(TestSaveCommand request
41
+ UserProfile.TestSaveCommand request,
42
+ ) async {
31
43
  final response = await _dio.post(
32
44
  '/user-profile/UserGeneralInfo/test/save',
33
45
  data: request.toJson(),
@@ -35,7 +47,9 @@ class UserProfileApi {
35
47
  return Result.fromJson(response.data);
36
48
  }
37
49
 
38
- Future<Result> userGeneralInfoSave(UserGeneralInfoSaveCommand request) async {
50
+ Future<Result> userGeneralInfoSave(UserGeneralInfoSaveCommand request
51
+ UserProfile.UserGeneralInfoSaveCommand request,
52
+ ) async {
39
53
  final response = await _dio.post(
40
54
  '/user-profile/UserGeneralInfo/save',
41
55
  data: request.toJson(),
@@ -6,7 +6,7 @@ part 'test_save_command.g.dart';
6
6
  @freezed
7
7
  abstract class TestSaveCommand with _$TestSaveCommand {
8
8
  const factory TestSaveCommand({
9
- required String name,
9
+ String? name,
10
10
  }) = _TestSaveCommand;
11
11
 
12
12
  factory TestSaveCommand.fromJson(Map<String, dynamic> json) => _$TestSaveCommandFromJson(json);
package/dist/generator.js CHANGED
@@ -3,7 +3,7 @@ import { ApiAngularWriter } from './generators-writers/angular/api-angular-write
3
3
  import { SingleBar, Presets } from 'cli-progress';
4
4
  import { ModelNextJsWriter } from './generators-writers/nextjs/model-nextjs-writer.js';
5
5
  import { ModelAngularWriter } from './generators-writers/angular/model-angular-writer.js';
6
- import { DateTimeLibrary, TargetGeneration } from './index.js';
6
+ import { TargetGeneration } from './index.js';
7
7
  import { ApiDartWriter } from './generators-writers/dart/api-dart-writer.js';
8
8
  import { ModelDartWriter } from './generators-writers/dart/model-dart-writer.js';
9
9
  import { Utils } from './generators-writers/utils.js';
@@ -49,7 +49,6 @@ export class Generator {
49
49
  const apiSwaggerMethodKey = this._swagger.paths[apiName];
50
50
  const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
51
51
  const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
52
- // console.debug(`\tAPI - ${apiName} - ${apiMethod}`);
53
52
  let apiDto = {
54
53
  name: apiName,
55
54
  url: apiName.replace('{version}', '1'),
@@ -109,7 +108,6 @@ export class Generator {
109
108
  for (let index = 0; index < Object.getOwnPropertyNames(this._swagger.components.schemas).length; index++) {
110
109
  const modelName = Object.getOwnPropertyNames(this._swagger.components.schemas)[index];
111
110
  const swaggerComponent = this._swagger.components.schemas[modelName];
112
- // console.debug(`\tModel - ${modelName}`);
113
111
  this._models.push({
114
112
  typeName: modelName,
115
113
  modelType: swaggerComponent.type == 'integer' ? 'enum' : 'class',
@@ -123,13 +121,14 @@ export class Generator {
123
121
  const swaggerMethod = this._swagger.paths[apiName];
124
122
  const method = Object.getOwnPropertyNames(swaggerMethod)[0];
125
123
  const swaggerMethodInfo = swaggerMethod[method];
126
- this._models.push({
127
- typeName: this.getApiNameNormalized(apiName),
128
- modelType: 'class',
129
- name: this.getApiNameNormalized(apiName),
130
- properties: this.retrieveComponentProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema),
131
- enumValues: [],
132
- });
124
+ throw new Error(`MultiPart FormData is not supported yet for ${apiName} - ${method}.`);
125
+ // this._models.push({
126
+ // typeName: this.getApiNameNormalized(apiName),
127
+ // modelType: 'class',
128
+ // name: this.getApiNameNormalized(apiName),
129
+ // properties: this.retrieveComponentProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema),
130
+ // enumValues: [],
131
+ // });
133
132
  });
134
133
  }
135
134
  generateApi() {
@@ -386,17 +385,18 @@ export class Generator {
386
385
  getObjectName(ref) {
387
386
  return ref.replace('#/components/schemas/', '');
388
387
  }
389
- retrieveComponentProperties(swaggerCopmponent) {
390
- if (swaggerCopmponent.properties == null)
388
+ retrieveComponentProperties(swaggerComponent) {
389
+ if (swaggerComponent.properties == null)
391
390
  return [];
392
391
  let properties = [];
393
- for (let index = 0; index < Object.getOwnPropertyNames(swaggerCopmponent.properties).length; index++) {
394
- const propertyName = Object.getOwnPropertyNames(swaggerCopmponent.properties)[index];
395
- const type = this.retrieveType(swaggerCopmponent.properties[propertyName]);
392
+ for (let index = 0; index < Object.getOwnPropertyNames(swaggerComponent.properties).length; index++) {
393
+ const propertyName = Object.getOwnPropertyNames(swaggerComponent.properties)[index];
394
+ const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
395
+ const type = this.retrieveType(swaggerComponent.properties[propertyName]);
396
396
  properties.push({
397
397
  ...type,
398
398
  name: propertyName,
399
- nullable: type.nullable,
399
+ nullable: required || type.nullable,
400
400
  });
401
401
  }
402
402
  return properties;
@@ -450,11 +450,12 @@ export class Generator {
450
450
  }
451
451
  if (nestedUsedType != '' && usedTypes.findIndex(x => x.typeName == nestedUsedType) == -1) {
452
452
  let nested = this._swagger.components.schemas[nestedUsedType];
453
+ const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
453
454
  usedTypes.push({
454
455
  typeName: nestedUsedType,
455
456
  isTypeReference: nested.type == 'object',
456
457
  isNativeType: nested.type != 'object',
457
- nullable: false,
458
+ nullable: required,
458
459
  isArray: false,
459
460
  isVoid: false,
460
461
  //potrebbe essere un enum
@@ -478,11 +479,11 @@ export class Generator {
478
479
  }
479
480
  else {
480
481
  if (schema.type == 'integer')
481
- nativeType = 'number';
482
+ nativeType = 'integer'; //era number
482
483
  if (schema.type == 'string' && schema.format == null)
483
484
  nativeType = 'string';
484
485
  if (schema.type == 'string' && schema.format == 'date-time')
485
- nativeType = this._commandLineArgs.dateTimeLibrary == DateTimeLibrary.Moment ? 'moment.Moment' : 'Date';
486
+ nativeType = 'dateTime';
486
487
  if (schema.type == 'string' && schema.format == 'uuid')
487
488
  nativeType = 'string';
488
489
  if (schema.type == 'string' && schema.format == 'binary')
@@ -23,7 +23,10 @@ ${this._properties(model)}${this._enumValues(model)}
23
23
  _properties(model) {
24
24
  let propertiesString = '';
25
25
  model.properties.forEach(property => {
26
- propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${property.typeName};\n`;
26
+ //const libraryDate = this._commandLineArgs.dateTimeLibrary == DateTimeLibrary.Moment ? 'moment.Moment' : 'Date'
27
+ const libraryDate = 'moment.Moment';
28
+ const typeName = property.typeName === 'dateTime' ? libraryDate : property.typeName;
29
+ propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${typeName};\n`;
27
30
  });
28
31
  return propertiesString.trimEnd();
29
32
  }
@@ -56,8 +56,15 @@ export class ApiDartWriter {
56
56
  responseType: responseType,
57
57
  haveRequest: api.haveRequest,
58
58
  requestType: requestType,
59
- isGet: api.method.toLowerCase() === 'get'
60
59
  };
60
+ if (api.parameters && api.parameters.length > 0) {
61
+ endpoint.queryParams = api.parameters
62
+ .map(p => ({
63
+ name: p.name,
64
+ type: p.typeName ? Normalizator.mapTsTypeToDart(p.typeName) : 'String',
65
+ nullable: p.nullable
66
+ }));
67
+ }
61
68
  if (api.haveRequest && api.parameters[0]?.typeName) {
62
69
  if (imports.findIndex(x => x.type.typeName == api.parameters[0]?.typeName) == -1) {
63
70
  models.forEach(model => {
@@ -29,10 +29,7 @@ export class ModelDartWriter {
29
29
  };
30
30
  var imports = [];
31
31
  model.properties.forEach(property => {
32
- var fieldTypeName = this._mapTsTypeToDart(property.typeName);
33
- // if (fieldTypeName.endsWith('Exception')) {
34
- // debugger
35
- // }
32
+ var fieldTypeName = Normalizator.mapTsTypeToDart(property.typeName);
36
33
  fieldTypeName = Normalizator.getNormalizedTypeName(fieldTypeName);
37
34
  if (property.isTypeReference) {
38
35
  if (imports.findIndex(x => x.type.typeName == property.typeName) == -1) {
@@ -96,38 +93,4 @@ export class ModelDartWriter {
96
93
  // });
97
94
  // this._writeFile(modelString);
98
95
  }
99
- _mapTsTypeToDart(type) {
100
- const normalized = type.trim().toLowerCase();
101
- if (normalized.endsWith("[]")) {
102
- const inner = normalized.slice(0, -2).trim();
103
- return `List<${this._mapTsTypeToDart(inner)}>`;
104
- }
105
- switch (normalized) {
106
- case "string":
107
- case "uuid":
108
- case "date":
109
- case "datetime":
110
- return "String";
111
- case "number":
112
- case "float":
113
- case "double":
114
- return "double";
115
- case "integer":
116
- case "int":
117
- case "long":
118
- return "int";
119
- case "boolean":
120
- case "bool":
121
- return "bool";
122
- case "any":
123
- case "object":
124
- return "dynamic";
125
- case "null":
126
- case "undefined":
127
- return "Null";
128
- default:
129
- // per tipi personalizzati (es. modelli) restituisci con PascalCase
130
- return Utils.toPascalCase(type);
131
- }
132
- }
133
96
  }
@@ -1,11 +1,5 @@
1
1
  import { Utils } from "../utils.js";
2
2
  export class Normalizator {
3
- // public static normalizeModelName(modelName: string): string {
4
- // let normalizeModelName = modelName.split('.').pop()!;
5
- // return Utils.toDartClassName(filename) ?? filename;
6
- // }
7
- // subPath = model.name.split('.').slice(0, -1).join('');
8
- // subPath = `${Utils.toDartFileName(subPath)}/models`;
9
3
  static getNormalizedInfo(model) {
10
4
  let subPath = '';
11
5
  let filename = '';
@@ -32,4 +26,39 @@ export class Normalizator {
32
26
  let formattedTypeName = typeName.split('.').pop();
33
27
  return Utils.toDartClassName(formattedTypeName) ?? typeName;
34
28
  }
29
+ static mapTsTypeToDart(type) {
30
+ const normalized = type.trim().toLowerCase();
31
+ if (normalized.endsWith("[]")) {
32
+ const inner = normalized.slice(0, -2).trim();
33
+ return `List<${Normalizator.mapTsTypeToDart(inner)}>`;
34
+ }
35
+ switch (normalized) {
36
+ case "string":
37
+ case "uuid":
38
+ case "date":
39
+ return "String";
40
+ case "dateTime":
41
+ return "DateTime";
42
+ case "number":
43
+ case "float":
44
+ case "double":
45
+ return "double";
46
+ case "integer":
47
+ case "int":
48
+ case "long":
49
+ return "int";
50
+ case "boolean":
51
+ case "bool":
52
+ return "bool";
53
+ case "any":
54
+ case "object":
55
+ return "dynamic";
56
+ case "null":
57
+ case "undefined":
58
+ return "Null";
59
+ default:
60
+ // per tipi personalizzati (es. modelli) restituisci con PascalCase
61
+ return Utils.toPascalCase(type);
62
+ }
63
+ }
35
64
  }
@@ -22,7 +22,10 @@ ${this._properties(model)}${this._enumValues(model)}
22
22
  _properties(model) {
23
23
  let propertiesString = '';
24
24
  model.properties.forEach(property => {
25
- propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${property.typeName};\n`;
25
+ //const libraryDate = this._commandLineArgs.dateTimeLibrary == DateTimeLibrary.Moment ? 'moment.Moment' : 'Date'
26
+ const libraryDate = 'Date';
27
+ const typeName = property.typeName === 'dateTime' ? libraryDate : property.typeName;
28
+ propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${typeName};\n`;
26
29
  });
27
30
  return propertiesString.trimEnd();
28
31
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devlearning/swagger-generator",
3
- "version": "1.0.19",
3
+ "version": "1.0.21",
4
4
  "description": "Swagger generator apis and models for Angular and NextJS",
5
5
  "main": "index.js",
6
6
  "type": "module",
package/src/generator.ts CHANGED
@@ -74,8 +74,6 @@ export class Generator {
74
74
  const apiMethod = Object.getOwnPropertyNames(apiSwaggerMethodKey)[0];
75
75
  const apiSwaggerMethod = apiSwaggerMethodKey[apiMethod];
76
76
 
77
- // console.debug(`\tAPI - ${apiName} - ${apiMethod}`);
78
-
79
77
  let apiDto: ApiDto = {
80
78
  name: apiName,
81
79
  url: apiName.replace('{version}', '1'),
@@ -149,7 +147,6 @@ export class Generator {
149
147
 
150
148
  const swaggerComponent = this._swagger.components.schemas[modelName];
151
149
 
152
- // console.debug(`\tModel - ${modelName}`);
153
150
  this._models.push({
154
151
  typeName: modelName,
155
152
  modelType: swaggerComponent.type == 'integer' ? 'enum' : 'class',
@@ -166,13 +163,14 @@ export class Generator {
166
163
  const method = Object.getOwnPropertyNames(swaggerMethod)[0];
167
164
  const swaggerMethodInfo = swaggerMethod[method];
168
165
 
169
- this._models.push({
170
- typeName: this.getApiNameNormalized(apiName),
171
- modelType: 'class',
172
- name: this.getApiNameNormalized(apiName),
173
- properties: this.retrieveComponentProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema),
174
- enumValues: [],
175
- });
166
+ throw new Error(`MultiPart FormData is not supported yet for ${apiName} - ${method}.`);
167
+ // this._models.push({
168
+ // typeName: this.getApiNameNormalized(apiName),
169
+ // modelType: 'class',
170
+ // name: this.getApiNameNormalized(apiName),
171
+ // properties: this.retrieveComponentProperties(swaggerMethodInfo.requestBody.content[contentTypeMultipartFormData].schema),
172
+ // enumValues: [],
173
+ // });
176
174
  });
177
175
  }
178
176
 
@@ -446,18 +444,18 @@ export class Generator {
446
444
  return ref.replace('#/components/schemas/', '');
447
445
  }
448
446
 
449
- retrieveComponentProperties(swaggerCopmponent: SwaggerComponent | SwaggerSchema) {
450
- if (swaggerCopmponent.properties == null) return [];
447
+ retrieveComponentProperties(swaggerComponent: SwaggerComponent) {
448
+ if (swaggerComponent.properties == null) return [];
451
449
 
452
450
  let properties: PropertyDto[] = [];
453
- for (let index = 0; index < Object.getOwnPropertyNames(swaggerCopmponent.properties).length; index++) {
454
- const propertyName = Object.getOwnPropertyNames(swaggerCopmponent.properties)[index];
455
-
456
- const type = this.retrieveType(swaggerCopmponent.properties[propertyName]);
451
+ for (let index = 0; index < Object.getOwnPropertyNames(swaggerComponent.properties).length; index++) {
452
+ const propertyName = Object.getOwnPropertyNames(swaggerComponent.properties)[index];
453
+ const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
454
+ const type = this.retrieveType(swaggerComponent.properties[propertyName]);
457
455
  properties.push({
458
456
  ...type,
459
457
  name: propertyName,
460
- nullable: type.nullable,
458
+ nullable: required || type.nullable,
461
459
  });
462
460
  }
463
461
 
@@ -512,7 +510,7 @@ export class Generator {
512
510
 
513
511
  if (swaggerComponent.properties[propertyName].$ref) {
514
512
  nestedUsedType = swaggerComponent.properties[propertyName].$ref!.replace('#/components/schemas/', '');
515
- }else if (swaggerComponent.properties[propertyName].allOf && swaggerComponent.properties[propertyName].allOf![0] && swaggerComponent.properties[propertyName].allOf![0]!.$ref) {
513
+ } else if (swaggerComponent.properties[propertyName].allOf && swaggerComponent.properties[propertyName].allOf![0] && swaggerComponent.properties[propertyName].allOf![0]!.$ref) {
516
514
  nestedUsedType = swaggerComponent.properties[propertyName].allOf![0]!.$ref!.replace('#/components/schemas/', ''); //TODO Assuming allOf contains a single $ref
517
515
  } else if (swaggerComponent.properties[propertyName].type == 'array' && swaggerComponent.properties[propertyName].items?.$ref) {
518
516
  nestedUsedType = swaggerComponent.properties[propertyName].items!.$ref!.replace('#/components/schemas/', '');
@@ -520,11 +518,12 @@ export class Generator {
520
518
 
521
519
  if (nestedUsedType != '' && usedTypes.findIndex(x => x.typeName == nestedUsedType) == -1) {
522
520
  let nested = this._swagger.components.schemas[nestedUsedType];
521
+ const required = swaggerComponent.required && swaggerComponent.required.includes(propertyName);
523
522
  usedTypes.push({
524
523
  typeName: nestedUsedType,
525
524
  isTypeReference: nested.type == 'object',
526
525
  isNativeType: nested.type != 'object',
527
- nullable: false,
526
+ nullable: required,
528
527
  isArray: false,
529
528
  isVoid: false,
530
529
  //potrebbe essere un enum
@@ -546,9 +545,9 @@ export class Generator {
546
545
  nativeType = this.getNativeType(schema.items);
547
546
  nativeType += '[]';
548
547
  } else {
549
- if (schema.type == 'integer') nativeType = 'number';
548
+ if (schema.type == 'integer') nativeType = 'integer'; //era number
550
549
  if (schema.type == 'string' && schema.format == null) nativeType = 'string';
551
- if (schema.type == 'string' && schema.format == 'date-time') nativeType = this._commandLineArgs.dateTimeLibrary == DateTimeLibrary.Moment ? 'moment.Moment' : 'Date';
550
+ if (schema.type == 'string' && schema.format == 'date-time') nativeType = 'dateTime';
552
551
  if (schema.type == 'string' && schema.format == 'uuid') nativeType = 'string';
553
552
  if (schema.type == 'string' && schema.format == 'binary') nativeType = 'File';
554
553
  if (schema.type == 'number') nativeType = 'number';
@@ -34,7 +34,10 @@ ${this._properties(model)}${this._enumValues(model)}
34
34
  let propertiesString = '';
35
35
 
36
36
  model.properties.forEach(property => {
37
- propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${property.typeName};\n`;
37
+ //const libraryDate = this._commandLineArgs.dateTimeLibrary == DateTimeLibrary.Moment ? 'moment.Moment' : 'Date'
38
+ const libraryDate = 'moment.Moment';
39
+ const typeName = property.typeName === 'dateTime' ? libraryDate : property.typeName;
40
+ propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${typeName};\n`;
38
41
  });
39
42
 
40
43
  return propertiesString.trimEnd();
@@ -25,9 +25,15 @@ interface EndpointDefinitionDart {
25
25
  httpMethod: HttpMethodDart;
26
26
  path: string;
27
27
  responseType: string;
28
- haveRequest?: boolean;
28
+ haveRequest: boolean;
29
29
  requestType?: string; // solo se haveRequest è true
30
- isGet?: boolean; // per indicare se è un metodo GET
30
+ queryParams?: Parameter[],
31
+ }
32
+
33
+ interface Parameter {
34
+ name: string;
35
+ type: string; // "string", "int", ecc
36
+ nullable: boolean;
31
37
  }
32
38
 
33
39
  type HttpMethodDart = 'get' | 'post' | 'put' | 'delete' | 'patch';
@@ -46,7 +52,7 @@ export class ApiDartWriter {
46
52
  const templatePath = path.join(__dirname, 'templates', 'api.mustache');
47
53
  const template = fs.readFileSync(templatePath, 'utf-8');
48
54
  let importDirectory = this._commandLineArgs.outputDirectory;
49
- if(importDirectory.startsWith('lib/')) {
55
+ if (importDirectory.startsWith('lib/')) {
50
56
  importDirectory = importDirectory.slice('lib/'.length);
51
57
  }
52
58
 
@@ -97,9 +103,17 @@ export class ApiDartWriter {
97
103
  responseType: responseType,
98
104
  haveRequest: api.haveRequest,
99
105
  requestType: requestType,
100
- isGet: api.method.toLowerCase() === 'get'
101
106
  };
102
107
 
108
+ if (api.parameters && api.parameters.length > 0) {
109
+ endpoint.queryParams = api.parameters
110
+ .map(p => ({
111
+ name: p.name,
112
+ type: p.typeName ? Normalizator.mapTsTypeToDart(p.typeName)! : 'String',
113
+ nullable: p.nullable
114
+ }));
115
+ }
116
+
103
117
  if (api.haveRequest && api.parameters[0]?.typeName) {
104
118
  if (imports.findIndex(x => x.type.typeName == api.parameters[0]?.typeName) == -1) {
105
119
  models.forEach(model => {
@@ -60,11 +60,7 @@ export class ModelDartWriter {
60
60
  var imports = <ImportDefinitionDart[]>[];
61
61
 
62
62
  model.properties.forEach(property => {
63
- var fieldTypeName = this._mapTsTypeToDart(property.typeName);
64
-
65
- // if (fieldTypeName.endsWith('Exception')) {
66
- // debugger
67
- // }
63
+ var fieldTypeName = Normalizator.mapTsTypeToDart(property.typeName);
68
64
 
69
65
  fieldTypeName = Normalizator.getNormalizedTypeName(fieldTypeName);
70
66
 
@@ -145,41 +141,4 @@ export class ModelDartWriter {
145
141
 
146
142
  // this._writeFile(modelString);
147
143
  }
148
-
149
- private _mapTsTypeToDart(type: string): string {
150
- const normalized = type.trim().toLowerCase();
151
-
152
- if (normalized.endsWith("[]")) {
153
- const inner = normalized.slice(0, -2).trim();
154
- return `List<${this._mapTsTypeToDart(inner)}>`;
155
- }
156
-
157
- switch (normalized) {
158
- case "string":
159
- case "uuid":
160
- case "date":
161
- case "datetime":
162
- return "String";
163
- case "number":
164
- case "float":
165
- case "double":
166
- return "double";
167
- case "integer":
168
- case "int":
169
- case "long":
170
- return "int";
171
- case "boolean":
172
- case "bool":
173
- return "bool";
174
- case "any":
175
- case "object":
176
- return "dynamic";
177
- case "null":
178
- case "undefined":
179
- return "Null";
180
- default:
181
- // per tipi personalizzati (es. modelli) restituisci con PascalCase
182
- return Utils.toPascalCase(type);
183
- }
184
- }
185
144
  }
@@ -3,15 +3,6 @@ import { Utils } from "../utils.js";
3
3
 
4
4
  export class Normalizator {
5
5
 
6
- // public static normalizeModelName(modelName: string): string {
7
- // let normalizeModelName = modelName.split('.').pop()!;
8
- // return Utils.toDartClassName(filename) ?? filename;
9
- // }
10
-
11
-
12
- // subPath = model.name.split('.').slice(0, -1).join('');
13
- // subPath = `${Utils.toDartFileName(subPath)}/models`;
14
-
15
6
  public static getNormalizedInfo(model: ModelDto) {
16
7
  let subPath = '';
17
8
  let filename = '';
@@ -41,4 +32,42 @@ export class Normalizator {
41
32
  return Utils.toDartClassName(formattedTypeName) ?? typeName;
42
33
  }
43
34
 
35
+ public static mapTsTypeToDart(type: string): string {
36
+ const normalized = type.trim().toLowerCase();
37
+
38
+ if (normalized.endsWith("[]")) {
39
+ const inner = normalized.slice(0, -2).trim();
40
+ return `List<${Normalizator.mapTsTypeToDart(inner)}>`;
41
+ }
42
+
43
+ switch (normalized) {
44
+ case "string":
45
+ case "uuid":
46
+ case "date":
47
+ return "String";
48
+ case "dateTime":
49
+ return "DateTime";
50
+ case "number":
51
+ case "float":
52
+ case "double":
53
+ return "double";
54
+ case "integer":
55
+ case "int":
56
+ case "long":
57
+ return "int";
58
+ case "boolean":
59
+ case "bool":
60
+ return "bool";
61
+ case "any":
62
+ case "object":
63
+ return "dynamic";
64
+ case "null":
65
+ case "undefined":
66
+ return "Null";
67
+ default:
68
+ // per tipi personalizzati (es. modelli) restituisci con PascalCase
69
+ return Utils.toPascalCase(type);
70
+ }
71
+ }
72
+
44
73
  }
@@ -10,16 +10,21 @@ class {{apiClassName}} {
10
10
  {{apiClassName}}() : _dio = getIt<Dio>();
11
11
 
12
12
  {{#endpoints}}
13
- Future<{{responseType}}> {{methodName}}({{#haveRequest}}{{requestType}} request{{/haveRequest}}) async {
13
+ Future<{{responseType}}> {{methodName}}({{#haveRequest}}{{requestType}} request{{/haveRequest}}
14
+ {{#queryParams}}
15
+ {{type}}{{#nullable}}?{{/nullable}} {{name}},
16
+ {{/queryParams}}) async {
14
17
  final response = await _dio.{{httpMethod}}(
15
18
  '{{{path}}}',
16
19
  {{#haveRequest}}
17
- {{#isGet}}
18
- queryParameters: request.toJson(),
19
- {{/isGet}}
20
- {{^isGet}}
21
20
  data: request.toJson(),
22
- {{/isGet}}
21
+ {{/haveRequest}}
22
+ {{^haveRequest}}
23
+ queryParameters: {
24
+ {{#queryParams}}
25
+ {{#nullable}}if ({{name}} != null) {{/nullable}}'{{name}}': {{name}},
26
+ {{/queryParams}}
27
+ },
23
28
  {{/haveRequest}}
24
29
  );
25
30
  return {{responseType}}.fromJson(response.data);
@@ -33,7 +33,10 @@ ${this._properties(model)}${this._enumValues(model)}
33
33
  let propertiesString = '';
34
34
 
35
35
  model.properties.forEach(property => {
36
- propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${property.typeName};\n`;
36
+ //const libraryDate = this._commandLineArgs.dateTimeLibrary == DateTimeLibrary.Moment ? 'moment.Moment' : 'Date'
37
+ const libraryDate = 'Date';
38
+ const typeName = property.typeName === 'dateTime' ? libraryDate : property.typeName;
39
+ propertiesString += ` ${property.name}${property.nullable ? '?' : ''}: ${typeName};\n`;
37
40
  });
38
41
 
39
42
  return propertiesString.trimEnd();
@@ -14,4 +14,5 @@ export interface SwaggerComponent {
14
14
  properties: { [key: string]: SwaggerSchema; };
15
15
  additionalProperties: boolean;
16
16
  enum: string[];
17
+ required: string[];
17
18
  }
@@ -1,13 +0,0 @@
1
- import 'package:freezed_annotation/freezed_annotation.dart';
2
-
3
- part 'test_list_query.freezed.dart';
4
- part 'test_list_query.g.dart';
5
-
6
- @freezed
7
- abstract class TestListQuery with _$TestListQuery {
8
- const factory TestListQuery({
9
- String? name,
10
- }) = _TestListQuery;
11
-
12
- factory TestListQuery.fromJson(Map<String, dynamic> json) => _$TestListQueryFromJson(json);
13
- }
@@ -1,14 +0,0 @@
1
- import 'package:freezed_annotation/freezed_annotation.dart';
2
-
3
- part 'test_read_query.freezed.dart';
4
- part 'test_read_query.g.dart';
5
-
6
- @freezed
7
- abstract class TestReadQuery with _$TestReadQuery {
8
- const factory TestReadQuery({
9
- required String name,
10
- required String date,
11
- }) = _TestReadQuery;
12
-
13
- factory TestReadQuery.fromJson(Map<String, dynamic> json) => _$TestReadQueryFromJson(json);
14
- }