Skip to content

Commit

Permalink
Step 9.4: Add Mutation.removeChat
Browse files Browse the repository at this point in the history
  • Loading branch information
DAB0mB authored and Urigo committed Jul 20, 2019
1 parent f2b0995 commit 3d4f54d
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
24 changes: 24 additions & 0 deletions schema/resolvers.ts
Expand Up @@ -153,6 +153,30 @@ const resolvers: Resolvers = {

return chat;
},

removeChat(root, { chatId }, { currentUser }) {
if (!currentUser) return null;

const chatIndex = chats.findIndex(c => c.id === chatId);

if (chatIndex === -1) return null;

const chat = chats[chatIndex];

if (!chat.participants.some(p => p === currentUser.id)) return null;

chat.messages.forEach(chatMessage => {
const chatMessageIndex = messages.findIndex(m => m.id === chatMessage);

if (chatMessageIndex !== -1) {
messages.splice(chatMessageIndex, 1);
}
});

chats.splice(chatIndex, 1);

return chatId;
},
},

Subscription: {
Expand Down
1 change: 1 addition & 0 deletions schema/typeDefs.graphql
Expand Up @@ -34,6 +34,7 @@ type Query {
type Mutation {
addMessage(chatId: ID!, content: String!): Message
addChat(recipientId: ID!): Chat
removeChat(chatId: ID!): ID
}

type Subscription {
Expand Down
52 changes: 52 additions & 0 deletions tests/mutations/removeChat.test.ts
@@ -0,0 +1,52 @@
import { createTestClient } from 'apollo-server-testing';
import { ApolloServer, PubSub, gql } from 'apollo-server-express';
import schema from '../../schema';
import { resetDb, users } from '../../db';

describe('Mutation.removeChat', () => {
beforeEach(resetDb);

it('removes chat by id', async () => {
const server = new ApolloServer({
schema,
context: () => ({
pubsub: new PubSub(),
currentUser: users[0],
}),
});

const { query, mutate } = createTestClient(server);

const addChatRes = await mutate({
variables: { chatId: '1' },
mutation: gql`
mutation RemoveChat($chatId: ID!) {
removeChat(chatId: $chatId)
}
`,
});

expect(addChatRes.data).toBeDefined();
expect(addChatRes.errors).toBeUndefined();
expect(addChatRes.data!.removeChat).toEqual('1');

const getChatRes = await query({
variables: { chatId: '1' },
query: gql`
query GetChat($chatId: ID!) {
chat(chatId: $chatId) {
id
name
participants {
id
}
}
}
`,
});

expect(addChatRes.data).toBeDefined();
expect(getChatRes.errors).toBeUndefined();
expect(addChatRes.data!.chat).toBeUndefined();
});
});

0 comments on commit 3d4f54d

Please sign in to comment.