From 329e51395d36e11090e33300d02f5a7a436bfe7a Mon Sep 17 00:00:00 2001 From: Dane Pilcher Date: Thu, 3 Feb 2022 14:49:54 -0700 Subject: [PATCH] feat: update imports generated for flutter datastore plugin dependency (#382) (#388) * chore(amplify-codegen): change flutter import path from datastore to core (#380) * feat(appsync-modelgen-plugin): Change flutter datastore models dependency to use amplify_core * feat(appsync-modelgen-plugin): add amplify_flutter version check to determine datastore dependency import * fix(appsync-modelgen-plugin): correct indentation for error message * fix(appsync-modelgen-plugin): run linter * fix(amplify-codegen): update unit tests * fix(amplify-codegen): lower minimum version to 0.4.0-rc.1 * fix(appsync-modelgen-plugin): remove duplicate .dart from imports Co-authored-by: Travis Sheppard Co-authored-by: Dane Pilcher Co-authored-by: Phani Srikar Edupuganti <55896475+phani-srikar@users.noreply.github.com> Co-authored-by: Travis Sheppard --- .../amplify-codegen/src/commands/models.js | 5 + ...eAmplifyFlutterCapableZeroThreeFeatures.js | 31 +- ...dateAmplifyFlutterCoreLibraryDependency.js | 9 + .../utils/validateAmplifyFlutterVersion.js | 29 + .../tests/commands/models.test.js | 84 -- ...teAmplifyFlutterCapableForNonModel.test.js | 10 +- .../appsync-dart-visitor.test.ts.snap | 930 +++++++++++++++--- .../visitors/appsync-dart-visitor.test.ts | 38 + .../appsync-dart-visitor.test.ts.snap | 170 ++-- .../src/configs/dart-config.ts | 7 +- .../src/visitors/appsync-dart-visitor.ts | 91 +- 11 files changed, 1046 insertions(+), 358 deletions(-) create mode 100644 packages/amplify-codegen/src/utils/validateAmplifyFlutterCoreLibraryDependency.js create mode 100644 packages/amplify-codegen/src/utils/validateAmplifyFlutterVersion.js diff --git a/packages/amplify-codegen/src/commands/models.js b/packages/amplify-codegen/src/commands/models.js index aa6d0a73f..7e4e0b229 100644 --- a/packages/amplify-codegen/src/commands/models.js +++ b/packages/amplify-codegen/src/commands/models.js @@ -7,6 +7,7 @@ const gqlCodeGen = require('@graphql-codegen/core'); const { getModelgenPackage } = require('../utils/getModelgenPackage'); const { validateDartSDK } = require('../utils/validateDartSDK'); const { validateAmplifyFlutterCapableZeroThreeFeatures } = require('../utils/validateAmplifyFlutterCapableZeroThreeFeatures'); +const { validateAmplifyFlutterCoreLibraryDependency } = require('../utils/validateAmplifyFlutterCoreLibraryDependency'); const platformToLanguageMap = { android: 'java', @@ -90,6 +91,7 @@ async function generateModels(context) { let isTimestampFieldsAdded = readFeatureFlag('codegen.addTimestampFields'); let enableDartNullSafety = readFeatureFlag('codegen.enableDartNullSafety'); let enableDartZeroThreeFeatures = false; + let dartUpdateAmplifyCoreDependency = false; if (projectConfig.frontend === 'flutter') { const isMinimumDartVersionSatisfied = validateDartSDK(context, projectRoot); @@ -107,6 +109,8 @@ async function generateModels(context) { // override isTimestampFieldsAdded to true when using amplify-flutter > 0.3.0 || > 0.3.0-rc.2 isTimestampFieldsAdded = validateAmplifyFlutterCapableZeroThreeFeatures(projectRoot); enableDartZeroThreeFeatures = validateAmplifyFlutterCapableZeroThreeFeatures(projectRoot); + // This feature is supported only for users using amplify-flutter > 0.4.0 || > 0.4.0-rc.1 + dartUpdateAmplifyCoreDependency = validateAmplifyFlutterCoreLibraryDependency(projectRoot); } const handleListNullabilityTransparently = readFeatureFlag('codegen.handleListNullabilityTransparently'); @@ -124,6 +128,7 @@ async function generateModels(context) { usePipelinedTransformer, enableDartZeroThreeFeatures, transformerVersion, + dartUpdateAmplifyCoreDependency }, }); diff --git a/packages/amplify-codegen/src/utils/validateAmplifyFlutterCapableZeroThreeFeatures.js b/packages/amplify-codegen/src/utils/validateAmplifyFlutterCapableZeroThreeFeatures.js index d9efb16fb..63e50601e 100644 --- a/packages/amplify-codegen/src/utils/validateAmplifyFlutterCapableZeroThreeFeatures.js +++ b/packages/amplify-codegen/src/utils/validateAmplifyFlutterCapableZeroThreeFeatures.js @@ -1,32 +1,9 @@ -const yaml = require('js-yaml'); -const path = require('path'); -const fs = require('fs-extra'); -const semver = require('semver'); +const { validateAmplifyFlutterVersion } = require('./validateAmplifyFlutterVersion'); -const PUBSPEC_LOCK_FILE_NAME = 'pubspec.lock'; -const MINIMUM_VERSION_CONSTRAIN = '>= 0.3.0 || >= 0.3.0-rc.2'; +const MINIMUM_VERSION_CONSTRAINT = '>= 0.3.0 || >= 0.3.0-rc.2'; function validateAmplifyFlutterCapableZeroThreeFeatures(projectRoot) { - try { - const lockFile = yaml.load(fs.readFileSync(path.join(projectRoot, PUBSPEC_LOCK_FILE_NAME), 'utf8')); - // check resolved dependency version written pubspec.lock file - const { version } = lockFile.packages.amplify_flutter || {}; - // For this util function it check only if the amplify_flutter version is great than the minimum version - // and it's not concerned with prerelease range, hence including prerelease to ensure - // 0.4.0-rc.2 > 0.3.0-rc.2 is true - if (semver.satisfies(version, MINIMUM_VERSION_CONSTRAIN, { includePrerelease: true })) { - return true; - } - return false; - } catch (e) { - if (e.stack) { - console.log(e.stack); - console.log(e.message); - } - - console.log('An error occurred while parsing ' + PUBSPEC_LOCK_FILE_NAME + '.'); - return false; - } + return validateAmplifyFlutterVersion(projectRoot, MINIMUM_VERSION_CONSTRAINT); } -module.exports = { validateAmplifyFlutterCapableZeroThreeFeatures, PUBSPEC_LOCK_FILE_NAME, MINIMUM_VERSION_CONSTRAIN }; +module.exports = { validateAmplifyFlutterCapableZeroThreeFeatures }; diff --git a/packages/amplify-codegen/src/utils/validateAmplifyFlutterCoreLibraryDependency.js b/packages/amplify-codegen/src/utils/validateAmplifyFlutterCoreLibraryDependency.js new file mode 100644 index 000000000..bd9528bc3 --- /dev/null +++ b/packages/amplify-codegen/src/utils/validateAmplifyFlutterCoreLibraryDependency.js @@ -0,0 +1,9 @@ +const { validateAmplifyFlutterVersion } = require('./validateAmplifyFlutterVersion'); + +const MINIMUM_VERSION_CONSTRAINT = '>= 0.4.0 || >= 0.4.0-rc.1'; + +function validateAmplifyFlutterCoreLibraryDependency(projectRoot) { + return validateAmplifyFlutterVersion(projectRoot, MINIMUM_VERSION_CONSTRAINT); +} + +module.exports = { validateAmplifyFlutterCoreLibraryDependency }; diff --git a/packages/amplify-codegen/src/utils/validateAmplifyFlutterVersion.js b/packages/amplify-codegen/src/utils/validateAmplifyFlutterVersion.js new file mode 100644 index 000000000..17a11e65f --- /dev/null +++ b/packages/amplify-codegen/src/utils/validateAmplifyFlutterVersion.js @@ -0,0 +1,29 @@ +const yaml = require('js-yaml'); +const path = require('path'); +const fs = require('fs-extra'); +const semver = require('semver'); + +const PUBSPEC_LOCK_FILE_NAME = 'pubspec.lock'; + +function validateAmplifyFlutterVersion(projectRoot, versionConstraint) { + try { + const lockFile = yaml.load(fs.readFileSync(path.join(projectRoot, PUBSPEC_LOCK_FILE_NAME), 'utf8')); + // check resolved dependency version written pubspec.lock file + const { version } = lockFile.packages.amplify_flutter || {}; + // For this util function it check only if the amplify_flutter version satisfies the given version constraint + if (semver.satisfies(version, versionConstraint, { includePrerelease: true })) { + return true; + } + return false; + } catch (e) { + if (e.stack) { + console.log(e.stack); + console.log(e.message); + } + + console.log('An error occurred while parsing ' + PUBSPEC_LOCK_FILE_NAME + '.'); + return false; + } +} + +module.exports = { validateAmplifyFlutterVersion, PUBSPEC_LOCK_FILE_NAME }; diff --git a/packages/amplify-codegen/tests/commands/models.test.js b/packages/amplify-codegen/tests/commands/models.test.js index 929ed949f..0f0d6f240 100644 --- a/packages/amplify-codegen/tests/commands/models.test.js +++ b/packages/amplify-codegen/tests/commands/models.test.js @@ -31,7 +31,6 @@ const MOCK_PROJECT_ROOT = 'project'; const MOCK_PROJECT_NAME = 'myapp'; const MOCK_BACKEND_DIRECTORY = 'backend'; const MOCK_GENERATED_CODE = 'This code is auto-generated!'; -const MOCK_PRE_EXISTING_FILE = 'preexisting.txt'; // Mock the Feature flag to use migrated moldegen jest.mock('amplify-cli-core', MOCK_PROJECT_ROOT => { @@ -109,89 +108,6 @@ describe('command-models-generates models in expected output path', () => { afterEach(mockFs.restore); }); -describe('codegen models respects cleanGeneratedModelsDirectory', () => { - beforeEach(() => { - jest.resetAllMocks(); - addMocksToContext(); - graphqlCodegen.codegen.mockReturnValue(MOCK_GENERATED_CODE); - }); - - for (const frontend in OUTPUT_PATHS) { - it(frontend + ': Should clear the output directory before generation if cleanGeneratedModelsDirectory is true', async () => { - MOCK_CONTEXT.amplify.getProjectConfig.mockReturnValue({ frontend: frontend }); - require('amplify-cli-core').FeatureFlags.getBoolean.mockImplementation((name, defaultValue) => { - if (name === 'codegen.useappsyncmodelgenplugin' || name === 'codegen.cleanGeneratedModelsDirectory') { - return true; - } - }); - - const outputDirectory = path.join(MOCK_PROJECT_ROOT, OUTPUT_PATHS[frontend]); - const preExistingFilePath = path.join(outputDirectory, MOCK_PRE_EXISTING_FILE); - createMockFS(outputDirectory); - - // assert output directory has a mock file to be cleared - expect(fs.readdirSync(outputDirectory).length).toEqual(1); - expect(fs.existsSync(preExistingFilePath)); - - await generateModels(MOCK_CONTEXT); - - // assert model generation succeeds - expect(graphqlCodegen.codegen).toBeCalled(); - - // assert that codegen generated in correct place - expect(fs.readdirSync(outputDirectory).length).toBeGreaterThan(0); - - // assert that the pre-existing file is deleted - expect(fs.existsSync(preExistingFilePath)).toBeFalsy; - }); - - it(frontend + ': Should not clear the output directory before generation if cleanGeneratedModelsDirectory is false', async () => { - MOCK_CONTEXT.amplify.getProjectConfig.mockReturnValue({ frontend: frontend }); - require('amplify-cli-core').FeatureFlags.getBoolean.mockImplementation((name, defaultValue) => { - if (name === 'codegen.useappsyncmodelgenplugin') { - return true; - } - if (name === 'codegen.cleanGeneratedModelsDirectory') { - return false; - } - }); - - const outputDirectory = path.join(MOCK_PROJECT_ROOT, OUTPUT_PATHS[frontend]); - const preExistingFilePath = path.join(outputDirectory, MOCK_PRE_EXISTING_FILE); - createMockFS(outputDirectory); - - // assert output directory has a mock file to be cleared - expect(fs.readdirSync(outputDirectory).length).toEqual(1); - expect(fs.existsSync(preExistingFilePath)); - - await generateModels(MOCK_CONTEXT); - - // assert model generation succeeds - expect(graphqlCodegen.codegen).toBeCalled(); - - // assert that codegen generated in correct place - expect(fs.readdirSync(outputDirectory).length).toBeGreaterThan(1); - - // assert that the pre-existing file is retained - expect(fs.existsSync(preExistingFilePath)).toBeTruthy; - }); - } - - function createMockFS(outputDirectory) { - // mock the input and output file structure - const schemaFilePath = path.join(MOCK_BACKEND_DIRECTORY, 'api', MOCK_PROJECT_NAME); - const mockedFiles = {}; - mockedFiles[schemaFilePath] = { - 'schema.graphql': ' type SimpleModel { id: ID! status: String } ', - }; - mockedFiles[outputDirectory] = {}; - mockedFiles[outputDirectory][MOCK_PRE_EXISTING_FILE] = 'A pre-existing mock file'; - mockFs(mockedFiles); - } - - afterEach(mockFs.restore); -}); - // Add models generation specific mocks to Amplify Context function addMocksToContext() { MOCK_CONTEXT.amplify.getEnvInfo.mockReturnValue({ projectPath: MOCK_PROJECT_ROOT }); diff --git a/packages/amplify-codegen/tests/utils/validateAmplifyFlutterCapableForNonModel.test.js b/packages/amplify-codegen/tests/utils/validateAmplifyFlutterCapableForNonModel.test.js index 84e6fa1b2..04e138469 100644 --- a/packages/amplify-codegen/tests/utils/validateAmplifyFlutterCapableForNonModel.test.js +++ b/packages/amplify-codegen/tests/utils/validateAmplifyFlutterCapableForNonModel.test.js @@ -1,14 +1,14 @@ const { - validateAmplifyFlutterCapableZeroThreeFeatures, - PUBSPEC_LOCK_FILE_NAME, - MINIMUM_VERSION_CONSTRAIN, + validateAmplifyFlutterCapableZeroThreeFeatures } = require('../../src/utils/validateAmplifyFlutterCapableZeroThreeFeatures'); +const { PUBSPEC_LOCK_FILE_NAME } = require('../../src/utils/validateAmplifyFlutterVersion'); const mockFs = require('mock-fs'); const { join } = require('path'); const yaml = require('js-yaml'); const MOCK_PROJECT_ROOT = 'project'; const MOCK_PUBSPEC_FILE_PATH = join(MOCK_PROJECT_ROOT, PUBSPEC_LOCK_FILE_NAME); +const MINIMUM_VERSION_CONSTRAINT = '>= 0.3.0 || >= 0.3.0-rc.2'; global.console = {log: jest.fn()} const mockErrorPrinter = console.log; @@ -17,7 +17,7 @@ describe('Validate amplify flutter version tests', () => { mockFs.restore(); }); - describe(`should return true if the resolved version meets the version constrain: ${MINIMUM_VERSION_CONSTRAIN}`, () => { + describe(`should return true if the resolved version meets the version constrain: ${MINIMUM_VERSION_CONSTRAINT}`, () => { ['0.3.0', '0.3.1', '1.0.0', '0.3.0-rc.2', '0.4.0', '0.4.0-rc.2'].forEach(version => { test(`when the resolved version is ${version}`, () => { const lockFile = { @@ -33,7 +33,7 @@ describe('Validate amplify flutter version tests', () => { }); }); - describe(`should return false if the resolved version does NOT meet the version constrain: ${MINIMUM_VERSION_CONSTRAIN}`, () => { + describe(`should return false if the resolved version does NOT meet the version constrain: ${MINIMUM_VERSION_CONSTRAINT}`, () => { ['0.2.0', '0.2.9', '0.3.0-rc.1'].forEach(version => { test(`when the resolved version is ${version}`, () => { const lockFile = { diff --git a/packages/appsync-modelgen-plugin/src/__tests__/visitors/__snapshots__/appsync-dart-visitor.test.ts.snap b/packages/appsync-modelgen-plugin/src/__tests__/visitors/__snapshots__/appsync-dart-visitor.test.ts.snap index 8b0401c13..8c7de8dd3 100644 --- a/packages/appsync-modelgen-plugin/src/__tests__/visitors/__snapshots__/appsync-dart-visitor.test.ts.snap +++ b/packages/appsync-modelgen-plugin/src/__tests__/visitors/__snapshots__/appsync-dart-visitor.test.ts.snap @@ -1,5 +1,685 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`AppSync Dart Visitor Amplify Core dependency used in imports Should use the amplify_core dependency if dartUpdateAmplifyCoreDependency is true 1`] = ` +"/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the \\"License\\"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the \\"license\\" file accompanying this file. This file is distributed +* on an \\"AS IS\\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'ModelProvider.dart'; +import 'package:amplify_core/amplify_core.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + + +/** This is an auto generated class representing the Post type in your schema. */ +@immutable +class Post extends Model { + static const classType = const _PostModelType(); + final String id; + final String? _title; + final int? _rating; + final PostStatus? _status; + final List? _comments; + + @override + getInstanceType() => classType; + + @override + String getId() { + return id; + } + + String get title { + try { + return _title!; + } catch(e) { + throw new AmplifyCodeGenModelException( + AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + int get rating { + try { + return _rating!; + } catch(e) { + throw new AmplifyCodeGenModelException( + AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + PostStatus get status { + try { + return _status!; + } catch(e) { + throw new AmplifyCodeGenModelException( + AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + List? get comments { + return _comments; + } + + const Post._internal({required this.id, required title, required rating, required status, comments}): _title = title, _rating = rating, _status = status, _comments = comments; + + factory Post({String? id, required String title, required int rating, required PostStatus status, List? comments}) { + return Post._internal( + id: id == null ? UUID.getUUID() : id, + title: title, + rating: rating, + status: status, + comments: comments != null ? List.unmodifiable(comments) : comments); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is Post && + id == other.id && + _title == other._title && + _rating == other._rating && + _status == other._status && + DeepCollectionEquality().equals(_comments, other._comments); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = new StringBuffer(); + + buffer.write(\\"Post {\\"); + buffer.write(\\"id=\\" + \\"$id\\" + \\", \\"); + buffer.write(\\"title=\\" + \\"$_title\\" + \\", \\"); + buffer.write(\\"rating=\\" + (_rating != null ? _rating!.toString() : \\"null\\") + \\", \\"); + buffer.write(\\"status=\\" + (_status != null ? enumToString(_status)! : \\"null\\")); + buffer.write(\\"}\\"); + + return buffer.toString(); + } + + Post copyWith({String? id, String? title, int? rating, PostStatus? status, List? comments}) { + return Post( + id: id ?? this.id, + title: title ?? this.title, + rating: rating ?? this.rating, + status: status ?? this.status, + comments: comments ?? this.comments); + } + + Post.fromJson(Map json) + : id = json['id'], + _title = json['title'], + _rating = (json['rating'] as num?)?.toInt(), + _status = enumFromString(json['status'], PostStatus.values), + _comments = json['comments'] is List + ? (json['comments'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => Comment.fromJson(new Map.from(e['serializedData']))) + .toList() + : null; + + Map toJson() => { + 'id': id, 'title': _title, 'rating': _rating, 'status': enumToString(_status), 'comments': _comments?.map((Comment? e) => e?.toJson()).toList() + }; + + static final QueryField ID = QueryField(fieldName: \\"post.id\\"); + static final QueryField TITLE = QueryField(fieldName: \\"title\\"); + static final QueryField RATING = QueryField(fieldName: \\"rating\\"); + static final QueryField STATUS = QueryField(fieldName: \\"status\\"); + static final QueryField COMMENTS = QueryField( + fieldName: \\"comments\\", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Comment).toString())); + static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = \\"Post\\"; + modelSchemaDefinition.pluralName = \\"Posts\\"; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Post.TITLE, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string) + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Post.RATING, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.int) + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Post.STATUS, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.enumeration) + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: Post.COMMENTS, + isRequired: false, + ofModelName: (Comment).toString(), + associatedKey: Comment.POST + )); + }); +} + +class _PostModelType extends ModelType { + const _PostModelType(); + + @override + Post fromJson(Map jsonData) { + return Post.fromJson(jsonData); + } +} + +/** This is an auto generated class representing the Comment type in your schema. */ +@immutable +class Comment extends Model { + static const classType = const _CommentModelType(); + final String id; + final Post? _post; + final String? _content; + + @override + getInstanceType() => classType; + + @override + String getId() { + return id; + } + + Post get post { + try { + return _post!; + } catch(e) { + throw new AmplifyCodeGenModelException( + AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + String get content { + try { + return _content!; + } catch(e) { + throw new AmplifyCodeGenModelException( + AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + const Comment._internal({required this.id, required post, required content}): _post = post, _content = content; + + factory Comment({String? id, required Post post, required String content}) { + return Comment._internal( + id: id == null ? UUID.getUUID() : id, + post: post, + content: content); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is Comment && + id == other.id && + _post == other._post && + _content == other._content; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = new StringBuffer(); + + buffer.write(\\"Comment {\\"); + buffer.write(\\"id=\\" + \\"$id\\" + \\", \\"); + buffer.write(\\"post=\\" + (_post != null ? _post!.toString() : \\"null\\") + \\", \\"); + buffer.write(\\"content=\\" + \\"$_content\\"); + buffer.write(\\"}\\"); + + return buffer.toString(); + } + + Comment copyWith({String? id, Post? post, String? content}) { + return Comment( + id: id ?? this.id, + post: post ?? this.post, + content: content ?? this.content); + } + + Comment.fromJson(Map json) + : id = json['id'], + _post = json['post']?['serializedData'] != null + ? Post.fromJson(new Map.from(json['post']['serializedData'])) + : null, + _content = json['content']; + + Map toJson() => { + 'id': id, 'post': _post?.toJson(), 'content': _content + }; + + static final QueryField ID = QueryField(fieldName: \\"comment.id\\"); + static final QueryField POST = QueryField( + fieldName: \\"post\\", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Post).toString())); + static final QueryField CONTENT = QueryField(fieldName: \\"content\\"); + static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = \\"Comment\\"; + modelSchemaDefinition.pluralName = \\"Comments\\"; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: Comment.POST, + isRequired: true, + targetName: \\"postID\\", + ofModelName: (Post).toString() + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Comment.CONTENT, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string) + )); + }); +} + +class _CommentModelType extends ModelType { + const _CommentModelType(); + + @override + Comment fromJson(Map jsonData) { + return Comment.fromJson(jsonData); + } +}" +`; + +exports[`AppSync Dart Visitor Amplify Core dependency used in imports Should use the older flutter datastore interface dependency if dartUpdateAmplifyCoreDependency is false 1`] = ` +"/* +* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the \\"License\\"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the \\"license\\" file accompanying this file. This file is distributed +* on an \\"AS IS\\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +// NOTE: This file is generated and may not follow lint rules defined in your app +// Generated files can be excluded from analysis in analysis_options.yaml +// For more info, see: https://dart.dev/guides/language/analysis-options#excluding-code-from-analysis + +// ignore_for_file: public_member_api_docs, file_names, unnecessary_new, prefer_if_null_operators, prefer_const_constructors, slash_for_doc_comments, annotate_overrides, non_constant_identifier_names, unnecessary_string_interpolations, prefer_adjacent_string_concatenation, unnecessary_const, dead_code + +import 'ModelProvider.dart'; +import 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + + +/** This is an auto generated class representing the Post type in your schema. */ +@immutable +class Post extends Model { + static const classType = const _PostModelType(); + final String id; + final String? _title; + final int? _rating; + final PostStatus? _status; + final List? _comments; + + @override + getInstanceType() => classType; + + @override + String getId() { + return id; + } + + String get title { + try { + return _title!; + } catch(e) { + throw new DataStoreException( + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + int get rating { + try { + return _rating!; + } catch(e) { + throw new DataStoreException( + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + PostStatus get status { + try { + return _status!; + } catch(e) { + throw new DataStoreException( + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + List? get comments { + return _comments; + } + + const Post._internal({required this.id, required title, required rating, required status, comments}): _title = title, _rating = rating, _status = status, _comments = comments; + + factory Post({String? id, required String title, required int rating, required PostStatus status, List? comments}) { + return Post._internal( + id: id == null ? UUID.getUUID() : id, + title: title, + rating: rating, + status: status, + comments: comments != null ? List.unmodifiable(comments) : comments); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is Post && + id == other.id && + _title == other._title && + _rating == other._rating && + _status == other._status && + DeepCollectionEquality().equals(_comments, other._comments); + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = new StringBuffer(); + + buffer.write(\\"Post {\\"); + buffer.write(\\"id=\\" + \\"$id\\" + \\", \\"); + buffer.write(\\"title=\\" + \\"$_title\\" + \\", \\"); + buffer.write(\\"rating=\\" + (_rating != null ? _rating!.toString() : \\"null\\") + \\", \\"); + buffer.write(\\"status=\\" + (_status != null ? enumToString(_status)! : \\"null\\")); + buffer.write(\\"}\\"); + + return buffer.toString(); + } + + Post copyWith({String? id, String? title, int? rating, PostStatus? status, List? comments}) { + return Post( + id: id ?? this.id, + title: title ?? this.title, + rating: rating ?? this.rating, + status: status ?? this.status, + comments: comments ?? this.comments); + } + + Post.fromJson(Map json) + : id = json['id'], + _title = json['title'], + _rating = (json['rating'] as num?)?.toInt(), + _status = enumFromString(json['status'], PostStatus.values), + _comments = json['comments'] is List + ? (json['comments'] as List) + .where((e) => e?['serializedData'] != null) + .map((e) => Comment.fromJson(new Map.from(e['serializedData']))) + .toList() + : null; + + Map toJson() => { + 'id': id, 'title': _title, 'rating': _rating, 'status': enumToString(_status), 'comments': _comments?.map((Comment? e) => e?.toJson()).toList() + }; + + static final QueryField ID = QueryField(fieldName: \\"post.id\\"); + static final QueryField TITLE = QueryField(fieldName: \\"title\\"); + static final QueryField RATING = QueryField(fieldName: \\"rating\\"); + static final QueryField STATUS = QueryField(fieldName: \\"status\\"); + static final QueryField COMMENTS = QueryField( + fieldName: \\"comments\\", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Comment).toString())); + static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = \\"Post\\"; + modelSchemaDefinition.pluralName = \\"Posts\\"; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Post.TITLE, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string) + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Post.RATING, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.int) + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Post.STATUS, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.enumeration) + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.hasMany( + key: Post.COMMENTS, + isRequired: false, + ofModelName: (Comment).toString(), + associatedKey: Comment.POST + )); + }); +} + +class _PostModelType extends ModelType { + const _PostModelType(); + + @override + Post fromJson(Map jsonData) { + return Post.fromJson(jsonData); + } +} + +/** This is an auto generated class representing the Comment type in your schema. */ +@immutable +class Comment extends Model { + static const classType = const _CommentModelType(); + final String id; + final Post? _post; + final String? _content; + + @override + getInstanceType() => classType; + + @override + String getId() { + return id; + } + + Post get post { + try { + return _post!; + } catch(e) { + throw new DataStoreException( + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + String get content { + try { + return _content!; + } catch(e) { + throw new DataStoreException( + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); + } + } + + const Comment._internal({required this.id, required post, required content}): _post = post, _content = content; + + factory Comment({String? id, required Post post, required String content}) { + return Comment._internal( + id: id == null ? UUID.getUUID() : id, + post: post, + content: content); + } + + bool equals(Object other) { + return this == other; + } + + @override + bool operator ==(Object other) { + if (identical(other, this)) return true; + return other is Comment && + id == other.id && + _post == other._post && + _content == other._content; + } + + @override + int get hashCode => toString().hashCode; + + @override + String toString() { + var buffer = new StringBuffer(); + + buffer.write(\\"Comment {\\"); + buffer.write(\\"id=\\" + \\"$id\\" + \\", \\"); + buffer.write(\\"post=\\" + (_post != null ? _post!.toString() : \\"null\\") + \\", \\"); + buffer.write(\\"content=\\" + \\"$_content\\"); + buffer.write(\\"}\\"); + + return buffer.toString(); + } + + Comment copyWith({String? id, Post? post, String? content}) { + return Comment( + id: id ?? this.id, + post: post ?? this.post, + content: content ?? this.content); + } + + Comment.fromJson(Map json) + : id = json['id'], + _post = json['post']?['serializedData'] != null + ? Post.fromJson(new Map.from(json['post']['serializedData'])) + : null, + _content = json['content']; + + Map toJson() => { + 'id': id, 'post': _post?.toJson(), 'content': _content + }; + + static final QueryField ID = QueryField(fieldName: \\"comment.id\\"); + static final QueryField POST = QueryField( + fieldName: \\"post\\", + fieldType: ModelFieldType(ModelFieldTypeEnum.model, ofModelName: (Post).toString())); + static final QueryField CONTENT = QueryField(fieldName: \\"content\\"); + static var schema = Model.defineSchema(define: (ModelSchemaDefinition modelSchemaDefinition) { + modelSchemaDefinition.name = \\"Comment\\"; + modelSchemaDefinition.pluralName = \\"Comments\\"; + + modelSchemaDefinition.addField(ModelFieldDefinition.id()); + + modelSchemaDefinition.addField(ModelFieldDefinition.belongsTo( + key: Comment.POST, + isRequired: true, + targetName: \\"postID\\", + ofModelName: (Post).toString() + )); + + modelSchemaDefinition.addField(ModelFieldDefinition.field( + key: Comment.CONTENT, + isRequired: true, + ofType: ModelFieldType(ModelFieldTypeEnum.string) + )); + }); +} + +class _CommentModelType extends ModelType { + const _CommentModelType(); + + @override + Comment fromJson(Map jsonData) { + return Comment.fromJson(jsonData); + } +}" +`; + exports[`AppSync Dart Visitor CustomType (non-model) Tests should generated correct dart class for Address with nullsafety disabled 1`] = ` "/* * Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. @@ -191,11 +871,11 @@ class Address { return _line1!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -208,11 +888,11 @@ class Address { return _city!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -221,11 +901,11 @@ class Address { return _state!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -234,11 +914,11 @@ class Address { return _postalCode!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -519,11 +1199,11 @@ class Contact { return _contactName!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -532,11 +1212,11 @@ class Contact { return _phone!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -968,11 +1648,11 @@ class Person extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -981,11 +1661,11 @@ class Person extends Model { return _phone!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2583,11 +3263,11 @@ class Post extends Model { return _title!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2725,11 +3405,11 @@ class Tag extends Model { return _label!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2851,11 +3531,11 @@ class PostTags extends Model { return _post!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2864,11 +3544,11 @@ class PostTags extends Model { return _tag!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -3425,11 +4105,11 @@ class TodoWithAuth extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -5937,11 +6617,11 @@ class Blog extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6095,11 +6775,11 @@ class Comment extends Model { return _content!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6245,11 +6925,11 @@ class Post extends Model { return _title!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6424,11 +7104,11 @@ class TestModel extends Model { return _floatVal!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6441,11 +7121,11 @@ class TestModel extends Model { return _floatList!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6458,11 +7138,11 @@ class TestModel extends Model { return _nullableFloatList!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6667,11 +7347,11 @@ class TestModel extends Model { return _floatVal!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6684,11 +7364,11 @@ class TestModel extends Model { return _floatList!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6701,11 +7381,11 @@ class TestModel extends Model { return _nullableFloatList!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6718,11 +7398,11 @@ class TestModel extends Model { return _intVal!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6735,11 +7415,11 @@ class TestModel extends Model { return _intList!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -6752,11 +7432,11 @@ class TestModel extends Model { return _nullableIntList!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } diff --git a/packages/appsync-modelgen-plugin/src/__tests__/visitors/appsync-dart-visitor.test.ts b/packages/appsync-modelgen-plugin/src/__tests__/visitors/appsync-dart-visitor.test.ts index 9d1f5f0ae..b5e44c20c 100644 --- a/packages/appsync-modelgen-plugin/src/__tests__/visitors/appsync-dart-visitor.test.ts +++ b/packages/appsync-modelgen-plugin/src/__tests__/visitors/appsync-dart-visitor.test.ts @@ -16,6 +16,7 @@ const getVisitor = ({ enableDartZeroThreeFeatures = false, isTimestampFieldsAdded = false, transformerVersion = 1, + dartUpdateAmplifyCoreDependency = false }: { schema: string; selectedType?: string; @@ -24,6 +25,7 @@ const getVisitor = ({ enableDartZeroThreeFeatures?: boolean; isTimestampFieldsAdded?: boolean; transformerVersion?: number; + dartUpdateAmplifyCoreDependency?: boolean; }) => { const ast = parse(schema); const builtSchema = buildSchemaWithDirectives(schema); @@ -37,6 +39,7 @@ const getVisitor = ({ enableDartZeroThreeFeatures, isTimestampFieldsAdded, transformerVersion, + dartUpdateAmplifyCoreDependency }, { selectedType, generate }, ); @@ -640,4 +643,39 @@ describe('AppSync Dart Visitor', () => { expect(generatedCode).toMatchSnapshot(); }); }); + + describe('Amplify Core dependency used in imports', () => { + const schema = /* GraphQL */` + enum PostStatus { + ACTIVE + INACTIVE + } + + type Post @model { + id: ID! + title: String! + rating: Int! + status: PostStatus! + # New field with @hasMany + comments: [Comment] @hasMany(indexName: "byPost", fields: ["id"]) + } + + # New model + type Comment @model { + id: ID! + postID: ID! @index(name: "byPost", sortKeyFields: ["content"]) + post: Post! @belongsTo(fields: ["postID"]) + content: String! + } + `; + it('Should use the older flutter datastore interface dependency if dartUpdateAmplifyCoreDependency is false', () => { + const generatedCode = getVisitor({ schema, transformerVersion: 2, enableDartNullSafety: true }).generate(); + expect(generatedCode).toMatchSnapshot(); + }); + + it('Should use the amplify_core dependency if dartUpdateAmplifyCoreDependency is true', () => { + const generatedCode = getVisitor({ schema, transformerVersion: 2, enableDartNullSafety: true, dartUpdateAmplifyCoreDependency: true }).generate(); + expect(generatedCode).toMatchSnapshot(); + }); + }); }); diff --git a/packages/appsync-modelgen-plugin/src/__tests__/visitors/gqlv2-regression-tests/__snapshots__/appsync-dart-visitor.test.ts.snap b/packages/appsync-modelgen-plugin/src/__tests__/visitors/gqlv2-regression-tests/__snapshots__/appsync-dart-visitor.test.ts.snap index b2900f6cf..5537d7641 100644 --- a/packages/appsync-modelgen-plugin/src/__tests__/visitors/gqlv2-regression-tests/__snapshots__/appsync-dart-visitor.test.ts.snap +++ b/packages/appsync-modelgen-plugin/src/__tests__/visitors/gqlv2-regression-tests/__snapshots__/appsync-dart-visitor.test.ts.snap @@ -49,11 +49,11 @@ class Post extends Model { return _title!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -203,11 +203,11 @@ class Comment extends Model { return _content!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -514,11 +514,11 @@ class Team2 extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -667,11 +667,11 @@ class Blog7V2 extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -823,11 +823,11 @@ class Post7V2 extends Model { return _title!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -1300,11 +1300,11 @@ class Team extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -1454,11 +1454,11 @@ class Post extends Model { return _title!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -1625,11 +1625,11 @@ class Tag extends Model { return _label!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -1900,11 +1900,11 @@ class Post2 extends Model { return _title!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2053,11 +2053,11 @@ class Comment2 extends Model { return _postID!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2066,11 +2066,11 @@ class Comment2 extends Model { return _content!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2366,11 +2366,11 @@ class Team2 extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2498,11 +2498,11 @@ class Post extends Model { return _title!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2651,11 +2651,11 @@ class Comment extends Model { return _content!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -2955,11 +2955,11 @@ class Team extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -3086,11 +3086,11 @@ class Customer extends Model { return _name!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } @@ -3103,11 +3103,11 @@ class Customer extends Model { return _accountRepresentativeID!; } catch(e) { throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() - ); + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + ); } } diff --git a/packages/appsync-modelgen-plugin/src/configs/dart-config.ts b/packages/appsync-modelgen-plugin/src/configs/dart-config.ts index ef7904135..6f1e255da 100644 --- a/packages/appsync-modelgen-plugin/src/configs/dart-config.ts +++ b/packages/appsync-modelgen-plugin/src/configs/dart-config.ts @@ -1,8 +1,7 @@ export const LOADER_CLASS_NAME = 'ModelProvider'; -export const BASE_IMPORT_PACKAGES = [ - 'package:flutter/foundation.dart', - 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface.dart', -]; +export const FLUTTER_DATASTORE_PLUGIN_INTERFACE_IMPORT = 'package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface'; +export const FLUTTER_AMPLIFY_CORE_IMPORT = 'package:amplify_core/amplify_core'; +export const BASE_IMPORT_PACKAGES = ['package:flutter/foundation.dart']; export const COLLECTION_PACKAGE = 'package:collection/collection.dart'; export const CUSTOM_LINTS_MESSAGE = `// NOTE: This file is generated and may not follow lint rules defined in your app diff --git a/packages/appsync-modelgen-plugin/src/visitors/appsync-dart-visitor.ts b/packages/appsync-modelgen-plugin/src/visitors/appsync-dart-visitor.ts index abb750354..86bb05674 100644 --- a/packages/appsync-modelgen-plugin/src/visitors/appsync-dart-visitor.ts +++ b/packages/appsync-modelgen-plugin/src/visitors/appsync-dart-visitor.ts @@ -14,6 +14,8 @@ import { printWarning } from '../utils/warn'; import { LOADER_CLASS_NAME, BASE_IMPORT_PACKAGES, + FLUTTER_AMPLIFY_CORE_IMPORT, + FLUTTER_DATASTORE_PLUGIN_INTERFACE_IMPORT, COLLECTION_PACKAGE, DART_RESERVED_KEYWORDS, typeToEnumMap, @@ -26,13 +28,6 @@ import { lowerCaseFirst } from 'lower-case-first'; import { GraphQLSchema } from 'graphql'; import { DART_SCALAR_MAP } from '../scalars'; -const FORCE_CAST_EXCEPTION = `throw new DataStoreException( - DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, - recoverySuggestion: - DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, - underlyingException: e.toString() -);` - export interface RawAppSyncModelDartConfig extends RawAppSyncModelConfig { /** * @name directives @@ -40,6 +35,7 @@ export interface RawAppSyncModelDartConfig extends RawAppSyncModelConfig { * @description optional, defines if dart model files are generated with null safety feature. */ enableDartNullSafety?: boolean; + /** * @name directives * @type boolean @@ -48,12 +44,20 @@ export interface RawAppSyncModelDartConfig extends RawAppSyncModelConfig { * - Emit auth provider information * - Generate timestamp fields */ - enableDartZeroThreeFeatures?: boolean; + enableDartZeroThreeFeatures?: boolean; + + /** + * @name directives + * @type boolean + * @description optional, determines if the generated models import amplify_core rather than amplify_datastore_plugin_interface + */ + dartUpdateAmplifyCoreDependency?: boolean; } export interface ParsedAppSyncModelDartConfig extends ParsedAppSyncModelConfig { enableDartNullSafety: boolean; enableDartZeroThreeFeatures: boolean; + dartUpdateAmplifyCoreDependency: boolean; } export class AppSyncModelDartVisitor< TRawConfig extends RawAppSyncModelDartConfig = RawAppSyncModelDartConfig, @@ -68,6 +72,7 @@ export class AppSyncModelDartVisitor< super(schema, rawConfig, additionalConfig, defaultScalars); this._parsedConfig.enableDartNullSafety = rawConfig.enableDartNullSafety || false; this._parsedConfig.enableDartZeroThreeFeatures = rawConfig.enableDartZeroThreeFeatures || false; + this._parsedConfig.dartUpdateAmplifyCoreDependency = rawConfig.dartUpdateAmplifyCoreDependency || false; } generate(): string { @@ -124,7 +129,9 @@ export class AppSyncModelDartVisitor< //Ignore for file result.push(IGNORE_FOR_FILE); //Packages for import - const packageImports: string[] = ['package:amplify_datastore_plugin_interface/amplify_datastore_plugin_interface', ...modelNames, ...nonModelNames]; + const flutterDatastorePackage = + this.config.dartUpdateAmplifyCoreDependency === true ? FLUTTER_AMPLIFY_CORE_IMPORT : FLUTTER_DATASTORE_PLUGIN_INTERFACE_IMPORT; + const packageImports: string[] = [flutterDatastorePackage, ...modelNames, ...nonModelNames]; //Packages for export const packageExports: string[] = [...exportClasses]; //Block body @@ -145,7 +152,7 @@ export class AppSyncModelDartVisitor< ['override'], ); } - //getModelTypeByModelName + //getModelTypeByModelName if (modelNames.length) { const getModelTypeImplStr = [ 'switch(modelName) {', @@ -235,7 +242,7 @@ export class AppSyncModelDartVisitor< protected generatePackageHeader(): string { let usingCollection = false; let usingOtherClass = false; - Object.entries({...this.getSelectedModels(), ...this.getSelectedNonModels()}).forEach(([name, model]) => { + Object.entries({ ...this.getSelectedModels(), ...this.getSelectedNonModels() }).forEach(([name, model]) => { model.fields.forEach(f => { if (f.isList) { usingCollection = true; @@ -245,8 +252,15 @@ export class AppSyncModelDartVisitor< } }); }); + const flutterDatastorePackage = + this.config.dartUpdateAmplifyCoreDependency === true ? FLUTTER_AMPLIFY_CORE_IMPORT : FLUTTER_DATASTORE_PLUGIN_INTERFACE_IMPORT; return ( - [...BASE_IMPORT_PACKAGES, usingCollection ? COLLECTION_PACKAGE : '', usingOtherClass ? `${LOADER_CLASS_NAME}.dart` : ''] + [ + ...BASE_IMPORT_PACKAGES, + `${flutterDatastorePackage}.dart`, + usingCollection ? COLLECTION_PACKAGE : '', + usingOtherClass ? `${LOADER_CLASS_NAME}.dart` : '', + ] .filter(f => f) .sort() .map(pckg => `import '${pckg}';`) @@ -361,20 +375,28 @@ export class AppSyncModelDartVisitor< } //other getters if (this.isNullSafety()) { + let forceCastException = `throw new DataStoreException( + DataStoreExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + DataStoreExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + );`; + if (this.config.dartUpdateAmplifyCoreDependency === true) { + forceCastException = `throw new AmplifyCodeGenModelException( + AmplifyExceptionMessages.codeGenRequiredFieldForceCastExceptionMessage, + recoverySuggestion: + AmplifyExceptionMessages.codeGenRequiredFieldForceCastRecoverySuggestion, + underlyingException: e.toString() + );`; + } + model.fields.forEach(field => { const fieldName = this.getFieldName(field); const fieldType = this.getNativeType(field); const returnType = this.isFieldRequired(field) ? fieldType : `${fieldType}?`; + const getterImpl = this.isFieldRequired(field) - ? [ - `try {`, - indent(`return _${fieldName}!;`), - '} catch(e) {', - indent( - FORCE_CAST_EXCEPTION - ), - '}', - ].join('\n') + ? [`try {`, indent(`return _${fieldName}!;`), '} catch(e) {', indent(forceCastException), '}'].join('\n') : `return _${fieldName};`; if (fieldName !== 'id') { declarationBlock.addClassMethod(`get ${fieldName}`, returnType, undefined, getterImpl, { isGetter: true, isBlock: true }); @@ -595,16 +617,20 @@ export class AppSyncModelDartVisitor< indent(`? (json['${varName}'] as List)`), this.isNullSafety() ? indent(`.where((e) => e != null)`, 2) : undefined, indent( - `.map((e) => ${this.getNativeType({ ...field, isList: false })}.fromJson(new Map.from(${this.isNonModelType(field) ? 'e[\'serializedData\']' : 'e'})))`, + `.map((e) => ${this.getNativeType({ ...field, isList: false })}.fromJson(new Map.from(${ + this.isNonModelType(field) ? "e['serializedData']" : 'e' + })))`, 2, ), indent(`.toList()`, 2), indent(`: null`), - ].filter((e) => e !== undefined).join('\n'); + ] + .filter(e => e !== undefined) + .join('\n'); } // single non-model i.e. embedded return [ - `${fieldName} = json['${varName}']${this.isNullSafety() ? `?['serializedData']`:''} != null`, + `${fieldName} = json['${varName}']${this.isNullSafety() ? `?['serializedData']` : ''} != null`, indent( `? ${this.getNativeType(field)}.fromJson(new Map.from(json['${varName}']${ this.isNullSafety() ? `['serializedData']` : '' @@ -871,8 +897,13 @@ export class AppSyncModelDartVisitor< .join(',\n'); fieldsToAdd.push( - [`ModelFieldDefinition.${ofType === '.embedded' ? 'embedded' : (field.isReadOnly ? 'nonQueryField' : 'field')}(`, indentMultiline(fieldParam), ')'].join('\n'), - ); } + [ + `ModelFieldDefinition.${ofType === '.embedded' ? 'embedded' : field.isReadOnly ? 'nonQueryField' : 'field'}(`, + indentMultiline(fieldParam), + ')', + ].join('\n'), + ); + } }); return fieldsToAdd.map(field => `modelSchemaDefinition.addField(${field});`).join('\n\n'); } @@ -907,9 +938,13 @@ export class AppSyncModelDartVisitor< `isRequired: ${this.isFieldRequired(field)}`, field.isList ? 'isArray: true' : '', ofTypeStr, - ].filter(f => f).join(',\n') + ] + .filter(f => f) + .join(',\n'); - fieldsToAdd.push([`ModelFieldDefinition.${ofType === '.embedded' ? 'embedded' : 'customTypeField'}(`, indentMultiline(fieldParam), ')'].join('\n')); + fieldsToAdd.push( + [`ModelFieldDefinition.${ofType === '.embedded' ? 'embedded' : 'customTypeField'}(`, indentMultiline(fieldParam), ')'].join('\n'), + ); }); return fieldsToAdd.map(field => `modelSchemaDefinition.addField(${field});`).join('\n\n');