-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-websocket.html
More file actions
614 lines (542 loc) · 21.6 KB
/
Copy pathtest-websocket.html
File metadata and controls
614 lines (542 loc) · 21.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat API 테스트</title>
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
<style>
* { box-sizing: border-box; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: #f5f5f5;
}
h1 { color: #333; border-bottom: 3px solid #007bff; padding-bottom: 10px; }
h2 { color: #555; margin-top: 30px; border-left: 4px solid #007bff; padding-left: 10px; }
.section {
background: white;
padding: 20px;
margin: 20px 0;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.status {
padding: 15px;
margin-bottom: 20px;
border-radius: 6px;
font-weight: bold;
}
.status.connected { background: #d4edda; color: #155724; }
.status.disconnected { background: #f8d7da; color: #721c24; }
.controls {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
margin: 15px 0;
}
input, select, textarea {
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
button {
padding: 10px 15px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
}
button:hover { background: #0056b3; }
button:disabled { background: #ccc; cursor: not-allowed; }
button.danger { background: #dc3545; }
button.danger:hover { background: #c82333; }
button.success { background: #28a745; }
button.success:hover { background: #218838; }
#messages {
border: 1px solid #ddd;
padding: 15px;
height: 300px;
overflow-y: auto;
background: #f9f9f9;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 12px;
}
.message {
margin: 5px 0;
padding: 8px;
background: white;
border-left: 3px solid #007bff;
border-radius: 4px;
}
.message.error { border-left-color: #dc3545; }
.message.success { border-left-color: #28a745; }
.message.warning { border-left-color: #ffc107; }
.api-group {
background: #f9f9f9;
padding: 15px;
border-radius: 4px;
margin: 10px 0;
border-left: 4px solid #007bff;
}
.api-group h3 {
margin-top: 0;
color: #007bff;
}
.response-box {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 4px;
padding: 10px;
margin-top: 10px;
max-height: 200px;
overflow-y: auto;
font-family: 'Courier New', monospace;
font-size: 11px;
white-space: pre-wrap;
display: none;
}
</style>
</head>
<body>
<h1>💬 채팅 API 테스트 도구</h1>
<!-- 공통 설정 -->
<div class="section">
<h2>⚙️ 설정</h2>
<div class="controls">
<input type="text" id="apiBaseUrl" placeholder="API URL" value="http://localhost:3000/api/v1">
<input type="password" id="accessToken" placeholder="Access Token (JWT)">
</div>
</div>
<!-- WebSocket 연결 -->
<div class="section">
<h2>🔌 실시간 채팅 (WebSocket)</h2>
<div id="wsStatus" class="status disconnected">🔴 연결 안됨</div>
<div class="controls">
<button onclick="connectWebSocket()" class="success">연결</button>
<button onclick="disconnectWebSocket()" class="danger">연결 끊기</button>
<button onclick="pingWS()">Ping</button>
<label style="display:flex;align-items:center;gap:6px;font-size:13px;">
<input type="checkbox" id="autoPing" onchange="toggleAutoPing()" style="width:auto;">
자동 ping (30초, 하트비트)
</label>
</div>
<!-- 채팅방 입장 & 메시지 전송 (WebSocket용) -->
<div class="api-group">
<h3>room.join - 채팅방 입장</h3>
<div class="controls">
<input type="number" id="chatRoomId" placeholder="채팅방 ID" value="3" min="1">
<button onclick="joinRoomWS()">입장</button>
</div>
</div>
<div class="api-group">
<h3>message.send - 메시지 전송 (실시간)</h3>
<div class="controls">
<select id="msgType">
<option value="TEXT">TEXT</option>
<option value="AUDIO">AUDIO</option>
<option value="PHOTO">PHOTO</option>
<option value="VIDEO">VIDEO</option>
</select>
<input type="text" id="msgText" placeholder="메시지 내용" value="안녕하세요!">
<input type="text" id="msgMediaUrl" placeholder="미디어 URL">
<input type="number" id="msgDuration" placeholder="길이(초)" value="5" min="1">
<button onclick="sendMessageWS()">전송</button>
</div>
</div>
</div>
<!-- REST API (초기 데이터 로드용) -->
<div class="section">
<h2>📡 채팅방 관리 (REST API)</h2>
<div class="api-group">
<h3>POST /chats/clubs/{clubId}/room - 클럽 채팅방 입장 (그룹)</h3>
<p style="font-size: 12px; color: #666;">ACTIVE 클럽 멤버만 입장(멱등). 최초 입장 시 "…님이 입장했습니다" SYSTEM 메시지가 나갑니다. 성공하면 chatRoomId가 위/아래 입력칸에 자동 채워집니다.</p>
<div class="controls">
<input type="number" id="clubId" placeholder="클럽 ID" value="1" min="1">
<button onclick="enterClubRoom()" class="success">입장</button>
</div>
<div id="enterClubResponse" class="response-box"></div>
</div>
<div class="api-group">
<h3>POST /chats/rooms - 새 채팅방 생성 (1:1)</h3>
<p style="font-size: 12px; color: #666;">상대방과 처음 만날 때 사용합니다.</p>
<div class="controls">
<input type="number" id="targetUserId" placeholder="상대방 ID" value="2" min="1">
<button onclick="createRoom()">생성</button>
</div>
<div id="createRoomResponse" class="response-box"></div>
</div>
<div class="api-group">
<h3>GET /chats/rooms - 내 채팅방 목록</h3>
<p style="font-size: 12px; color: #666;">로그인 후 내가 참여 중인 채팅방을 보여줍니다.</p>
<div class="controls">
<button onclick="listRooms()">목록 조회</button>
</div>
<div id="listRoomsResponse" class="response-box"></div>
</div>
<div class="api-group">
<h3>GET /chats/rooms/{id} - 채팅방 상세</h3>
<div class="controls">
<input type="number" id="roomDetailId" placeholder="채팅방 ID" value="3" min="1">
<button onclick="getRoomDetail()">조회</button>
</div>
<div id="roomDetailResponse" class="response-box"></div>
</div>
<div class="api-group">
<h3>GET /chats/rooms/{id}/messages - 과거 메시지 조회</h3>
<p style="font-size: 12px; color: #666;">채팅방 입장 시 이전 메시지들을 받아옵니다.</p>
<div class="controls">
<input type="number" id="msgRoomId" placeholder="채팅방 ID" value="3" min="1">
<button onclick="listMessages()">조회</button>
</div>
<div id="listMessagesResponse" class="response-box"></div>
</div>
<div class="api-group">
<h3>PATCH /chats/rooms/{chatRoomId}/read - 채팅방 읽음 처리 (방 단위 커서)</h3>
<p style="font-size: 12px; color: #666;">내 읽음 커서(lastReadAt)를 현재 시각으로 전진. 기존 메시지 단위 read를 대체합니다. (DIRECT/CLUB 공통)</p>
<div class="controls">
<input type="number" id="readRoomId" placeholder="채팅방 ID" value="3" min="1">
<button onclick="markRoomReadRest()">읽음 처리</button>
</div>
<div id="markReadResponse" class="response-box"></div>
</div>
<div class="api-group">
<h3>PATCH /chats/messages/{messageId} - 메시지 전송취소</h3>
<p style="font-size: 12px; color: #666;">DIRECT: 상대 미열람 시만(읽힘 409 CHAT-005). CLUB: 항상 차단(409 CHAT-006).</p>
<div class="controls">
<input type="number" id="deleteMessageId" placeholder="메시지 ID" value="555" min="1">
<button onclick="deleteMessageRest()" class="danger">전송취소</button>
</div>
<div id="deleteMessageResponse" class="response-box"></div>
</div>
</div>
<!-- 활동중 사용자 (REST) -->
<div class="section">
<h2>🟢 활동중 사용자 (REST)</h2>
<div class="api-group">
<h3>GET /users/active - 현재 활동중 사용자 조회</h3>
<p style="font-size: 12px; color: #666;">
내 지역(또는 areaCode) 기준 현재 활동중 유저. 데이터 소스는 <b>소켓 presence + 주기적 ping</b>이라
연결 후 ping(자동 ping 권장)을 보내고 있어야 뜹니다.
<b>본인은 결과에서 제외</b>되므로, 같은 지역 다른 유저가 접속+ping 중이어야 목록이 채워집니다(탭 2개로 테스트).
</p>
<div class="controls">
<input type="text" id="activeAreaCode" placeholder="areaCode (선택, 미지정 시 내 지역)">
<input type="number" id="activeSize" placeholder="size (기본 20)" value="20" min="1" max="50">
<input type="text" id="activeCursor" placeholder="cursor (다음 페이지용, 자동 채움)">
<button onclick="getActiveUsers(false)" class="success">활동중 조회</button>
<button onclick="getActiveUsers(true)" id="activeNextBtn" disabled>다음 페이지</button>
</div>
<div id="activeUsersResponse" class="response-box"></div>
</div>
</div>
<!-- 로그 -->
<div class="section">
<h2>📋 로그</h2>
<div id="messages"></div>
</div>
<script>
let socket = null;
// ============ 유틸리티 함수 ============
function getWebSocketUrl() {
const apiBaseUrl = document.getElementById('apiBaseUrl').value || 'http://localhost:3000/api/v1';
return apiBaseUrl.replace('http://', 'ws://').replace('https://', 'wss://').replace('/api/v1', '');
}
function addLog(message, type = 'info') {
const logsEl = document.getElementById('messages');
const logEl = document.createElement('div');
logEl.className = `message ${type}`;
logEl.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
logsEl.appendChild(logEl);
logsEl.scrollTop = logsEl.scrollHeight;
}
function updateWSStatus(connected) {
const statusEl = document.getElementById('wsStatus');
if (connected) {
statusEl.className = 'status connected';
statusEl.textContent = '🟢 WebSocket 연결됨';
} else {
statusEl.className = 'status disconnected';
statusEl.textContent = '🔴 WebSocket 연결 안됨';
}
}
function showResponse(elementId, data, isError = false) {
const el = document.getElementById(elementId);
if (!el) return;
el.style.display = 'block';
el.textContent = JSON.stringify(data, null, 2);
el.style.borderLeftColor = isError ? '#dc3545' : '#28a745';
}
// ============ WebSocket 함수 ============
function connectWebSocket() {
const token = document.getElementById('accessToken').value;
if (!token) {
addLog('❌ 토큰이 없습니다. JWT access_token을 입력하세요.', 'error');
return;
}
const wsUrl = getWebSocketUrl();
socket = io(`${wsUrl}/chats`, {
path: '/ws',
auth: { token },
transports: ['websocket'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: 5,
});
socket.on('connect', () => {
addLog('✅ WebSocket 연결 성공!', 'success');
updateWSStatus(true);
});
socket.on('disconnect', () => {
addLog('⚠️ WebSocket 연결 끊김', 'warning');
updateWSStatus(false);
});
socket.on('connect_error', (error) => {
addLog(`❌ 연결 오류: ${error.message}`, 'error');
});
socket.on('message.new', (msg) => {
// 입장/퇴장 등 SYSTEM 공지는 message.new(type=SYSTEM, isSystem=true)로 옴
if (msg.isSystem || msg.type === 'SYSTEM') {
addLog(`📢 시스템: ${msg.text}`, 'warning');
} else {
addLog(`📨 새 메시지: [${msg.senderUserId}] ${msg.text || `[${msg.type}]`}`, 'success');
}
});
socket.on('exception', (error) => {
addLog(`❌ 오류: ${JSON.stringify(error)}`, 'error');
});
// 읽음 처리는 방 단위 커서로 변경됨: {chatRoomId, readerUserId, lastReadAt}
socket.on('message.read', (payload) => {
addLog(
`👀 읽음 커서: room=${payload.chatRoomId} reader=${payload.readerUserId} lastReadAt=${payload.lastReadAt}`,
'success',
);
});
socket.on('message.deleted', (payload) => {
addLog(
`🗑️ 삭제: room=${payload.chatRoomId} msg=${payload.messageId} by=${payload.deletedByUserId} at=${payload.deletedAt}`,
'warning',
);
});
socket.on('notification.new', (payload) => {
addLog(`🔔 알림: ${payload.title} - ${payload.body}`, 'success');
});
}
function disconnectWebSocket() {
if (socket) {
socket.disconnect();
addLog('WebSocket 연결을 닫았습니다.', 'warning');
updateWSStatus(false);
}
}
function pingWS() {
if (!socket?.connected) {
addLog('❌ WebSocket이 연결되지 않았습니다.', 'error');
return;
}
socket.emit('ping', (res) => {
addLog(`🏓 Ping! ${JSON.stringify(res)}`, 'success');
});
}
function joinRoomWS() {
if (!socket?.connected) {
addLog('❌ WebSocket이 연결되지 않았습니다.', 'error');
return;
}
const chatRoomId = parseInt(document.getElementById('chatRoomId').value);
if (!chatRoomId) {
addLog('❌ 채팅방 ID를 입력하세요.', 'error');
return;
}
socket.emit('room.join', { chatRoomId }, (res) => {
if (res.ok) {
addLog(`✅ 채팅방 입장: ${res.joined}`, 'success');
} else {
addLog(`❌ 입장 실패`, 'error');
}
});
}
function sendMessageWS() {
if (!socket?.connected) {
addLog('❌ WebSocket이 연결되지 않았습니다.', 'error');
return;
}
const chatRoomId = parseInt(document.getElementById('chatRoomId').value);
const type = document.getElementById('msgType').value;
const text = document.getElementById('msgText').value;
const mediaUrl = document.getElementById('msgMediaUrl').value;
const durationSec = parseInt(document.getElementById('msgDuration').value);
if (!chatRoomId) {
addLog('❌ 채팅방 ID를 입력하세요.', 'error');
return;
}
const payload = {
chatRoomId,
type,
text: type === 'TEXT' ? text : null,
mediaUrl: type !== 'TEXT' ? mediaUrl : null,
durationSec: type === 'AUDIO' || type === 'VIDEO' ? durationSec : null,
};
socket.emit('message.send', payload, (res) => {
if (res.ok) {
addLog(`✅ 메시지 전송 성공!`, 'success');
document.getElementById('msgText').value = '';
}
});
}
// ============ REST API 함수 ============
async function apiCall(method, endpoint, body = null) {
const apiBase = document.getElementById('apiBaseUrl').value || 'http://localhost:3000/api/v1';
const token = document.getElementById('accessToken').value;
const url = `${apiBase}${endpoint}`;
const options = {
method,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
};
if (body) options.body = JSON.stringify(body);
try {
const response = await fetch(url, options);
const data = await response.json();
addLog(`${method} ${endpoint} - ${response.status}`, response.ok ? 'success' : 'error');
return { ok: response.ok, data };
} catch (error) {
addLog(`네트워크 오류: ${error.message}`, 'error');
return { ok: false, error: error.message };
}
}
// 응답 envelope({success:{data}}) 또는 평면 응답 모두에서 값 꺼내기
function pickData(resData) {
return resData?.success?.data ?? resData ?? {};
}
async function enterClubRoom() {
const clubId = parseInt(document.getElementById('clubId').value);
if (!clubId) {
addLog('❌ 클럽 ID를 입력하세요.', 'error');
return;
}
const result = await apiCall('POST', `/chats/clubs/${clubId}/room`);
showResponse('enterClubResponse', result.data, !result.ok);
// 성공하면 chatRoomId를 관련 입력칸에 자동 채움
const chatRoomId = pickData(result.data)?.chatRoomId;
if (result.ok && chatRoomId) {
['chatRoomId', 'roomDetailId', 'msgRoomId', 'readRoomId'].forEach((id) => {
const el = document.getElementById(id);
if (el) el.value = chatRoomId;
});
addLog(`➡️ 클럽 채팅방 ID ${chatRoomId} 자동 입력됨 (WebSocket room.join으로 입장 후 전송하세요)`, 'success');
}
}
async function createRoom() {
const targetUserId = parseInt(document.getElementById('targetUserId').value);
if (!targetUserId) {
addLog('❌ 상대방 ID를 입력하세요.', 'error');
return;
}
const result = await apiCall('POST', '/chats/rooms', { targetUserId });
showResponse('createRoomResponse', result.data, !result.ok);
}
async function listRooms() {
const result = await apiCall('GET', '/chats/rooms');
showResponse('listRoomsResponse', result.data, !result.ok);
}
async function getRoomDetail() {
const roomId = parseInt(document.getElementById('roomDetailId').value);
if (!roomId) {
addLog('❌ 채팅방 ID를 입력하세요.', 'error');
return;
}
const result = await apiCall('GET', `/chats/rooms/${roomId}`);
showResponse('roomDetailResponse', result.data, !result.ok);
}
async function listMessages() {
const roomId = parseInt(document.getElementById('msgRoomId').value);
if (!roomId) {
addLog('❌ 채팅방 ID를 입력하세요.', 'error');
return;
}
const result = await apiCall('GET', `/chats/rooms/${roomId}/messages`);
showResponse('listMessagesResponse', result.data, !result.ok);
}
async function markRoomReadRest() {
const roomId = parseInt(document.getElementById('readRoomId').value);
if (!roomId) {
addLog('❌ 채팅방 ID를 입력하세요.', 'error');
return;
}
const result = await apiCall('PATCH', `/chats/rooms/${roomId}/read`);
showResponse('markReadResponse', result.data, !result.ok);
}
async function deleteMessageRest() {
const messageId = parseInt(document.getElementById('deleteMessageId').value);
if (!messageId) {
addLog('❌ 메시지 ID를 입력하세요.', 'error');
return;
}
const result = await apiCall('PATCH', `/chats/messages/${messageId}`);
showResponse('deleteMessageResponse', result.data, !result.ok);
}
// ============ 활동중 사용자 (REST) ============
async function getActiveUsers(useCursor = false) {
const areaCode = document.getElementById('activeAreaCode').value.trim();
const size = document.getElementById('activeSize').value.trim();
const cursor = document.getElementById('activeCursor').value.trim();
const params = new URLSearchParams();
if (areaCode) params.set('areaCode', areaCode);
if (size) params.set('size', size);
if (useCursor && cursor) params.set('cursor', cursor);
const qs = params.toString();
const result = await apiCall('GET', `/users/active${qs ? `?${qs}` : ''}`);
showResponse('activeUsersResponse', result.data, !result.ok);
if (!result.ok) {
document.getElementById('activeNextBtn').disabled = true;
return;
}
const data = pickData(result.data);
const items = data?.items ?? [];
const page = data?.page ?? {};
addLog(`🟢 활동중 ${items.length}명 (hasNext=${!!page.hasNext})`, 'success');
items.forEach((u) => {
addLog(
` · [${u.userId}] ${u.nickname} (${u.gender ?? '-'}, ${u.age ?? '-'}) ${u.areaName ?? ''} · lastActive=${u.lastActiveAt}`,
'info',
);
});
// 다음 페이지 커서 자동 반영
document.getElementById('activeCursor').value = page.nextCursor ?? '';
document.getElementById('activeNextBtn').disabled = !page.hasNext;
}
// ============ 하트비트 자동 ping ============
let autoPingTimer = null;
function toggleAutoPing() {
const on = document.getElementById('autoPing').checked;
if (on) {
if (autoPingTimer) clearInterval(autoPingTimer);
autoPingTimer = setInterval(() => {
if (socket?.connected) socket.emit('ping', () => {});
}, 30000);
addLog('🫀 자동 ping 시작 (30초 간격)', 'success');
} else if (autoPingTimer) {
clearInterval(autoPingTimer);
autoPingTimer = null;
addLog('🫀 자동 ping 중지', 'warning');
}
}
// 초기화
document.addEventListener('DOMContentLoaded', () => {
updateWSStatus(false);
addLog('준비됨. Access Token을 입력하고 WebSocket을 연결하세요.', 'info');
});
</script>
</body>
</html>