Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.