Created
May 19, 2021 19:18
-
-
Save stargazing-dino/8983a46b839c76a7770a5494f8c5af9f to your computer and use it in GitHub Desktop.
A wrapper around a document reference to be used with Firebase
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
import 'package:cloud_firestore/cloud_firestore.dart'; | |
import 'package:freezed_annotation/freezed_annotation.dart'; | |
part 'document.freezed.dart'; | |
typedef RestoreData<T> = Future<void> Function(); | |
/// To generate updated model code, run: | |
/// flutter pub run build_runner build | |
@freezed | |
class Document<T extends Object?> with _$Document<T> { | |
const Document._(); | |
const factory Document({ | |
required DocumentReference<T> reference, | |
required T data, | |
}) = _Document<T>; | |
static Document<T?> fromSnapshot<T>(DocumentSnapshot<T?> snapshot) { | |
return Document<T?>( | |
data: snapshot.data(), | |
reference: snapshot.reference, | |
); | |
} | |
static Document<T> fromSnapshotForce<T>(DocumentSnapshot<T> snapshot) { | |
assert(snapshot.exists); | |
return Document<T>( | |
data: snapshot.data()!, | |
reference: snapshot.reference, | |
); | |
} | |
static Document<T> fromQuerySnapshot<T>(QueryDocumentSnapshot<T> snapshot) { | |
return Document<T>( | |
data: snapshot.data(), | |
reference: snapshot.reference, | |
); | |
} | |
Future<RestoreData> delete() async { | |
await reference.delete(); | |
return () async { | |
await reference.set(data); | |
}; | |
} | |
Future<RestoreData> set(T value) async { | |
await reference.set(value); | |
return () async { | |
await reference.set(data); | |
}; | |
} | |
Future<RestoreData> upsert(T value) async { | |
await reference.set( | |
value, | |
SetOptions(merge: true), | |
); | |
return () async { | |
await reference.set(data); | |
}; | |
} | |
String get id => reference.id; | |
Document<R> cast<R>({ | |
required R data, | |
required FromFirestore<R> fromFirestore, | |
required ToFirestore<R> toFirestore, | |
}) { | |
return Document<R>( | |
data: data, | |
reference: reference.withConverter<R>( | |
fromFirestore: fromFirestore, | |
toFirestore: toFirestore, | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment