Skip to content

3. Customization

Sergey Ivonchik edited this page Nov 4, 2021 · 2 revisions

How to customize Httx

Custom mappers

Example blow show maybe one of most common cases. Custom mapper for Json.NET. Basically you need to follow two simple steps:

  1. Implement your mapper using IMapper interface
  2. Add mappers while initializing Context
// 1. Create custom mapper by implementing IMapper interface.
public class NewtonsoftJsonMapper<TBody, TResult> : IMapper<TBody, TResult> {
  public IEnumerable<byte> AsBody(TBody serializableObject) {
    return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(serializableObject));
  }

  public TResult FromResult(object result) {
    if (result is IEnumerable<byte> bytes) {
      return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bytes.ToArray()));
    }

    if (result is string jsonString) {
      return JsonConvert.DeserializeObject<T>(jsonString);
    }

    throw new InvalidOperationException($"can't deserialize result {result} as json");
  }
}

// 2. Add mapper while initilizing context
Context.InitializeDefault(Version, () => {
  // onContextReady logic
}, builder => {
  builder.WithMapper(typeof(Json<>), typeof(NewtonsoftJsonMapper<,>));
  builder.WithMapper(typeof(Json), typeof(NewtonsoftJsonMapper<,>));
});

Custom loggers

You just implement ILogger interface:

public class HttxUnityLogger : ILogger {
  public void Log(object message) {
    Debug.Log($"[Http/s]: {message}");
  }
}
Clone this wiki locally