package cn.qinys.platform.gateway.response;

import com.alibaba.fastjson.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tanlie
 * Date 2021/12/24 15:58
 * Description
 */

@Component
public class Result {

    public static Mono<Void> fail(ServerHttpResponse response, Integer code, String msg) {
        if (StringUtils.hasLength(msg) && msg.contains("404 NOT_FOUND")) {
            code = 404;
        }
        Map<String, Object> map = new HashMap<>(3);
        map.put("code", code);
        map.put("msg", msg);
        map.put("data", "");
        String jsonStr = JSON.toJSONString(map);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        DataBuffer buffer = response.bufferFactory().wrap(jsonStr.getBytes());
        return response.writeWith(Mono.just(buffer));
    }


}
