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
447 stars 30 forks source link

Type casting in model.fromJson map #417

Open kidusdev opened 2 weeks ago

kidusdev commented 2 weeks ago
Sale.fromJson(s)

factory Sale.fromJson(Map json) => Sale(
        id: json['id'],
        quantity: json['quantity'],
        // eg. quantity: double.tryParse("${json['quantity']}") 
       // this way it can convert String, int, num to double so you don't have to worry about the api data type 
        unitPrice: json['unit_price'],
        createdAt: switch (json['created_at']) {
          DateTime value => value,
          String value => DateTime.parse(value),
          _ => json['created_at']
        },
      );

in this example the Map json data is coming from an api but the quantity is either double or int but the model's quantity field only accepts double. can we parse and cast it to double or are there any other available methods to deal with. i could cast every field but it would be if we have this feature inside the model instead of all over my project

medz commented 2 weeks ago

I am waiting for the official release of macros. Previously, FromJson and ToJson relied on code generate.