save method

  1. @override
Future<JsonApiDocument> save(
  1. String endpoint,
  2. Object document
)
override

Implementation

@override
Future<JsonApiDocument> save(String endpoint, Object document) async {
  if (document is! JsonApiDocument) {
    throw ArgumentError('document must be a JsonApiDocument');
  }
  JsonApiDocument? jsonApiDoc;
  try {
    jsonApiDoc = document;
    var response;
    if (jsonApiDoc.isNew) {
      response = await httpPost("$apiPath/$endpoint",
          body: serializer.serialize(jsonApiDoc));
    } else {
      response = await httpPatch("$apiPath/$endpoint/${jsonApiDoc.id}",
          body: serializer.serialize(jsonApiDoc));
    }
    String payload = checkAndDecode(response) ?? '{}';
    JsonApiDocument saved =
        serializer.deserialize(payload) as JsonApiDocument;
    cache(endpoint, saved);
    return saved;
  } on UnprocessableException catch (e) {
    Map parsed = (serializer as JsonApiSerializer).parse(e.responseBody!);
    if (parsed.containsKey('errors')) {
      jsonApiDoc!.errors = parsed['errors'];
      throw InvalidRecordException();
    } else {
      rethrow;
    }
  }
}