npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

neo4j-request

v1.3.2

Published

Wrapper for neo4j-driver to simplify requests

Downloads

8

Readme

neo4j-request

A wrapper for the official neo4j-driver that simplifies the execution of cypher queries by encapsulating session opening and closing as well as transaction handling in respective methods. The queried records are extracted to a simplified format, non-standard properties (e.g. dates) are converted.

Currently, this package only makes use of the Promise API of neo4j-driver. Features like the Streaming API or bookmarks are not yet implemented.

Installation

Via npm:

npm install neo4j-request

Usage

Import:

const neo4j = require('neo4j-request');
// or
import * as neo4j from 'neo4j-request';

init

Before doing any transaction, the neo4j-driver needs to be initialized once. The driver instance is set globally, such that you can import neo4j-request in any other module without the need to initialize again. If the node application closes, the driver gets closed as well.

If the Neo4j instance is unavailable, connection is not possible. Driver instantiation will be re-invoked a few times before throwing an error (useful in cases like server startup when node application is live earlier than the Neo4j database instance).

For detailed options refer to neo4j-driver.

neo4j.init(url, user, password, database = 'neo4j', options = {disableLosslessIntegers: true});

|Param|Details| |---|---| |url|Type: string Usually something like neo4j://localhost.| |user|Type: string| |password|Type: string| |database (optional)|Type: string Default: neo4j If using Neo4j 3.x, this information gets ignored.| |options (optional)|Type: Object For details refer to neo4j-driver.

Returns Promise<ServerInfo>.

readTransaction

A very simple read transaction that expects a cypher statement and (optionally) query parameters.

|Param|Details| |---|---| |query|Type: string| |params (optional)|Type: Object<string, any>|

Returns Promise<Object[]>: an array of objects, where the object's property names correlate with identifiers within the RETURN clause.

const query = `
  MATCH (p:Person {name: $name})-[:HAS_ADDRESS]->(add:Address)
  RETURN p.name AS name, add AS address
`;

const params = {
  name: 'Alex'
};

try {
  
  const results = await neo4j.readTransaction(query, params);
  console.log(results);
  
} catch (e) {
  
  // handle error
  
}

// console.log(results)
// [
//   {
//     name: 'Alex',
//     address: {
//       ZIP: '10178',
//       number: '1',
//       town: 'Berlin',
//       street: 'Alexanderplatz'
//     }
//   }
// ]

writeTransaction

Very similar to readTransaction (see for details) except that it expects a cypher statement that modifies the database.

multipleStatements

Execute multiple cypher queries within one transaction. A fail of one statement will lead to the rollback of the whole transaction.

|Param|Details| |---|---| |statements|Type: Array<{statement: string, parameters: Object<string, any>}>|

Returns Promise<Object[][]>: an array of arrays similar to readTransaction.


const statements = [{
  statement: `CREATE ...`,
  parameters: {}
}, {
  statement: `MATCH ... CREATE (n:Node $map) ...`,
  parameters: { map: { value: 'foo' } }
}];

try {
  
  const results = await neo4j.multipleStatements(statements);
  // handle results
  
} catch (e) {
  
  // handle error
  
}

getDriver

Get the driver instance to access full API of neo4j-driver.

const driver = neo4j.getDriver();

session

Acquire a session to execute, e.g., explicit transactions.

const session = neo4j.session();
const txc = session.beginTransaction();

// ...

await session.close();

extractRecords

Used internally to extract and convert the returned records by neo4j-driver to a more simplified format. It converts non-standard values, like date, time, etc., to strings as well as Neo4j integers, if they are outside of the safe range.

Takes an array of records Record[] and returns an array of objects Object[].

const query = `
  MATCH (p:Person {name: "Alex"})-[:HAS_ADDRESS]->(add:Address)
  RETURN p.name AS name, add AS address
`;

// query results returned by neo4j-driver
// {
//   records: [
//     Record {
//       keys: [ 'name', 'address' ],
//       length: 2,
//       _fields: [
//         'Alex',
//         Node {
//           identity: 1,
//           labels: [ 'Address' ],
//           properties: {
//             ZIP: '10178',
//             number: '1',
//             town: 'Berlin',
//             street: 'Alexanderplatz'
//           }
//         }
//       ]
//       _fieldLookup: { name: 0, address: 1 }
//     }
//   ],
//   summary: ResultSummary {...}
// }

extractRecords(queryResults.records);

// simplified records returned by neo4j-request
// {
//   name: 'Alex',
//   address: {
//     ZIP: '10178',
//     number: '1',
//     town: 'Berlin',
//     street: 'Alexanderplatz'
//   }
// }

removeEmptyArrays

Look for empty arrays returned by Neo4j and clean them, if there is null inside.

Sometimes, if the cypher query contains OPTIONAL MATCH node in combination with collect({key: node.value}) AS values, the resulting array may be filled with one object with null values: [{key: null}]. This method reduces the array to [] by calling removeEmptyArrays(data, 'values', 'key').

|Param|Details| |---|---| |data|Type: any[]| |arrayKey|Type: string Property key of the array to check.| |checkKey|Type: string Property key of first array element to check against null.|

Returns cleaned data array.

const query = `
  MATCH (p:Person {name: "Alex"})-[:HAS_ADDRESS]->(add:Address)
  OPTIONAL MATCH (p)-[:HAS_FRIEND]->(f:Person)-[:HAS_ADDRESS]->(fAddr:Address)
  RETURN p.name AS name,
         add AS address,
         collect({name: f.name, address: fAddr}) AS friends
`;

const results = await neo4j.readTransaction(query);
console.log(results);

// [
//   {
//     name: 'Alex',
//     address: {
//       ZIP: '10178',
//       number: '1',
//       town: 'Berlin',
//       street: 'Alexanderplatz'
//     },
//     friends: [ { address: null, name: null } ]
//   }
// ]

const resultsCleaned = neo4j.removeEmptyArrays(results, 'friends', 'name');
console.log(resultsCleaned);

// [
//   {
//     name: 'Alex',
//     address: {
//       ZIP: '10178',
//       number: '1',
//       town: 'Berlin',
//       street: 'Alexanderplatz'
//     },
//     friends: []
//   }
// ]

Testing

Copy test/config-sample.js to test/config.js and change the values according to the settings of your Neo4j instance. Then, run test command:

npm test