Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch from a model M1 to a model M2 #1079

Closed
ThomasDevApps opened this issue Apr 28, 2024 · 1 comment
Closed

Switch from a model M1 to a model M2 #1079

ThomasDevApps opened this issue Apr 28, 2024 · 1 comment
Assignees
Labels
enhancement New feature or request

Comments

@ThomasDevApps
Copy link

ThomasDevApps commented Apr 28, 2024

Hello,

The models generated by Freezed are very useful for many developers, including me ! So first of all, thank you for this package.
However, there's one feature that might be nice to implement, that's the ability to switch from a model M1 to a model M2 :

@freezed
sealed class User with _$User {
  const factory User.toInsert({
    required String username,
  }) = UserToInsert;

  const factory User.data({
    required String id,
    required String username,
    required DateTime createdAt,
  }) = UserData;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

We will therefore have a method for switching from UserToInsert to UserData and vice versa.

Note : Similar fields do not need to be redefined.

const userToInsert = UserToInsert(username: 'toto');
final newUserData = userToInsert.toUserData(
  id: '1-e5',
  // No need to redefine username
  createdAt: DateTime.now(),
);
const userData = UserData(
  id: '4-f8',
  username: 'toto',
  createdAt: DateTime.now(),
);
final newUserToInsert = userData.toUserToInsert();

Currently the workaround is :

extension UserToDataExtension on UserData {
  UserToInsert toUserToInsert() {
    return UserToInsert(username: username);
  }
}
extension UserToInsertExtension on UserToInsert {
  UserData toUserData({
    required String id,
    required DateTime createdAt,
  }) {
    return UserData(
      id: id,
      username: username,
      createdAt: createdAt,
    );
  }
}

Using this method, you can have models for insertions into databases (where the id and other fields are given directly in the backend) and easily convert them into a "normal" model.

However, static metaprogramming may be mandatory for this type of method.

@rrousselGit
Copy link
Owner

This sort of logic isn't simple to implement, because it's common that two models aren't fully compatible.

The code-generator wouldn't know how to solve the possible conflict. Doing things by hand is generally the best here I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants