ChopperClient constructor

ChopperClient({
  1. Uri? baseUrl,
  2. Client? client,
  3. Iterable? interceptors,
  4. Authenticator? authenticator,
  5. Converter? converter,
  6. ErrorConverter? errorConverter,
  7. Iterable<ChopperService>? services,
})

Creates and configures a ChopperClient.

The base URL of each request of the registered services can be defined with the baseUrl parameter. E.g., the hostname of your service. If not provided, a empty default Uri will be used.

A custom HTTP client can be passed as the client parameter to be used with the created ChopperClient. If not provided, a default http.Client will be used.

ChopperServices can be added to the client with the services parameter. See the ChopperApi annotation to learn more about creating services.

final chopper = ChopperClient(
  baseUrl: Uri.parse('localhost:8000'),
  services: [
    // Add a generated service
    TodosListService.create()
  ],
);

RequestInterceptors and ResponseInterceptors can be added to the client with the interceptors parameter.

See RequestInterceptor, ResponseInterceptor, HttpLoggingInterceptor, HeadersInterceptor, CurlInterceptor

final chopper = ChopperClient(
  ...
  interceptors: [
    HttpLoggingInterceptor(),
  ]
);

Converters can be added to the client with the converter parameter. Converters are used to convert the body of requests and responses to and from the HTTP format.

A different converter can be used to handle error responses (when Response.isSuccessful == false)) with tche errorConverter parameter.

See Converter, JsonConverter

final chopper = ChopperClient(
    ...
    converter: JsonConverter(),
    errorConverter: JsonConverter(),
  );

Implementation

ChopperClient({
  Uri? baseUrl,
  http.Client? client,
  Iterable? interceptors,
  this.authenticator,
  this.converter,
  this.errorConverter,
  Iterable<ChopperService>? services,
})  : assert(
        baseUrl == null || !baseUrl.hasQuery,
        'baseUrl should not contain query parameters. '
        'Use a request interceptor to add default query parameters',
      ),
      baseUrl = baseUrl ?? Uri(),
      httpClient = client ?? http.Client(),
      _clientIsInternal = client == null,
      assert(
        interceptors?.every(_isAnInterceptor) ?? true,
        'Unsupported type for interceptors, it only support the following types:\n'
        ' - ${allowedInterceptorsType.join('\n - ')}',
      ),
      _requestInterceptors = [
        ...?interceptors?.where(_isRequestInterceptor),
      ],
      _responseInterceptors = [
        ...?interceptors?.where(_isResponseInterceptor),
      ] {
  _services = <Type, ChopperService>{
    for (final ChopperService service in services?.toSet() ?? [])
      service.definitionType: service..client = this
  };
}