@nhogs/nestjs-neo4j
    TypeScript icon, indicating that this package has built-in type declarations

    0.1.3 • Public • Published

    nhogs-logo

    @nhogs/nestjs-neo4j

    Description

    Neo4j module for Nest.js.

    Firebase CI Maintainability Test Coverage

    Peer Dependencies

    npm peer dependency version NestJS) npm peer dependency version neo4j-driver)

    Installation

    $ npm i --save @nhogs/nestjs-neo4j

    Usage

    In static module definition:

    @Module({
      imports: [
        Neo4jModule.forRoot({
          scheme: 'neo4j',
          host: 'localhost',
          port: '7687',
          database: 'neo4j',
          username: 'neo4j',
          password: 'test',
          global: true,
        }),
        CatsModule,
      ],
    })
    export class AppModule {}

    In async module definition:

    @Module({
      imports: [
        Neo4jModule.forRootAsync({
          imports: [ConfigModule],
          inject: [ConfigService],
          useFactory: (configService: ConfigService): Neo4jConfig => ({
            scheme: configService.get('NEO4J_SCHEME'),
            host: configService.get('NEO4J_HOST'),
            port: configService.get('NEO4J_PORT'),
            username: configService.get('NEO4J_USERNAME'),
            password: configService.get('NEO4J_PASSWORD'),
            database: configService.get('NEO4J_DATABASE'),
          }),
          global: true,
        }),
        PersonModule,
        ConfigModule.forRoot({
          envFilePath: './test/src/.test.env',
        }),
      ],
    })
    export class AppAsyncModule {}

    Use in service:

    @Injectable()
    export class CatService {
      constructor(private readonly neo4jService: Neo4jService) {}
    
      async create(cat: Cat): Promise<Cat> {
        const result = await this.neo4jService.run(
          'CREATE (c:`Cat`) SET c=$props RETURN properties(c) AS cat',
          {
            params: {
              props: cat,
            },
            sessionOptions: { write: true },
          },
        );
    
        return result.records[0].toObject().cat;
      }
    
      async findAll(): Promise<Cat[]> {
        return (
          await this.neo4jService.run('MATCH (c:`Cat`) RETURN properties(c) AS cat')
        ).records.map((record) => record.toObject().cat);
      }
    }

    Run with reactive session

    neo4jService
      .rxRun('MATCH (n) RETURN count(n) AS count')
      .records()
      .subscribe({
        next: (record) => {
          console.log(record.get('count'));
        },
        complete: () => {
          done();
        },
      });

    Define constraints with decorators:

    @Node({ label: 'Person' })
    export class PersonDto {
      @ConstraintKey({
        name: 'person_node_key',
        additionalKeys: ['firstname'],
        ifNotExists: true,
      })
      name: string;
    
      @ConstraintNotNull({
        ifNotExists: true,
      })
      firstname: string;
    
      @ConstraintUnique({
        name: 'surname_is_unique',
        ifNotExists: true,
      })
      surname: string;
    
      @ConstraintNotNull({
        name: 'person_name_exists',
        ifNotExists: true,
      })
      age: number;
    }

    Will generate the following constraints:

    CREATE CONSTRAINT `person_node_key` IF NOT EXISTS FOR (p:`Person`) REQUIRE (p.`name`, p.`firstname`) IS NODE KEY;
    CREATE CONSTRAINT IF NOT EXISTS FOR (p:`Person`) REQUIRE p.`firstname` IS NOT NULL;
    CREATE CONSTRAINT `surname_is_unique` IF NOT EXISTS FOR (p:`Person`) REQUIRE p.`surname` IS UNIQUE;
    CREATE CONSTRAINT `person_name_exists` IF NOT EXISTS FOR (p:`Person`) REQUIRE p.`age` IS NOT NULL;
    

    Extends Neo4jModelService to get CRUD methods:

    • runCypherConstraints
    • create
    • merge
    • delete
    • findAll
    • findBy
    • searchBy
    /**
     * Cat Service example
     */
    
    @Injectable()
    export class CatsService extends Neo4jModelService<Cat> {
      constructor(protected readonly neo4jService: Neo4jService) {
        super();
      }
    
      protected label = 'Cat';
      protected logger = undefined;
      protected timestamp = 'created';
    
      async findByName(params: {
        name: string;
        skip?: number;
        limit?: number;
        orderBy?: string;
        descending?: boolean;
      }): Promise<Cat[]> {
        return super.findBy({
          props: { name: params.name },
          ...params,
        });
      }
    
      async searchByName(params: {
        search: string;
        skip?: number;
        limit?: number;
      }): Promise<[Cat, number][]> {
        return super.searchBy({
          prop: 'name',
          terms: params.search.split(' '),
          skip: params.skip,
          limit: params.limit,
        });
      }
    }

    License

    MIT licensed.

    Install

    npm i @nhogs/nestjs-neo4j

    DownloadsWeekly Downloads

    9

    Version

    0.1.3

    License

    MIT

    Unpacked Size

    166 kB

    Total Files

    61

    Last publish

    Collaborators

    • popoto