Created
June 7, 2023 00:18
-
-
Save lukepighetti/cf0452ff066c7ea5372e83b3e8860462 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// we need this in core dart so all these serialization packages can use it | |
// this enables generalized solutions for storage, messaging, tasks, etc | |
abstract interface class JsonCoder<T> { | |
String toJson(T payload); | |
T fromJson(String payload); | |
} | |
// then we can create generalized packages for things like storage | |
/// ```dart | |
/// final box1 = Storage(MyFreezedDataClass.coder); | |
/// final box2 = Storage(MyBuiltValue.coder); | |
/// final box3 = Storage(MyDartMappable.coder); | |
/// final box4 = Storage(MyHandCrafted.coder); | |
/// ``` | |
class BasedStorage { | |
void store<T>(String key, JsonCoder<T> object) { | |
///... | |
} | |
T fetch<T extends JsonCoder>(String key) { | |
/// ... | |
} | |
} | |
// developers can create simple data classes using any serialization package | |
class MyDataClass { | |
final String foo; | |
final String bar; | |
MyDataClass(this.foo, this.bar); | |
// generated, added by hand | |
static final coder = MyDataClassJsonCoder(); | |
} | |
// generated by existing serialization package implementing JsonCoder | |
class MyDataClassJsonCoder extends JsonCoder<MyDataClass> { | |
@override | |
MyDataClass fromJson(String payload) { | |
final map = jsonDecode(payload); | |
return MyDataClass(map['foo'], map['bar']); | |
} | |
@override | |
String toJson(MyDataClass payload) { | |
final map = {'foo': payload.foo, 'bar': payload.bar}; | |
return jsonEncode(map); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// or maybe this?? | |
class JsonCoder<T> extends Codec<String, T> { | |
@override | |
Converter<T, String> get decoder => throw UnimplementedError(); | |
@override | |
Converter<String, T> get encoder => throw UnimplementedError(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment