medz / prisma-dart

Prisma Client Dart is an auto-generated type-safe ORM. It uses Prisma Engine as the data access layer and is as consistent as possible with the Prisma Client JS/TS APIs.
https://prisma.pub
BSD 3-Clause "New" or "Revised" License
436 stars 29 forks source link

add copyWith method to models #403

Open kidusdev opened 5 days ago

kidusdev commented 5 days ago

Hy

I encounter this redundant code in various places of my application

final e = someMonthlyExpense;

 Expenses(
      id: e.amount == amount ? e.id : 0,
      amount: e.amount/30,
      period: e.period,
      reason: e.reason,
      startDate: e.startDate,y
      endDate: e.endDate,
      createdAt: e.createdAt,
    );

here in the above example i am grouping expenses to their lower expense period. its like if i have 1500$ house rent expense and if i have to cover that in a month how much should i earn daily and its obviously 50$ and the same for yearly expense. and the new value is treated as daily expense and the only difference is the amount. it would be great if we can do this instead;

final e = someMonthlyExpense;

final dailyExpense = e.copyWith(amount: e.amount/30);
// this ^ is better and concise code than this
/**
 Expenses(
      id: e.amount == amount ? e.id : 0,
      amount: e.amount/30,
      period: e.period,
      reason: e.reason,
      startDate: e.startDate,y
      endDate: e.endDate,
      createdAt: e.createdAt,
    );
*/

i tried

Expenses.fromJson({...e.toJson(), "amount": e.amount! * difference});

it doesn't work because the toJson method changes the createdAt to String then when i use the fromJson method is complains type 'String' is not a subtype of type 'DateTime?'. the DateTime Field in the models should parse a String and DateTime types

NB. i added the copyWith method to the models but it resets everytime i change the schema.prisma and generate a client

medz commented 5 days ago

I'll take some time to look at it. In fact, another problem has arisen. FromJson does not handle time strings correctly.

kidusdev commented 5 days ago

another problem has arisen. FromJson does not handle time strings correctly.

Yeah, i encountered that many time i added an extra step to parse string to dates and assigning it to the model in my apps before mentioning it here.

medz commented 4 days ago

@kidusdev Fixed an issue with <model>.fromJson not being able to handle DateTime.

I actually want to wait for the macros (which are coming soon) to add the copyWith feature

Because along with that, we should not only add fromJson/toJson/copyWith to model, but also to input types. So that types can be published independently for the front end to use it.