From a646f01730f2021d316fb72245374a15e126dd0b Mon Sep 17 00:00:00 2001 From: Jiaqi Liu Date: Thu, 3 Oct 2024 14:58:06 +0800 Subject: [PATCH] Refactor out query execution logic (#4) --- .../wilhelm/web/endpoints/DataServlet.java | 44 ++++++++++++------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/qubitpi/wilhelm/web/endpoints/DataServlet.java b/src/main/java/org/qubitpi/wilhelm/web/endpoints/DataServlet.java index 000b668..2515dd9 100644 --- a/src/main/java/org/qubitpi/wilhelm/web/endpoints/DataServlet.java +++ b/src/main/java/org/qubitpi/wilhelm/web/endpoints/DataServlet.java @@ -127,6 +127,21 @@ public Response getVocabularyByLanguagePaged( LANGUAGES.get(language), (Integer.parseInt(page) - 1) * Integer.parseInt(perPage), perPage ); + return Response + .status(Response.Status.OK) + .entity(executeNativeQuery(query)) + .build(); + } + + /** + * Runs a cypher query against Neo4J database and return the query result as a JSON-serializable object. + * + * @param query A standard cypher query string + * + * @return query result + */ + @NotNull + private Object executeNativeQuery(@NotNull final String query) { try (Driver driver = GraphDatabase.driver(NEO4J_URL, AuthTokens.basic(NEO4J_USERNAME, NEO4J_PASSWORD))) { driver.verifyConnectivity(); @@ -134,25 +149,20 @@ public Response getVocabularyByLanguagePaged( .withConfig(QueryConfig.builder().withDatabase(NEO4J_DATABASE).build()) .execute(); - return Response - .status(Response.Status.OK) - .entity( - result - .records() + return result + .records() + .stream() + .map( + record -> record.keys() .stream() - .map( - record -> record.keys() - .stream() - .map(key -> new AbstractMap.SimpleImmutableEntry<>( - key, - expand(record.get(key)) - )) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) - - ) - .collect(Collectors.toList()) + .map(key -> new AbstractMap.SimpleImmutableEntry<>( + key, + expand(record.get(key)) + )) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) + ) - .build(); + .collect(Collectors.toList()); } }