performDocumentUpsert method

  1. @override
Future<void> performDocumentUpsert(
  1. DocumentUpsertRequest request,
  2. {bool autoCreateIndex = true}
)
override

Implementation

@override
Future<void> performDocumentUpsert(
  DocumentUpsertRequest request, {
  bool autoCreateIndex = true,
}) async {
  final document = request.document;
  final collection = document.parent;
  final schema = request.inputSchema ?? const ArbitraryTreeSchema();

  //
  // Validate IDs
  //
  final documentId = _validateDocumentId(document.documentId);
  final collectionId = _validateCollectionId(collection.collectionId);

  //
  // Send HTTP request
  //
  final json = schema.encodeWith(JsonEncoder(), request.data);
  final response = await _httpRequest(
    'PUT',
    '/$collectionId/_doc/$documentId',
    json: json,
  );

  final error = response.error;
  if (error != null) {
    switch (error.type) {
      case 'index_not_found_exception':
        if (autoCreateIndex) {
          //
          // Create index
          //
          final response = await _httpRequest('PUT', '/$collectionId');
          final responseError = response.error;
          if (responseError != null) {
            throw responseError;
          }

          //
          // Try again
          //
          return performDocumentUpsert(
            request,
            autoCreateIndex: false,
          );
        }

        //
        // We are not allowed to create an index
        //
        throw DatabaseException.internal(
          document: request.document,
          message: 'ElasticSearch index was not found',
        );
    }
  }

  switch (response.status) {
    case HttpStatus.created:
      return;
    case HttpStatus.ok:
      return;
    default:
      throw response.error;
  }
}