Skip to content

Commit

Permalink
feat(api): add copyWith to GraphQLRequest (#4365)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarlonJD authored Feb 6, 2024
1 parent 3859b16 commit 42990f5
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,39 @@ class GraphQLRequest<T> with AWSSerializable<Map<String, Object?>> {
'authorizationMode': authorizationMode!.name,
if (decodePath != null) 'decodePath': decodePath,
};

/// Creates a copy of this request with the given fields replaced with the new values.
/// If no new value is given, the old value is used.
///
/// ```dart
/// final original = ModelQueries.list(
/// Blog.classType,
/// );
/// final modified = original.copyWith(
/// document: yourCustomQuery,
/// );
/// ```
///
/// Useful in advanced scenarios where you want to modify the request before sending it.
///
/// See https://docs.amplify.aws/lib/graphqlapi/advanced-workflows/q/platform/flutter/.
GraphQLRequest<T> copyWith({
String? document,
String? apiName,
Map<String, String>? headers,
APIAuthorizationType? authorizationMode,
Map<String, dynamic>? variables,
String? decodePath,
ModelType? modelType,
}) {
return GraphQLRequest<T>(
document: document ?? this.document,
apiName: apiName ?? this.apiName,
headers: headers ?? this.headers,
authorizationMode: authorizationMode ?? this.authorizationMode,
variables: variables ?? this.variables,
decodePath: decodePath ?? this.decodePath,
modelType: modelType ?? this.modelType,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,37 @@ void main({bool useExistingTestUser = false}) {
expect(postFromResponse?.title, title);
});

testWidgets('should copyWith request', (WidgetTester tester) async {
final title = 'Lorem Ipsum Test Post: ${uuid()}';
const rating = 0;
final createdPost = await addPostAndBlog(title, rating);
final blogId = createdPost.blog?.id;

// Original request with mock id
final req = ModelQueries.list(
Post.classType,
where: Post.BLOG.eq(uuid()),
limit: _limit,
);

// Copy request with actual blog id
final copiedRequest = req.copyWith(
variables: {
...req.variables,
'filter': {
'blogID': {'eq': blogId},
},
},
);
final res = await Amplify.API.query(request: copiedRequest).response;
final postFromResponse = res.data?.items[0];

expect(res, hasNoGraphQLErrors);
expect(postFromResponse?.blog?.id, isNotNull);
expect(postFromResponse?.blog?.id, blogId);
expect(postFromResponse?.title, title);
});

testWidgets('should decode a custom list request',
(WidgetTester tester) async {
final name = 'Lorem Ipsum Test Blog: ${uuid()}';
Expand Down

0 comments on commit 42990f5

Please sign in to comment.