All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 1m4s
54 lines
1.6 KiB
TypeScript
54 lines
1.6 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
|
|
last_message_type: 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 and type
|
|
const result = await query<ChatRow>(
|
|
`SELECT c.id, c.jid, c.name, c.is_group, c.unread_count, c.last_message_at,
|
|
c.last_message_type,
|
|
(SELECT COALESCE(content, caption) 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 || '',
|
|
lastMessageType: row.last_message_type || 'text'
|
|
}))
|
|
})
|