package com.sckw.core.filter;

import cn.hutool.core.util.StrUtil;
import com.sckw.core.utils.TenantUtil;
import com.sckw.core.utils.WebFrameworkUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author xucaiqin
 * @date 2024-05-21 09:12:35
 */
@Component
public class TenantFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String tenantId = WebFrameworkUtils.getTenantId(request);
        TenantUtil.setTenant(StrUtil.isBlank(tenantId) ? "1" : tenantId);
        try {
            filterChain.doFilter(request, response);
        } finally {
            TenantUtil.clear();
        }
    }
}
