apollo-server-express: how to resolve inside subscriptions? - graphql

When doing regular graphQL queries, I have no trouble to get nested objects or computations. But when inside a subscription like:
subscription {
Event(filter: {
mutation_in: [CREATED]
}) {
node {
title
description
start
end
seats
bookings
owner {
email
}
}
}
}
It breaks as soon as I add bookings or owner { ... }. I see no error message on then server. QraphiQL only displays a [object Object] as a response.
The interesing par of the schema is:
type Event {
id: ID!
title: String!
description: String!
owner: User!
seats: Int
bookings: Int
start: DateTime!
end: DateTime!
tickets: [EventTicket!]!
}
type Mutation {
createEvent(event: EventInput!): Event
}
input EventInput {
title: String!
description: String!
seats: Int
start: DateTime!
end: DateTime!
}
type Subscription {
Event(filter: EventSubscriptionFilter): EventSubscriptionPayload
}
input EventSubscriptionFilter {
mutation_in: [_ModelMutationType!]
}
type EventSubscriptionPayload {
mutation: _ModelMutationType!
node: Event
}
enum _ModelMutationType {
CREATED
UPDATED
DELETED
}
And the resolvers:
import { ObjectId } from "mongodb"
import pubsub from "../../utils/pubsub"
export default {
// ...
Mutation: {
createEvent: async (_, data, { mongo: { Events }, user }) => {
const newEvent = data.event
newEvent.ownerId = user._id
const response = await Events.insert(newEvent)
const [_id] = response.insertedIds
newEvent._id = _id
pubsub.publish("Event", { Event: { mutation: "CREATED", node: newEvent } })
return newEvent
},
},
Subscription: {
Event: {
subscribe: () => pubsub.asyncIterator("Event"),
},
},
Event: {
id: event => event._id.toString(),
owner: async (event, _, { mongo: { Users } }) => Users.findOne({ _id: event.ownerId }),
bookings: async (event, _, { mongo: { EventTickets } }) =>
EventTickets.find({ eventId: event._id }).count(),
tickets: async (event, _, { mongo: { EventTickets } }) =>
EventTickets.find({ eventId: event._id }).toArray(),
},
}
Any idea about how to deal with this (and/or how to get a proper error message to debug ^^).

Ok after searching, I found the solution/hack here.
SubscriptionServer.create(
{
execute, subscribe, schema,
onOperation: (message, params, webSocket) => {
return { ...params, context: {mongo} }
},
},
{ server, path: '/subscriptions' },
);
Thanks nharraud.

Related

Relationships with AwsCdk, DynamoDB and AppSync - Typescript and lambda functions

