Merge pull request #1331 from North101/develop

Enforce nnbd for typeconverters
This commit is contained in:
Simon Binder 2021-07-09 10:41:08 +02:00 committed by GitHub
commit 1f11a392a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 74 additions and 0 deletions

View File

@ -39,3 +39,34 @@ class EnumIndexConverter<T> extends TypeConverter<T, int> {
return (value as dynamic)?.index as int;
}
}
/// A type converter automatically mapping `null` values to `null` in both
/// directions.
///
/// Instead of overriding [mapToDart] and [mapToSql], subclasses of this
/// converter should implement [requireMapToDart] and [requireMapToSql], which
/// are used to map non-null values to and from sql values, respectively.
///
/// Apart from the implementation changes, subclasses of this converter can be
/// used just like all other type converters.
abstract class NullAwareTypeConverter<D, S> extends TypeConverter<D, S> {
/// Constant default constructor.
const NullAwareTypeConverter();
@override
D? mapToDart(S? fromDb) {
return fromDb == null ? null : requireMapToDart(fromDb);
}
/// Map a non-null value from an object in Dart into something that will be
/// understood by the database.
D requireMapToDart(S fromDb);
@override
S? mapToSql(D? value) {
return value == null ? null : requireMapToSql(value);
}
/// Maps a non-null column from the database back to Dart.
S requireMapToSql(D value);
}

View File

@ -21,3 +21,21 @@ class SyncTypeConverter extends TypeConverter<SyncType, int> {
return value?.index;
}
}
class NullAwareSyncTypeConverter extends NullAwareTypeConverter<SyncType, int> {
const NullAwareSyncTypeConverter();
@override
SyncType requireMapToDart(int fromDb) {
const values = SyncType.values;
if (fromDb < 0 || fromDb >= values.length) {
return SyncType.locallyCreated;
}
return values[fromDb];
}
@override
int requireMapToSql(SyncType value) {
return value.index;
}
}

View File

@ -0,0 +1,25 @@
import 'package:test/test.dart';
import '../data/tables/converter.dart';
void main() {
test('test null in null aware type converters', () {
const typeConverter = NullAwareSyncTypeConverter();
expect(typeConverter.mapToDart(typeConverter.mapToSql(null)), null);
expect(typeConverter.mapToSql(typeConverter.mapToDart(null)), null);
});
test('test value in null aware type converters', () {
const typeConverter = NullAwareSyncTypeConverter();
const value = SyncType.synchronized;
expect(typeConverter.mapToDart(typeConverter.mapToSql(value)), value);
expect(typeConverter.mapToSql(typeConverter.mapToDart(value.index)),
value.index);
});
test('test invalid value in null aware type converters', () {
const typeConverter = NullAwareSyncTypeConverter();
const defaultValue = SyncType.locallyCreated;
expect(typeConverter.mapToDart(-1), defaultValue);
});
}