build method

JsonQuery build()

Implementation

JsonQuery build() {
  if (_modelName == null) {
    throw StateError('Model name is required');
  }
  if (_action == null) {
    throw StateError('Action is required');
  }

  final arguments = <String, dynamic>{};

  if (_where != null) arguments['where'] = _where;
  if (_data != null) arguments['data'] = _data;
  if (_orderBy != null) arguments['orderBy'] = _orderBy;
  if (_take != null) arguments['take'] = _take;
  if (_skip != null) arguments['skip'] = _skip;
  if (_aggregate != null) arguments['_aggregate'] = _aggregate;
  if (_groupBy != null) arguments['by'] = _groupBy;
  if (_selectFields != null) arguments['selectFields'] = _selectFields;

  // Build selection
  JsonSelection? selection;
  if (_select != null || _include != null) {
    final fields = <String, JsonFieldSelection>{};

    if (_select != null) {
      for (final entry in _select!.entries) {
        if (entry.value == true) {
          fields[entry.key] = const JsonFieldSelection();
        }
      }
    }

    if (_include != null) {
      for (final entry in _include!.entries) {
        if (entry.value == true) {
          fields[entry.key] = const JsonFieldSelection(
            selection: JsonSelection(scalars: true),
          );
        } else if (entry.value is Map) {
          fields[entry.key] = JsonFieldSelection(
            arguments: entry.value as Map<String, dynamic>,
            selection: const JsonSelection(scalars: true),
          );
        }
      }
    }

    selection = JsonSelection(
      scalars: _selectScalars,
      fields: fields.isNotEmpty ? fields : null,
    );
  } else {
    selection = JsonSelection(scalars: _selectScalars);
  }

  return JsonQuery(
    modelName: _modelName!,
    action: _action!,
    args: JsonQueryArgs(
      arguments: arguments.isNotEmpty ? arguments : null,
      selection: selection,
    ),
  );
}