Skip to content

Commit

Permalink
レビュー修正
Browse files Browse the repository at this point in the history
  • Loading branch information
tegnike committed Oct 9, 2024
1 parent d4fbdff commit a86e368
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 53 deletions.
83 changes: 47 additions & 36 deletions src/components/messageReceiver.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,59 @@
import { useEffect, useState } from 'react'
import { useEffect, useState, useCallback } from 'react'
import { processReceivedMessage } from '@/features/chat/handlers'
import settingsStore from '@/features/stores/settings'
import homeStore from '@/features/stores/home'

class Message {
timestamp: number
message: string

constructor(timestamp: number, message: string) {
this.timestamp = timestamp
this.message = message
}
}

const MessageReceiver = () => {
const [lastId, setLastId] = useState(0)
const chatLog = homeStore((state) => state.chatLog)
const [lastTimestamp, setLastTimestamp] = useState(0)
const clientId = settingsStore((state) => state.clientId)

const updateChatLog = useCallback((messages: Message[]) => {
homeStore.setState((state) => ({
chatLog: [
...state.chatLog,
...messages.map((message) => ({
role: 'assistant',
content: message.message,
})),
],
}))
messages.forEach((message) => processReceivedMessage(message.message))
}, [])

useEffect(() => {
if (!clientId) return // clientIdがない場合は何もしない

const intervalId = setInterval(() => {
fetch(`/api/messages?lastId=${lastId}&clientId=${clientId}`)
.then((res) => res.json())
.then((data) => {
if (data.messages && data.messages.length > 0) {
data.messages.forEach(
(message: { id: number; message: string }) => {
homeStore.setState({
chatLog: [
...chatLog,
{
role: 'assistant',
content: message.message,
},
],
})
processReceivedMessage(message.message)
}
)
const newLastId = data.messages[data.messages.length - 1].id
setLastId(newLastId)
}
})
.catch((error) => {
console.error('Error fetching messages:', error)
})
}, 1000)

return () => {
clearInterval(intervalId)
if (!clientId) return

const fetchMessages = async () => {
try {
const response = await fetch(
`/api/messages?lastTimestamp=${lastTimestamp}&clientId=${clientId}`
)
const data = await response.json()
if (data.messages && data.messages.length > 0) {
updateChatLog(data.messages)
const newLastTimestamp =
data.messages[data.messages.length - 1].timestamp
setLastTimestamp(newLastTimestamp)
}
} catch (error) {
console.error('Error fetching messages:', error)
}
}
}, [lastId, clientId, chatLog])

const intervalId = setInterval(fetchMessages, 1000) // 5秒ごとに変更

return () => clearInterval(intervalId)
}, [lastTimestamp, clientId, updateChatLog]) // chatLogを依存配列から除外し、updateChatLogを追加

return <></>
}
Expand Down
17 changes: 10 additions & 7 deletions src/pages/api/messages.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next'

interface Message {
id: number
timestamp: number
message: string
}

Expand All @@ -12,8 +12,6 @@ interface MessageQueue {

let messagesPerClient: { [clientId: string]: MessageQueue } = {}

let nextId = 1 // メッセージのIDを管理

const CLIENT_TIMEOUT = 1000 * 60 * 5 // 5分

const handler = (req: NextApiRequest, res: NextApiResponse) => {
Expand Down Expand Up @@ -41,7 +39,10 @@ const handler = (req: NextApiRequest, res: NextApiResponse) => {
}

// メッセージをクライアントのキューに追加
messagesPerClient[clientId].messages.push({ id: nextId++, message })
messagesPerClient[clientId].messages.push({
timestamp: Date.now(),
message,
})
messagesPerClient[clientId].lastAccessed = Date.now()

res.status(201).json({ message: 'Successfully sent' })
Expand All @@ -51,19 +52,21 @@ const handler = (req: NextApiRequest, res: NextApiResponse) => {
messagesPerClient[clientId] = { messages: [], lastAccessed: Date.now() }
}

const lastId = parseInt(req.query.lastId as string, 10) || 0
const lastTimestamp = parseInt(req.query.lastTimestamp as string, 10) || 0

// クライアントのキューから新しいメッセージを取得
const clientQueue = messagesPerClient[clientId]
const newMessages = clientQueue.messages.filter((msg) => msg.id > lastId)
const newMessages = clientQueue.messages.filter(
(msg) => msg.timestamp > lastTimestamp
)

console.log(newMessages)

res.status(200).json({ messages: newMessages })

// 取得済みのメッセージをキューから削除
clientQueue.messages = clientQueue.messages.filter(
(msg) => msg.id <= lastId
(msg) => msg.timestamp <= lastTimestamp
)
clientQueue.lastAccessed = Date.now()
} else {
Expand Down
20 changes: 10 additions & 10 deletions src/pages/send-message.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ const SendMessage = () => {
e?.preventDefault()
if (!message.trim() || !clientId.trim()) return

const url = new URL('/api/messages', window.location.origin)
url.searchParams.append('clientId', clientId.trim())

try {
const res = await fetch(
`/api/messages?clientId=${encodeURIComponent(clientId)}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
}
)
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
})

if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`)
Expand Down

0 comments on commit a86e368

Please sign in to comment.