Created
July 17, 2025 07:22
-
-
Save mp911de/6729ca327326d072820a1a0eb225c4a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright 2025 the original author or authors. | |
* | |
* Licensed under the Apache License, Version 2.0 (the "License"); | |
* you may not use this file except in compliance with the License. | |
* You may obtain a copy of the License at | |
* | |
* https://www.apache.org/licenses/LICENSE-2.0 | |
* | |
* Unless required by applicable law or agreed to in writing, software | |
* distributed under the License is distributed on an "AS IS" BASIS, | |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
* See the License for the specific language governing permissions and | |
* limitations under the License. | |
*/ | |
package org.springframework.data.mongodb.observability; | |
import io.micrometer.common.KeyValue; | |
import io.micrometer.common.docs.KeyName; | |
import java.util.function.Function; | |
import org.jspecify.annotations.Nullable; | |
/** | |
* @author Mark Paluch | |
*/ | |
class SmartKeyName<C> implements KeyName { | |
private final String name; | |
private final boolean required; | |
private final Function<C, @Nullable Object> valueFunction; | |
private SmartKeyName(String name, boolean required, Function<C, Object> valueFunction) { | |
this.required = required; | |
this.valueFunction = valueFunction; | |
this.name = name; | |
} | |
public static <C> SmartKeyName<C> required(String name, Function<C, @Nullable Object> valueFunction) { | |
return new SmartKeyName<C>(name, true, valueFunction); | |
} | |
public @Nullable KeyValue valueOf(@Nullable C context) { | |
Object value = context != null ? valueFunction.apply(context) : null; | |
// TODO having a sophisticated way to skip not required keys would be nice if the value cannot be provided. | |
if (!isRequired()) { | |
return null; | |
} | |
return KeyValue.of(this, value == null ? KeyValue.NONE_VALUE : value.toString()); | |
} | |
@Override | |
public boolean isRequired() { | |
return required; | |
} | |
@Override | |
public String asString() { | |
return name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment