sdy

create newMessage

1 +type Mutation {
2 + newMessage(receiverId: String!, message: String!, roomId: String!): Message!
3 +}
1 +import { isAuthenticated, prisma } from "../../../utils";
2 +import { NEW_MESSAGE_TOPIC } from "../../../topics";
3 +
4 +export default {
5 + Mutation: {
6 + newMessage: async (_, args, { request, pubsub }) => {
7 + // isAuthenticated(request);
8 + const { user } = request;
9 + const { receiverId, message, roomId } = args;
10 + let room;
11 + // 방이 없는 경우
12 + if (roomId === undefined) {
13 + // 보내는 사람과 받는 사람이 다른 경우
14 + if (user.id !== receiverId) {
15 + room = await prisma.room.create({
16 + data: {
17 + participants: {
18 + connect: [{ id: receiverId }, { id: user.id }],
19 + },
20 + },
21 + });
22 + } else {
23 + // 자기 자신에게 보내는 경우
24 + room = await prisma.room.create({
25 + data: {
26 + participants: {
27 + connect: [{ id: user.id }],
28 + },
29 + },
30 + });
31 + }
32 + } else {
33 + // 방이 있는 경우
34 + room = await prisma.room.findOne({
35 + where: {
36 + id: roomId,
37 + },
38 + });
39 + }
40 + if (!room) {
41 + throw new Error("There is no room");
42 + }
43 +
44 + // 메시지 생성부분. (지금은 1명 밖에 안들어간 구조.)
45 + const newMessage = await prisma.message.create({
46 + data: {
47 + text: message,
48 + to: {
49 + connect: {
50 + id: receiverId,
51 + },
52 + },
53 + from: {
54 + connect: {
55 + id: user.id,
56 + },
57 + },
58 + room: {
59 + connect: {
60 + id: room.id,
61 + },
62 + },
63 + },
64 + });
65 + pubsub.publish(NEW_MESSAGE_TOPIC, { newMessage });
66 + return newMessage;
67 + },
68 + },
69 +};