we are currently studying the stack: cdk, appsync and amplify to migrate our applications.
In our initial tests, we were able to upload a graphql api with only appsync wit relationships and it was very smooth, nice and fast.
When testing to build with cdk, we are having difficulties to create the relationships.
Here my code:
Schema
type Person {
id: ID!
name: String!
}
input PersonInput {
id: ID!
name: String!
}
input UpdatePersonInput {
id: ID!
name: String
}
type Client {
id: ID!
type: String!
personId: String
# Person: PersonConnection
Person: Person #connection(fields: ["personId"])
}
input ClientInput {
id: ID!
type: String!
personId: String!
}
input UpdateClientInput {
id: ID!
type: String
personId: String
}
My function
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
async function list() {
const params = {
TableName: process.env.CLIENT_TABLE,
}
try {
const data = await docClient.scan(params).promise()
return data.Items
} catch (err) {
console.log('DynamoDB error: ', err)
return null
}
}
export default list;
My table
const clientTable = new dynamodb.Table(scope, 'ClientTable', {
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
partitionKey: {
name: 'id',
type: dynamodb.AttributeType.STRING,
},
});
clientTable.addGlobalSecondaryIndex({
indexName: 'client-by-person-id',
partitionKey: {
name: 'personId',
type: dynamodb.AttributeType.STRING
},
sortKey: {
name: 'createdAt',
type: dynamodb.AttributeType.STRING
}
})
My query
query MyQuery {
listClients {
id
personId
type
Person {
name
}
}
}
However, my return to Person connection is null
"listClients": [
{
"id": "1",
"personId": "1",
"type": "PJ",
"Person": null
}
]
I would appreciate it if could point out our mistake
Solution of the problem based on the response of the Thorsten.
First, add resolver to the Person field in Client
export const clientResolvers = [{ typeName: "Client", fieldName: "Person" },...]
clientResolvers.map(((resolver: clientTypeResolver) => dataSource2.createResolver(resolver)))
Map function to the Person field in its lambda function
type AppSyncEvent = {
...
source: {personId: string,}
...
}
exports.handler = async (event:AppSyncEvent) => {
switch (event.info.fieldName) {
...
case "Person":
return await getPerson(event.source.personId);
}
}```
Function to solve the person field
async function getPerson(personId: string) {
console.log("CONTEXT\n" + JSON.stringify(personId, null, 2))
// console.log(context.source)
const params = {
TableName: process.env.PERSON_TABLE,
Key: { id: personId }
}
try {
const { Item } = await docClient.get(params).promise()
console.log("DATA\n" + JSON.stringify(Item, null, 2))
return Item
} catch (err) {
console.log('DynamoDB error: ', err)
}

todo list optimistic subscription updates with Apollo GraphQl

I am trying to get an optimistic response when I add a task to my todo list:
ADD_TASK and GET_TASK from query.ts
export const GET_TASKS = gql`
subscription {
queryTask {
id
title
completed
user {
username
}
}
}
`;
export const ADD_TASK = gql`
mutation addTask($task: AddTaskInput!) {
addTask(input: [$task]) {
task {
id
title
completed
}
}
}
`;
addTask() function
const newId = Math.round(Math.random() * -1000000);
await addTask({
variables: {
task: {
title: text,
completed: false,
user: { username: user?.email },
},
},
optimisticResponse: {
__typename: "Mutation",
addTask: {
__typename: "AddTaskPayload",
task: {
__typename: "Task",
id: newId,
title: text,
completed: false,
user: {
__typename: "User",
username: user?.email,
},
},
},
},
update(cache, { data: addTask }: any) {
const queryTask: any = cache.readQuery({
query: GET_TASKS,
});
cache.writeQuery({
query: GET_TASKS,
data: {
queryTask: [...queryTask.queryTask, addTask.addTask.task],
},
});
},
});
UPDATE
So, I got it working normally, now I just need to get it working with:
1.) Subscriptions
2.) The ID problem... it generates a random ID here instead of knowing what it should be (any suggestions)?
I am using my repository with Dgraph here.
(This does not include the optimistic version)
Any suggestions?
J

GraphQL Subscriptions Error: "The \"properties\" argument must be of type Array. Received type object"

I am trying to implement a simple API with GraphQL. My queries and my mutations are in place and working, but now I'm trying to include subscriptions as well.
I already added the subscription in the schema, I included the event publish in the addUser mutation and defined the subscribe function for the subscription type.
Now, when I am trying to run a subscription query in the graphiql in-browser IDE, I get this error:
"The \"properties\" argument must be of type Array. Received type object"
Attached is the schema object. Did I configured something wrong or am I missing something? Thanks!
P.S I also need to mention that I am using mongoose to store the data on an a mongo instance, hence the entities.
import {
GraphQLFloat,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString
} from 'graphql';
// models
import UserType from '../types/user/UserType';
import AccountType from '../types/account/AccountType';
import TransactionType from '../types/transaction/TransactionType';
// entities
import User from '../entities/user/user';
import Account from '../entities/account/account';
import Transaction from '../entities/transaction/transaction';
// subscriptions
import { PubSub } from 'graphql-subscriptions';
// subscriptions
const pubsub = new PubSub();
const USER_CREATED = 'user_created';
// the acceptable starting point of our graph
const RootQueryType = new GraphQLObjectType({
name: 'RootQueryType',
fields: () => ({
// query individual entities in the database
user: {
type: UserType,
description: 'The current user identified by an id',
args: {
id: {
type: GraphQLID
}
},
resolve(parent, args) {
return User.findById(args.id);
}
},
account: {
type: AccountType,
description: 'Details about the account in question identified by an id',
args: {
id: {
type: GraphQLID
}
},
resolve(parent, args) {
return Account.findById(args.id);
}
},
transaction: {
type: TransactionType,
description: 'Details about the transaction in question identified by an id',
args: {
id: {
type: GraphQLID
}
},
resolve(parent, args) {
return Transaction.findById(args.id);
}
},
// query all entities in the database
users: {
type: new GraphQLList(UserType),
resolve: (parent, args) => {
return User.find({});
}
},
accounts: {
type: new GraphQLList(AccountType),
resolve: (parent, args) => {
return Account.find({});
}
},
transactions: {
type: new GraphQLList(TransactionType),
resolve(parent, args) {
return Transaction.find({});
}
}
})
});
const MutationType = new GraphQLObjectType({
name: 'Mutation',
fields: () => ({
addUser: {
type: UserType,
args: {
name: {
type: new GraphQLNonNull(GraphQLString)
},
age: {
type: new GraphQLNonNull(GraphQLInt)
},
email: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve(parent, args) {
let user = new User({
name: args.name,
age: args.age,
email: args.email
});
pubsub.publish(USER_CREATED, {
newUser: user
});
return user.save();
}
},
addAccount: {
type: AccountType,
args: {
currency: {
type: new GraphQLNonNull(GraphQLString)
},
balance: {
type: new GraphQLNonNull(GraphQLFloat)
},
holderId: {
type: new GraphQLNonNull(GraphQLString)
}
},
resolve(parent, args) {
let account = new Account({
currency: args.currency,
balance: args.balance,
holderId: args.holderId
});
return account.save().then(() => console.log('user created'));
}
},
addTransaction: {
type: TransactionType,
args: {
sourceAccountId: {
type: new GraphQLNonNull(GraphQLString)
},
targetAccountId: {
type: new GraphQLNonNull(GraphQLString)
},
amount: {
type: new GraphQLNonNull(GraphQLFloat)
}
},
resolve(parent, args) {
let transaction = new Transaction({
sourceAccountId: args.sourceAccountId,
tagetAccountId: args.tagetAccountId,
timestamp: new Date(),
amount: args.amount
});
Account.findById(args.sourceAccountId, (err, account) => {
if (!err) {
account.balance -= args.amount;
return account.save();
}
});
Account.findById(args.targetAccountId, (err, account) => {
if (!err) {
account.balance += args.amount;
return account.save();
}
});
return transaction.save();
}
}
})
});
const SubscriptionType = new GraphQLObjectType({
name: 'Subscription',
fields: () => ({
newUser: {
type: UserType,
description: 'This subscription is going to provide information every time a new user creation event fires',
resolve: (payload, args, context, info) => {
console.table(payload, args, context, info); // debugging
return payload;
},
subscribe: () => pubsub.asyncIterator(USER_CREATED)
}
})
});
const schema = new GraphQLSchema({
query: RootQueryType,
mutation: MutationType,
subscription: SubscriptionType
});
export default schema;
I expect that when I run the subscription query, it will run listening for events being published and when from another tab I will run a mutation to add a new user, the first tab will catch the event and return details of the user in the payload.

Pass argument child type graphql

I would like to know how can I pass an argument in "child" type.
With the request, I would like to have only the message with id 1 from user id 1.
Currently I have this request :
{user(id:1){
email,
username,
messages(id:1){
text,
id
}
}}
I modified in the schema the User type, and changed
messages: [Message]
by
messages(id: Int): [Message]
But I have always all messages from user and not the message with specific id.
schema.js
import { gql } from 'apollo-server';
export const typeDefs = gql`
# declare custom scalars
scalar Date
##########
## TYPE ##
##########
# a group
type Group {
id: Int!
name: String
users: [User]!
messages: [Message]
}
# a user
type User {
id: Int! # unique id for the user
email: String!
username: String
messages(id: Int): [Message]
groups: [Group]
friends: [User]
}
# a message sent from a user to a group
type Message {
id: Int!
to: Group!
from: User!
text: String!
createdAt: Date!
}
###########
## QUERY ##
###########
# query for types
type Query {
user(email: String, id: Int): User
messages(groupId: Int, userId: Int): [Message]
}
schema {
query: Query
}
`;
export default typeDefs;
resolvers.js
import GraphQLDate from 'graphql-date';
import { Group, Message, User } from './connectors';
export const resolvers = {
Date: GraphQLDate,
Query: {
group(_, args) {
return Group.find({ where: args });
},
messages(_, args) {
return Message.findAll({
where: args,
order: [['createdAt', 'DESC']],
});
},
user(_, args) {
return User.findOne({ where: args });
},
},
Group: {
users(group) {
return group.getUsers();
},
messages(group) {
return Message.findAll({
where: { groupId: group.id },
order: [['createdAt', 'DESC']],
});
},
},
Message: {
to(message) {
return message.getGroup();
},
from(message) {
return message.getUser();
},
},
User: {
messages(user) {
return Message.findAll({
where: { userId: user.id },
order: [['createdAt', 'DESC']],
});
},
groups(user) {
return user.getGroups();
},
friends(user) {
return user.getFriends();
},
},
};
export default resolvers;
You have to update User.messages resolver. This way:
User: {
messages(user, { id }) {
return Message.findAll({
where: { userId: user.id, id },
order: [['createdAt', 'DESC']],
});
},
groups(user) {
return user.getGroups();
},
friends(user) {
return user.getFriends();
},
},
If you want to make id parameter optional, something like this may help:
messages(user, { id }) {
const where = { userId: user.id }
if (id) {
where.id = id
}
return Message.findAll({
where,
order: [['createdAt', 'DESC']],
});
},

How to pass the values of a connection to a subscription?

I'm trying to return a subscription which consists of the following:
const postsSubscription = gql`
subscription postAdded {
postAdded {
id
title
description
author{
name
}
}
}
`
What happens is that Author is type of User, and I just pass an authorId. That means that I don't have the author name when I create the Post:
createPost: async (root, req, { posts }) => {
const Item = {
id: uuid.v4(),
authorId: '565dbdc0-36f2-4bba-be67-c126d0c71fff',
...req
}
await posts.create({ Item })
pubsub.publish('postAdded', { postAdded: Item })
return Item
},
Here is the Author resolver:
Post: {
author: async({ authorId }, req, { users }) => {
const Key = { id: authorId }
const { Item } = await users.get({ Key })
return Item
}
}
Here is the schema:
type Post {
id: ID
title: String
description: String
author: User #relation(name: "PostAuthor")
}
type User {
id: ID
name: String
email: String
password: String
posts: [Post] #relation(name: "UserPosts")
}
type PostPayload {
post: Post
}
type CreateUserPayload {
user: User
}
type Query {
allPosts: [Post]
allUsers: [User]
post(id: ID!): Post
user(id: ID!): User
}
type Mutation {
createPost(input: CreatePostInput!): PostPayload
updatePost(input : UpdatePostInput!): PostPayload
createUser(input : CreateUserInput!): CreateUserPayload
}
type Subscription {
postAdded: Post
}
input CreatePostInput {
title: String!
description: String!
}
input UpdatePostInput {
id: ID!
title: String!,
description: String!
}
input CreateUserInput {
name: String!
email: String!
password: String!
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
So, my question is, how to pass all required fields (including the connections) to the subscription?
I made it work, but not as I wanted.
1) I had to remove this part of the code:
Post: {
author: async({ authorId }, req, { users }) => {
const Key = { id: authorId }
const { Item } = await users.get({ Key })
return Item
}
}
and added this function to the createPost function itself:
createPost: async (root, { input }, { posts, users }) => {
const Key = { id: '3b1884b8-9ee7-4d9d-ab2f-ff32bcd69b9a' }
const user = await users.get({ Key })
const Item = {
id: uuid.v4(),
author: user.Item,
...input
}
await posts.create({ Item })
await pubsub.publish(POST_ADDED_TOPIC, { [POST_ADDED_TOPIC]: Item })
return { post: Item }
}
So this is kinda fixed. But, if you know how to fix this, using the first approach (Post: author thingy) I'll appreciate.

Resources