如何整合 Neo4j 数据库、NestJS 框架和 GraphQL?

How to integrate Neo4j database, NestJS framework and GraphQL?

我正在尝试将我的 REST API (NestJS) 与带有 GraphQL 查询的新 Neo4j 数据库集成。有人成功吗?提前致谢

编辑 1:(我添加了我的代码)

import { Resolver } from "@nestjs/graphql";
import { Query, forwardRef, Inject, Logger } from "@nestjs/common";
import { Neo4jService } from "src/shared/neo4j/neoj4.service";
import { GraphModelService } from "./models/model.service";
import { Movie } from "src/graphql.schema";

@Resolver('Movie')
    export class GraphService {
    constructor(private readonly _neo4jService: Neo4jService) {}

    @Query()
    async getMovie() {
        console.log("hello");
        return neo4jgraphql(/*i don't know how get the query and params*/);
    }
}

我没有研究过 GraphQL,但我知道有一个 npm 包(Neo4j-graphql-js)可以将 GraphQL 查询转换为 Cypher 查询。它使 GraphQL 和 Neo4j 一起使用变得更容易。

此外,检查 GRANDstack 它是用于构建基于图形的应用程序的全栈开发集成。

我建议你访问Neo4j Community

我正在使用 NestInterceptor 来完成此操作:

@Injectable()
export class Neo4JGraphQLInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    next: CallHandler<any>,
  ): Observable<any> | Promise<Observable<any>> {
    const ctx = GqlExecutionContext.create(context);
    return neo4jgraphql(
      ctx.getRoot(),
      ctx.getArgs(),
      ctx.getContext(),
      ctx.getInfo(),
    );
  }
}

要在您的 Resolver 中使用它:

@Resolver('Movie')
@UseInterceptors(Neo4JGraphQLInterceptor)
export class MovieResolver {}

我的GraphQLModule是这样配置的:

@Module({
  imports: [
    GraphQLModule.forRoot({
      typePaths: ['./**/*.gql'],
      transformSchema: augmentSchema,
      context: {
        driver: neo4j.driver(
          'bolt://neo:7687',
          neo4j.auth.basic('neo4j', 'password1234'),
        ),
      },
    }),
  ],
  controllers: [...],
  providers: [..., MovieResolver, Neo4JGraphQLInterceptor],
})

注意 transformSchema: augmentSchema 的用法以启用自动生成的突变和查询 (GRANDStack: Schema Augmentation)

希望对您有所帮助!

这对我有用...虽然没有我想要的那么优雅,但它确实有效;我只想让一个 service/provider 访问我的数据库,而不是每个模块的服务,即使这也有效。所以我坚持使用 myModule->myResolver->myService-->Neo4jService 的 Nest 格式。所以 Neo4jService 被注入到所有 xService(s) 中。我在必要时使用 neo4jGraphql 和 augmentSchema 和 Cypher。

代码:

**appmodule.ts**
....
import { makeExecutableSchema } from 'graphql-tools';
import { v1 as neo4j } from 'neo4j-driver';
import { augmentTypeDefs, augmentSchema  } from 'neo4j-graphql-js';
import { Neo4jService } from './neo4j/neo4j.service';
import { MyModule } from './my/my.module';
import { MyResolver } from './my/my.resolver';
import { MyService } from './my/my.service';
....
import { typeDefs } from './generate-schema';  // SDL type file
...
const driver =  neo4j.driver('bolt://localhost:3000', neo4j.auth.basic('neo4j', 'neo4j'))

const schema = makeExecutableSchema({
  typeDefs: augmentTypeDefs(typeDefs),
 });
const augmentedSchema = augmentSchema(schema);   // Now we have an augmented schema

@Module({
  imports: [
    MyModule,

    GraphQLModule.forRoot({
      schema: augmentedSchema,       
      context: {
      driver,
       },
     }),
    ],
  controllers: [],

  providers: [ Neo4jService,
               myResolver,
             ],
})
export class AppModule {}

**myResolver.ts**

import { Args, Mutation, Query, Resolver  } from '@nestjs/graphql';

import { MyService } from './my.service';

@Resolver('My')
export class MyResolver {

    constructor(
        private readonly myService: MyService) {}

      @Query()
      async getData(object, params, ctx, resolveInfo) {
       return await this.myService.getData(object, params, ctx, resolveInfo);
      }

     *//Notice I am just passing the graphql params, etc to the myService*

}

**myService.ts**

import { Injectable } from '@nestjs/common';
import { Neo4jService } from '../neo4j/neo4j.service';

@Injectable()
export class MyService {

    constructor(private neo4jService: Neo4jService) {}

    async getData(object, params, ctx, resolveInfo) {
        return await this.neo4jService.getData(object, params, ctx, resolveInfo);
   }

     *// Again I am just passing the graphql params, etc to the neo4jService*
 }
**neo4jService.ts**
import { Injectable } from '@nestjs/common';
import { neo4jgraphql } from 'neo4j-graphql-js';


@Injectable()
export class Neo4jService {

        getData(object, params, ctx, resolveInfo) {
              return neo4jgraphql(object, params, ctx, resolveInfo);
            }
     .....
     ......
}

所以基本上我推迟了使用 neo4jgraphql,直到我们到达 neo4jService。现在我所有的数据库调用都在这里.....正如我所说的不优雅但它有效。

挑战:Graphql generate 不接受@relation...我发现进行了更改,现在您需要 augmentTypeDefs。 ...希望这可以帮助 编辑 Nestjs 需要很长时间来处理 augmentSchema...所以我建议暂时跳过它...

这是我为 (NestJS + GraphQL + Neo4j) 创建的示例。希望对您有所帮助!

NestJS + GraphQL + Neo4j