OneOf<T>.byStatus constructor

OneOf<T>.byStatus(
  1. Map<Object, OneOfBuilder<T>> types, {
  2. OneOfBuilder<T>? otherwise,
})

Picks the shape by the response's status code.

A key is a status code such as 404, or a pattern such as '4xx' or '40x' where x matches any digit. An exact code wins, then the pattern with the fewest xs. otherwise builds anything else.

OrderResult: OneOf<OrderResult>.byStatus({
  200: OrderPlaced.fromJson,
  404: OrderNotFound.fromJson,
  '4xx': (json) => OrderRejected(ApiError.fromJson(json)),
}),

Implementation

factory OneOf.byStatus(
  Map<Object, OneOfBuilder<T>> types, {
  OneOfBuilder<T>? otherwise,
}) {
  assert(
    types.keys.every(_isStatusKey),
    'OneOf.byStatus keys must be status codes like 404 or patterns like "4xx"',
  );
  return OneOf(
    (json, response) =>
        (_forStatus(types, response.statusCode) ?? otherwise)?.call(json),
  );
}