diff --git a/src/main/kotlin/com/cosmotech/api/utils/StringExtensions.kt b/src/main/kotlin/com/cosmotech/api/utils/StringExtensions.kt index eea79f5c..f5fd8553 100644 --- a/src/main/kotlin/com/cosmotech/api/utils/StringExtensions.kt +++ b/src/main/kotlin/com/cosmotech/api/utils/StringExtensions.kt @@ -40,3 +40,17 @@ fun String.shaHash(): String { } fun String.toRedisMetaDataKey() = "${this}MetaData" + +fun String.formatQuery(map: Map): String { + var newValue = this + map.forEach { (key, value) -> + var sanitizedValue = + if (value.isNullOrBlank()) { + "null" + } else { + "\"${value.replace("\"","\\\"")}\"" + } + newValue = newValue.replace("$$key", sanitizedValue) + } + return newValue +} diff --git a/src/test/kotlin/com/cosmotech/api/utils/StringExtensionsTests.kt b/src/test/kotlin/com/cosmotech/api/utils/StringExtensionsTests.kt index 29f1ffea..52c1f5d8 100644 --- a/src/test/kotlin/com/cosmotech/api/utils/StringExtensionsTests.kt +++ b/src/test/kotlin/com/cosmotech/api/utils/StringExtensionsTests.kt @@ -40,4 +40,27 @@ class StringExtensionsTests { val actual = input.toRedisMetaDataKey() assertEquals(expected, actual) } + + @Test + fun `should format Cypher Query with variables`() { + val map = + mapOf( + "name" to "Joe Doe", + "id" to "100", + "object" to "{id:\"id\"}", + "array" to "{id:['one', 'two']}") + val actual = "CREATE (:Person {name: \$name, id: \$id, object: \$object, array: \$array)" + val expected = + "CREATE (:Person {name: \"Joe Doe\", id: \"100\", object: \"{id:\\\"id\\\"}\", " + + "array: \"{id:['one', 'two']}\")" + assertEquals(expected, actual.formatQuery(map)) + } + + @Test + fun `should format Cypher Query & replace empty value with null`() { + val map = mapOf("name" to "Joe Doe", "id" to " ") + val actual = "CREATE (:Person {name: \$name, id: \$id})" + val expected = "CREATE (:Person {name: \"Joe Doe\", id: null})" + assertEquals(expected, actual.formatQuery(map)) + } }