package com.chushang.gateway.filter;

import com.chushang.common.core.constant.CommonConstants;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 计算请求时间
 */
@Component
public class TimestampHeaderFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 创建一个新的请求对象并替换原来的头信息
        ServerHttpRequest mutatedRequest = request.mutate().headers(headers -> headers.add(CommonConstants.START_TIME, System.currentTimeMillis() + "")).build();
        // 继续处理请求
        return chain.filter(exchange.mutate().request(mutatedRequest).build());
    }

    @Override
    public int getOrder() {
        // 设置过滤器的执行顺序，数值越小，优先级越高
        return -1;
    }
}
