如何 return 在 prisma 订阅中自定义数据

how to return customize data in prisma subscription

我正在学习 graphql 和 prisma,我遇到了一个关于 prisma 订阅的问题。

我想 return 每当有项目创建或更新时,就列出一个项目。所以这是我的代码,它不起作用。

scheme.graphql

# import Item from "./generated/prisma.graphql"

type Subscription {
    todoItems: TodoItems
}

type TodoItems {
    items: [Item!]!
}

解析器

const Subscription = {
    todoItems: {
        subscribe: async (parent, args, context, info) => {
            const itemSubscription = await context.db.subscription.item({
                where: { mutation_in: ['CREATED', 'UPDATED'] },
            }, info);

            return itemSubscription;
        },
        resolve: async (payload, args, context, info) => {
            const items = await context.db.query.items({ type: 0, orderBy: 'updatedAt_DESC' }, info);
            return { items };
        },
    },
}

module.exports = {
    Subscription,
}

在 graphql 操场上,

subscription{
  todoItems{
    items{
      title
    }
  }
}

它给出了错误:

{
  "errors": [
    {
      "message": "Anonymous Subscription must select only one top level field.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "todoItems"
      ],
      "extensions": {
        "code": "INTERNAL_SERVER_ERROR",
        "exception": {
          "stacktrace": [
            "Error: Anonymous Subscription must select only one top level field.",
            "    at asErrorInstance (d:\git\inote\node_modules\graphql\execution\execute.js:489:43)",
            "    at <anonymous>",
            "    at process._tickCallback (internal/process/next_tick.js:118:7)"
          ]
        }
      }
    }
  ]
}

有什么想法吗?

Prisma 不支持订阅项目列表。相反,prisma 希望您订阅单个项目突变("created"、"updated"、"deleted")。如所述 here.

例如

subscription newTodos {
  todo(where: {
    mutation_in: [CREATED]
  }) {
    mutation
    node {
      title
    }
  }
}

要获得 "the full list",您必须在 订阅 之后查询待办事项以避免丢失事件(竞争条件)。因此,您必须手动 "sync" 来自订阅和查询的数据。