Подписка prisma2 возвращает данные: ноль
У меня есть базовый паб, работающий здесь, используя шаблон и graphql-yoga: https://github.com/ryanking1809/prisma2_subscriptions https://codesandbox.io/s/github/ryanking1809/prisma2_subscriptions/tree/sql-lite
С опубликованной мутацией:
const Mutation = objectType({
name: 'Mutation',
definition(t) {
//...
t.field('publish', {
type: 'Post',
nullable: true,
args: {
id: idArg(),
},
resolve: async (parent, { id }, ctx) => {
const post = await ctx.photon.posts.update({
where: { id },
data: { published: true },
include: { author: true }
});
ctx.pubsub.publish("PUBLISHED_POST", {
publishedPost: post
});
return post
},
})
},
})
И подписка - я только возвращаюсь true
Чтобы убедиться withFilter
(из graphql-yoga
) работает.
const Subscription = objectType({
name: "Subscription",
definition(t) {
t.field("publishedPostWithEmail", {
type: "Post",
args: {
authorEmail: stringArg({ required: false })
},
subscribe: withFilter(
(parent, { authorEmail }, ctx) => ctx.pubsub.asyncIterator("PUBLISHED_POST"),
(payload, { authorEmail }) => true
)
});
}
});
Возвращая следующее на publish
(Вы можете скопировать и вставить их в коды и коробки - это аккуратно!)
mutation {
publish(
id: "cjzwz39og0000nss9b3gbzb7v"
) {
id,
title,
author {
email
}
}
}
subscription {
publishedPostWithEmail(authorEmail:"prisma@subscriptions.com") {
title,
content,
published
}
}
{
"errors": [
{
"message": "Cannot return null for non-nullable field Subscription.publishedPostWithEmail.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"publishedPostWithEmail"
]
}
],
"data": null
}
По какой-то причине он возвращается data: null
, Когда я вхожу payload.publishedPosts
в функции фильтра кажется, что все есть.
{ id: 'cjzwqcf2x0001q6s97m4yzqpi',
createdAt: '2019-08-29T13:34:26.648Z',
updatedAt: '2019-08-29T13:54:19.479Z',
published: true,
title: 'Check Author',
content: 'Do you save the author?',
author:
{ id: 'sdfsdfsdfsdf',
email: 'prisma@subscriptions.com',
name: 'Prisma Sub' } }
Я что-то упускаю?
1 ответ
Наконец-то разобрался!
Функция подписки должна быть названа в честь ключа в pubsub. Так что, если у вас есть функция публикации, например:
ctx.pubsub.publish("PUBLISHED_POST", {
publishedPost: post
});
тогда вы должны назвать свою подписку publishedPost
t.field("publishedPost", {
type: "Post",
args: {
authorEmail: stringArg({ required: false })
},
subscribe: withFilter(
(parent, { authorEmail }, ctx) =>
ctx.pubsub.asyncIterator("PUBLISHED_POST"),
(payload, { authorEmail }) => payload.publishedPost.author.email === authorEmail
)
});
если вы называете свою подписку publishedPostWithEmail
тогда данные не возвращаются
t.field("publishedPostWithEmail", {
//...
});
Интересно, если у вас есть 2 ключа
ctx.pubsub.publish("PUBLISHED_POST", {
publishedPost2: post,
publishedPost3: post
});
Тогда, если вы назовете свою подписку publishedPost2
тогда publishedPost3
опущено из результатов.
Странно, если вы подписываетесь на 2 сообщения, вы получаете все данные
ctx.pubsub.publish("PUBLISHED_POST", {
publishedPost: post,
publishedPost2: post
});
ctx.pubsub.publish("PUBLISHED_POST_X", {
publishedPostX: post,
publishedPostY: post
});
ctx.pubsub.asyncIterator([
"PUBLISHED_POST",
"PUBLISHED_POST_X"
]),
возвращается publishedPost
, publishedPost2
, publishedPostX
, publishedPostY
Таким образом, вы можете обойти вышеуказанную проблему, подписавшись на массив одним элементом, и имя подписки становится неактуальным.
t.field("publishedPostXYZ", {
type: "Post",
args: {
authorEmail: stringArg({ required: false })
},
subscribe: withFilter(
(parent, { authorEmail }, ctx) =>
ctx.pubsub.asyncIterator([
"PUBLISHED_POST"
]),
(payload, { authorEmail }) => {
return payload.publishedPost.author.email === authorEmail;
}
)
});
Кажется, это может быть ошибкой