Search code examples
javascriptnode.jsneo4jcypher

Run Neo4j queries from Cypher files in Javascript


I am using the official Neo4j Javascript driver to connect with my database. I want to run queries directly from .cypher files because writing them as strings is much more error-prone.

I don't want to read the file using fs, as it would consume unnecessary resources. I want to import the file as I do with a JSON file (at compile time)

How can I do that?


Solution

  • A coworker created something that seems exactly what you want in typescript with nest

    import { Inject } from '@nestjs/common';
    
    /** All injectables cyphers */
    export const cypherInjections: string[] = [];
    
    export const InjectCypher = (
      path: string,
    ): ((target: object, key: string | symbol, index?: number) => void) => {
      const cypher = `${path}.cypher`;
      if (!cypherInjections.includes(cypher)) {
        cypherInjections.push(cypher);
      }
    
      return Inject(cypher);
    };
    

    it is use like that:

    import { Injectable } from '@nestjs/common';
    
    @Injectable()
    export class CypherService {
      constructor(
        @InjectCypher('path/to/your/cypher')
        private readonly myCypher: string,
      ) {}
    
      // here you can use this.myCypher
      // it's a string that represent your cypher
    }
    

    Hope that it can help someone :)