ApiUtils.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package com.poyee.utils;
  2. import cn.hutool.core.lang.Assert;
  3. import cn.hutool.core.util.ObjectUtil;
  4. import cn.hutool.json.JSONUtil;
  5. import com.poyee.res.Result;
  6. import lombok.extern.slf4j.Slf4j;
  7. import java.util.function.Function;
  8. import java.util.function.Supplier;
  9. /**
  10. * @author Hr
  11. */
  12. @Slf4j
  13. public class ApiUtils {
  14. public static <T, R> R httpSuccess(Function<T, Result<R>> function, T request, R defaultValue, String msg) {
  15. Assert.notNull(request, msg);
  16. Result<R> response = function.apply(request);
  17. if (response != null && response.successFlag()) {
  18. return ObjectUtil.defaultIfNull(response.getData(), defaultValue);
  19. } else {
  20. log.error("{} error,request={}, response={}", msg, JSONUtil.toJsonStr(request), JSONUtil.toJsonStr(response));
  21. assert response != null;
  22. throw new RuntimeException(response.getMessage());
  23. }
  24. }
  25. public static <T, R> R httpSuccess(Function<T, Result<R>> function, T request, String msg) {
  26. return httpSuccess(function, request, null, msg);
  27. }
  28. public static <R> R httpSuccessNoParams(Supplier<Result<R>> function, R defaultValue, String msg) {
  29. Assert.notNull(function, "Function must not be null");
  30. Result<R> response = function.get();
  31. if (response != null && response.successFlag()) {
  32. return ObjectUtil.defaultIfNull(response.getData(), defaultValue);
  33. } else {
  34. log.error("{} error, response={}", msg, JSONUtil.toJsonStr(response));
  35. throw new RuntimeException(msg);
  36. }
  37. }
  38. }