Skip to content

Feature: copyWith() method for entities #748

Closed

Description

@wstrange

A minor feature request for quality of life: Generate a copyWith method on entities. Makes it easy to clone objects.

Lateral thought: Generate models using freezed as the base. Provides copyWith, immutability, and json serialization.

Activity

  1. added
    enhancement
    on Mar 20, 2023
  2. vlidholt commented on Mar 20, 2023

    @vlidholt
    Collaborator

    This is a feature we should add.

    For reference, Serverpod is compatible with Freezed if you prefer that for your serialization. More info here:
    https://docs.serverpod.dev/concepts/serialization#custom-serializable-objects

  3. wstrange commented on Mar 20, 2023

    @wstrange
    ContributorAuthor

    WDYT about using Freezed as the base for generated models? You'd get copyWIth for "free". It might be a breaking change though...

  4. pro100andrey commented on May 30, 2023

    @pro100andrey
    Contributor

    @vlidholt Hi,

    I'm almost done with this functionality, and I will submit the pull request today. Do you have any preferences or specific requirements for it?

    class: TestEntry
    # table: test_entry
    fields:
      userId: int
      description: String
      tags: List<String>
      likes: List<int>

    result file for client:

    /* AUTOMATICALLY GENERATED CODE DO NOT MODIFY */
    /*   To generate run: "serverpod generate"    */
    
    // ignore_for_file: library_private_types_in_public_api
    // ignore_for_file: public_member_api_docs
    // ignore_for_file: implementation_imports
    
    // ignore_for_file: no_leading_underscores_for_library_prefixes
    import 'package:serverpod_client/serverpod_client.dart' as _i1;
    import 'package:collection/collection.dart' as _i2;
    
    /// An entry in the database for an uploaded file.
    class TestEntry extends _i1.SerializableEntity {
      TestEntry({
        required this.userId,
        required this.description,
        required this.tags,
        required this.likes,
      });
    
      factory TestEntry.fromJson(
        Map<String, dynamic> jsonSerialization,
        _i1.SerializationManager serializationManager,
      ) {
        return TestEntry(
          userId:
              serializationManager.deserialize<int>(jsonSerialization['userId']),
          description: serializationManager
              .deserialize<String>(jsonSerialization['description']),
          tags: serializationManager
              .deserialize<List<String>>(jsonSerialization['tags']),
          likes: serializationManager
              .deserialize<List<int>>(jsonSerialization['likes']),
        );
      }
    
      int userId;
    
      String description;
    
      List<String> tags;
    
      List<int> likes;
    
      @override
      Map<String, dynamic> toJson() {
        return {
          'userId': userId,
          'description': description,
          'tags': tags,
          'likes': likes,
        };
      }
    
      @override
      int get hashCode => Object.hash(
            userId,
            description,
            const _i2.DeepCollectionEquality().hash(tags),
            const _i2.DeepCollectionEquality().hash(likes),
          );
    
      TestEntry copyWith({
        int? userId,
        String? description,
        List<String>? tags,
        List<int>? likes,
      }) {
        return TestEntry(
          userId: userId ?? this.userId,
          description: description ?? this.description,
          tags: tags ?? this.tags,
          likes: likes ?? this.likes,
        );
      }
    }

    The only thing left is to implement the == operator.

    Thanks!

  5. moved this to Version 1.2 - Nice to have 🥳 in Serverpod Frameworkson Jul 12, 2023
  6. vlidholt commented on Jul 12, 2023

    @vlidholt
    Collaborator

    There is a good starting point for doing this here:
    #976

  7. jason-downs commented on Aug 16, 2023

    @jason-downs

    The problem with using the Custom Serializable Objects approach is that in that case it can't be connected to the database. Or am I missing something? As far as I can tell only with the classes defined in yaml can they be used in the postgres tables.

    So it seems currenlty my dilemma is I can either have classes that are equatable via freezed/equatable etc, or I can have them compatible with the built-in database, but not both. I'm trying to move a pre-existing large flutter project over to serverpod and this is basically a blocker for me until fixed, becuase I'm heavily dependent on classes being equatable (via Equatable package) for unit tests and some business logic that would be hard to change.

    I hope this can be dealt with soon as I don't know what to do for now except being super-hacky and adding Equatable to the classes in the generated code after each serverpod generate which obviously is not workable long-term.

  8. moved this from Version 1.2 - Nice to have 🥳 to Done 🚀 in Serverpod Frameworkson Sep 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions