save method
- @protected
- @visibleForTesting
- T model, {
- bool? remote,
- Map<
String, dynamic> ? params, - Map<
String, String> ? headers, - OnData<
T> ? onSuccess, - OnDataError<
T> ? onError,
inherited
Implementation
@protected
@visibleForTesting
Future<T> save(
T model, {
bool? remote,
Map<String, dynamic>? params,
Map<String, String>? headers,
OnData<T>? onSuccess,
OnDataError<T>? onError,
}) async {
_assertInit();
remote ??= _remote;
params = await defaultParams & params;
headers = await defaultHeaders & headers;
// we ignore the `init` argument here as
// saving locally requires initializing
model._initialize(adapters, save: true);
if (remote == false) {
return model;
}
final body = json.encode(serialize(model));
final result = await sendRequest(
baseUrl.asUri / urlForSave(model.id, params) & params,
method: methodForSave(model.id, params),
headers: headers,
body: body,
requestType: DataRequestType.save,
key: model._key,
onSuccess: (data) {
T _model;
if (data == null) {
// return "old" model if response was empty
_model = model._initialize(adapters, save: true);
} else {
// deserialize already inits models
// if model had a key already, reuse it
final _newModel =
deserialize(data as Map<String, dynamic>, key: model._key!)
.model!;
// in the unlikely case where supplied key couldn't be used
// ensure "old" copy of model carries the updated key
if (model._key != null && model._key != _newModel._key) {
graph.removeKey(model._key!);
model._key = _newModel._key;
}
_model = _newModel;
}
return onSuccess?.call(_model) ?? _model;
},
onError: onError,
);
return result ?? model;
}