如何使用 Graphql 和 Neo4j 在类型字段上添加唯一约束?

How to add a unique constraint on type field with Graphql and Neo4j?

我正在制作一个 GRANDStack 应用程序,所以我正在使用 neo4j 和 graphql,

我的 schema.graphql 文件中有这种类型:

type User {
  userId: ID!
  username: String! @unique
  mail: String! @unique
  password: String! @private
}

但我仍然可以使用同一个帐户创建多个帐户

当我在这里查看 neo4j 文档时,我知道这是可能的: https://neo4j.com/docs/graphql-manual/current/directives/#_unique

但我目前唯一发现的是在我的数据库中手动执行类似的操作:

CREATE CONSTRAINT ON (u:User) ASSERT u.mail IS UNIQUE;

但这不是个好主意,我希望它是自动的

我认为我的 package.json 也是最新的 :

{
  "name": "grand-stack-starter-api",
  "version": "0.0.1",
  "description": "API app for GRANDstack",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:dev": "./node_modules/.bin/nodemon --watch src --ext js,graphql --exec babel-node  src/index.js",
    "build": "babel src --out-dir build && shx cp .env build 2>/dev/null || : && shx cp src/schema.graphql build",
    "now-build": "babel src --out-dir build && shx cp src/schema.graphql build",
    "start": "npm run build && node build/index.js",
    "seedDb": "./node_modules/.bin/babel-node src/seed/seed-db.js"
  },
  "author": "William Lyon",
  "license": "MIT",
  "dependencies": {
    "@apollo/client": "^3.2.5",
    "@neo4j/graphql": "^2.4.0",
    "apollo-server": "^3.5.0",
    "apollo-server-lambda": "^2.19.0",
    "csv-parse": "^4.10.1",
    "dotenv": "^7.0.0",
    "graphql": "^16.0.1",
    "neo4j-driver": "^4.4.0",
    "node-fetch": "^2.6.0",
    "react": "^16.13.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.9.0",
    "@babel/node": "^7.8.7",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/plugin-transform-runtime": "^7.9.0",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-react": "^7.9.4",
    "@babel/preset-typescript": "^7.9.0",
    "@babel/runtime-corejs3": "^7.9.2",
    "babel-plugin-auto-import": "^1.0.5",
    "babel-plugin-module-resolver": "^4.0.0",
    "cross-env": "^7.0.2",
    "nodemon": "^1.19.1",
    "shx": "^0.3.2"
  }
}

原来文档没有更新

为了解决这个问题,我首先必须遵循这个: https://neo4j.com/docs/graphql-manual/current/type-definitions/constraints/#type-definitions-constraints-unique

解决方案是添加这个错误的

await neoSchema.assertConstraints({ options: { create: true }});

我在他们的 discord 和 right 功能一中与在 neo4j 工作的人交谈过:

await neoSchema.assertIndexesAndConstraints({ options: { create: true }});

如果像我一样你不能等待,因为你的代码不在函数中,你可以用 .then 做这样的事情:

 const neoSchema = new Neo4jGraphQL({
   ...
    })
 neoSchema
      .assertIndexesAndConstraints({ options: { create: true } })
      .then(() => {
        const server = new ApolloServer({
         ...

    app.listen({ host, port, path }, () => {
      console.log(`GraphQL server ready at http://${host}:${port}${path}`)
    })
  })