Files
whatsappNucleo/server/api/messages/[instanceId]/chats.get.ts
josedario87 478f4f8b34
Some checks failed
build-and-deploy / build-and-deploy (push) Failing after 13s
Fix: API de chats con lastMessage y send acepta content
2025-12-02 19:44:06 -06:00

51 lines
1.4 KiB
TypeScript

/**
* GET /api/messages/:instanceId/chats
* Get all chats for an instance
*/
import { query } from '../../../utils/database'
interface ChatRow {
id: string
jid: string
name: string | null
is_group: boolean
unread_count: number
last_message_at: Date | null
last_message: string | null
}
export default defineEventHandler(async (event) => {
const username = getHeader(event, 'x-authentik-username')
if (!username) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
const instanceId = getRouterParam(event, 'instanceId')
// Verify instance exists
const instanceCheck = await query('SELECT id FROM instances WHERE id = $1', [instanceId])
if (instanceCheck.rows.length === 0) {
throw createError({ statusCode: 404, message: 'Instance not found' })
}
// Get chats with last message
const result = await query<ChatRow>(
`SELECT c.id, c.jid, c.name, c.is_group, c.unread_count, c.last_message_at,
(SELECT content FROM messages m WHERE m.chat_id = c.id ORDER BY timestamp DESC LIMIT 1) as last_message
FROM chats c
WHERE c.instance_id = $1
ORDER BY c.last_message_at DESC NULLS LAST`,
[instanceId]
)
return result.rows.map(row => ({
id: row.id,
jid: row.jid,
name: row.name || row.jid.split('@')[0],
isGroup: row.is_group,
unreadCount: row.unread_count,
lastMessageAt: row.last_message_at,
lastMessage: row.last_message || ''
}))
})