All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.graphglue.model.property.NodeCache.kt Maven / Gradle / Ivy

Go to download

A library to develop annotation-based code-first GraphQL servers using GraphQL Kotlin, Spring Boot and Neo4j - excluding Spring GraphQL server dependencies

There is a newer version: 7.0.5
Show newest version
package io.github.graphglue.model.property

import io.github.graphglue.model.Node

/**
 * A cache which can be used that lazy loading uses existing nodes instead of new ones
 *
 * @param nodes already fetched nodes
 */
class NodeCache(nodes: Collection = emptySet()) {

    /**
     * Internal representation of the loaded [Node]s
     */
    private val internalNodes = nodes.associateBy { it }.toMutableMap()

    /**
     * The loaded [Node]s, excluding deleted ones
     */
    val nodes: Set get() = internalNodes.keys

    /**
     * Adds a node to the cache
     *
     * @param node the [Node] to add
     */
    fun add(node: Node) {
        internalNodes[node] = node
    }

    /**
     * Gets the cached node equivalent to [node], otherwise puts
     * it into the cache
     * If already marked as deleted, or provided `null`, return `null`
     *
     * @param T the type of node
     * @param node the node to get
     * @return the node from the cache or [node]
     */
    @Suppress("UNCHECKED_CAST")
    fun  getOrAdd(node: T): T? {
        return when (node) {
            null -> null
            else -> {
                internalNodes.computeIfAbsent(node) {
                    node
                } as T
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy