micimize / graphql-to-dart

generate dart classes and respective JsonSerializable transcoders
42 stars 8 forks source link

Override schema types of specific fields with custom scalars #7

Closed fvisticot closed 4 years ago

fvisticot commented 5 years ago

By example, the Schema I'm using is not managing date field properly and those date field are managed as String. I would like to overload type of some fields with configuration.

By Exemple: From Schema: creationDate String

I would like to transform to creationDate DateTime

micimize commented 5 years ago

Not possible to do exactly that right now, but you could use the conditional mixin config to do something similar:

  mixins:
  # add the mixin {{name}} when the given fields are found in a model
  - when:
      fields:
      - creationDate
    name: FixDate

where FixDate is something like

class FixDate {
  String creationDate;
  DateTime get created => DateTime.parse(creationDate).toLocal();
  set created(DateTime date) => creationDate = date.toUtc().toIso8601String();
}
fvisticot commented 5 years ago

Not possible to do exactly that right now, but you could use the conditional mixin config to do something similar:

  mixins:
  # add the mixin {{name}} when the given fields are found in a model
  - when:
      fields:
      - creationDate
    name: FixDate

where FixDate is something like

class Entity {
  String creationDate;
  get creationDateFix => dateFromJson(creationDate);
}

Sorry to disturb you again and big tx for your support

micimize commented 5 years ago

sorry, Entity was a typo, should be FixDate. So, you can add a ./base.dart to parts and place it there, next to your generates target. So, if you're generating lib/serializers/graphql.dart, this should work:

// in lib/serializers/base.dart
class FixDate {
  String creationDate;

  DateTime get created => DateTime.parse(creationDate).toLocal();

  set created(DateTime date) => creationDate = date.toUtc().toIso8601String();
}

Config section of codegen.yml:

config:
  mixins:
  # add the mixin {{name}} when the given fields are found in a model
  - when:
      fields:
      - creationDate
    name: FixDate
  parts:
  - "./base.dart"
  - "./graphql.g.dart"