Skip to content

Instantly share code, notes, and snippets.

@adam-cowley
Created March 2, 2018 16:24
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adam-cowley/0e86d581d3e416045bd407291d53ac73 to your computer and use it in GitHub Desktop.
Save adam-cowley/0e86d581d3e416045bd407291d53ac73 to your computer and use it in GitHub Desktop.
Neo4j Driver as an Express Middleware
// Create an express app
const express = require('express');
const app = express();
// Tell it to use Neo4j middleware
app.use(require('./neo4j'));
// Example Route
app.get('/', (req, res) => {
// Create Driver session
const session = req.driver.session();
// Run Cypher query
const cypher = 'MATCH (n) RETURN count(n) as count';
session.run(cypher)
.then(result => {
// On result, get count from first record
const count = result.records[0].get('count');
// Send response
res.send({count: count.toNumber()});
})
.catch(e => {
// Output the error
res.status(500).send(e);
})
.then(() => {
// Close the session
return session.close();
});
});
// Listen on port 8080
app.listen(8080, () => console.log('Listening on :8080'));
// Require Neo4j
const neo4j = require('neo4j-driver').v1;
// Create Driver
const driver = new neo4j.driver("bolt://localhost:7687", neo4j.auth.basic("neo4j", "neo"));
// Express middleware
module.exports = function(req, res, next) {
req.driver = driver;
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment