package cn.axzo.workflow.server.common.handler;

import org.redisson.api.NameMapper;
import org.springframework.util.StringUtils;

/**
 * redis缓存key前缀处理
 *
 * @author wangli
 * @since 2022/7/14 17:44
 */
public class KeyPrefixHandler implements NameMapper {

    private final String keyPrefix;

    public KeyPrefixHandler(String keyPrefix) {
        //前缀为空 则返回空前缀
        this.keyPrefix = StringUtils.hasLength(keyPrefix) ? keyPrefix + ":" : "";
    }

    /**
     * 增加前缀
     */
    @Override
    public String map(String name) {
        if (!StringUtils.hasLength(name)) {
            return null;
        }
        if (StringUtils.hasLength(keyPrefix) && !name.startsWith(keyPrefix)) {
            return keyPrefix + name;
        }
        return name;
    }

    /**
     * 去除前缀
     */
    @Override
    public String unmap(String name) {
        if (!StringUtils.hasLength(name)) {
            return null;
        }
        if (StringUtils.hasLength(keyPrefix) && name.startsWith(keyPrefix)) {
            return name.substring(keyPrefix.length());
        }
        return name;
    }

}
