sdy

update newMessage

1 type Mutation { 1 type Mutation {
2 - newMessage(receiverId: Int, message: String!, roomId: Int): Message! 2 + newMessage(receiverEmail: String, message: String!, roomId: Int): Message!
3 } 3 }
......
1 import { isAuthenticated, prisma } from "../../../utils"; 1 import { isAuthenticated, prisma } from "../../../utils";
2 import { ONE_TO_ONE_MESSAGE } from "../../../topics"; 2 import { ONE_TO_ONE_MESSAGE } from "../../../topics";
3 3
4 +// newMessage 에서는 1:1, 1:n 메시지 방만 가정하고 있음
5 +// 나머지 랜덤채팅은 아직 구상중 (5/4) 기준
4 export default { 6 export default {
5 Mutation: { 7 Mutation: {
6 newMessage: async (_, args, { request, pubsub }) => { 8 newMessage: async (_, args, { request, pubsub }) => {
7 isAuthenticated(request); 9 isAuthenticated(request);
8 const { user } = request; 10 const { user } = request;
9 - const { receiverId, message, roomId } = args; 11 + const { receiverEmail, message, roomId } = args;
10 - let room = await prisma.room.findOne({ 12 + const receiver = await prisma.user.findOne({
11 where: { 13 where: {
12 - id: roomId, 14 + email: receiverEmail,
13 }, 15 },
14 }); 16 });
15 - room = await prisma.room.update({ 17 +
18 + let room = await prisma.room.findOne({
16 where: { 19 where: {
17 id: roomId, 20 id: roomId,
18 }, 21 },
19 - data: {
20 - participants: {
21 - connect: [{ id: user.id }, { id: receiverId }],
22 - },
23 - },
24 }); 22 });
23 +
25 // 방이 없는 경우 24 // 방이 없는 경우
26 if (room === undefined || room === null) { 25 if (room === undefined || room === null) {
27 // 보내는 사람과 받는 사람이 다른 경우 26 // 보내는 사람과 받는 사람이 다른 경우
28 - if (user.id !== receiverId) { 27 + if (user.id !== receiver.id) {
29 room = await prisma.room.create({ 28 room = await prisma.room.create({
30 data: { 29 data: {
31 participants: { 30 participants: {
32 - connect: [{ id: receiverId }, { id: user.id }], 31 + connect: [{ id: receiver.id }, { id: user.id }],
33 }, 32 },
34 }, 33 },
35 }); 34 });
...@@ -43,23 +42,32 @@ export default { ...@@ -43,23 +42,32 @@ export default {
43 }, 42 },
44 }); 43 });
45 } 44 }
45 + } else {
46 + // 방이 원래 있던 경우 업데이트
47 + room = await prisma.room.update({
48 + where: {
49 + id: roomId,
50 + },
51 + data: {
52 + participants: {
53 + connect: [{ id: user.id }, { id: receiver.id }],
54 + },
55 + },
56 + });
46 } 57 }
58 +
47 if (!room) { 59 if (!room) {
48 throw new Error("There is no room"); 60 throw new Error("There is no room");
49 } 61 }
50 - const toUser = await prisma.user.findOne({ 62 +
51 - where: {
52 - id: receiverId,
53 - },
54 - });
55 const subMessage = await prisma.message.create({ 63 const subMessage = await prisma.message.create({
56 data: { 64 data: {
57 text: message, 65 text: message,
58 to: { 66 to: {
59 - connect: [{ id: toUser.id }], 67 + connect: { id: receiver.id },
60 }, 68 },
61 from: { 69 from: {
62 - connect: [{ id: user.id }], 70 + connect: { id: user.id },
63 }, 71 },
64 room: { 72 room: {
65 connect: { 73 connect: {
......