Add chat page and chat server
This commit is contained in:
87
inventory-server/chat/routes.js
Normal file
87
inventory-server/chat/routes.js
Normal file
@@ -0,0 +1,87 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
|
||||
// Get all active users for the "view as" dropdown
|
||||
router.get('/users', async (req, res) => {
|
||||
try {
|
||||
const result = await global.pool.query(`
|
||||
SELECT id, username, name, type, active
|
||||
FROM users
|
||||
WHERE active = true AND type = 'user'
|
||||
ORDER BY name ASC
|
||||
`);
|
||||
|
||||
res.json({
|
||||
status: 'success',
|
||||
users: result.rows
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', error);
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
error: 'Failed to fetch users',
|
||||
details: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Get rooms for a specific user
|
||||
router.get('/users/:userId/rooms', async (req, res) => {
|
||||
const { userId } = req.params;
|
||||
|
||||
try {
|
||||
// Get rooms where the user is a member
|
||||
const result = await global.pool.query(`
|
||||
SELECT DISTINCT r.id, r.name, r.fname, r.t as type, r.msgs, r.lm as last_message_date
|
||||
FROM room r, subscription s
|
||||
WHERE s.rid = r.mongo_id
|
||||
AND s.u->>'_id' = (SELECT mongo_id FROM users WHERE id = $1)
|
||||
AND r.archived IS NOT TRUE
|
||||
ORDER BY r.lm DESC NULLS LAST
|
||||
LIMIT 50
|
||||
`, [userId]);
|
||||
|
||||
res.json({
|
||||
status: 'success',
|
||||
rooms: result.rows
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching user rooms:', error);
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
error: 'Failed to fetch user rooms',
|
||||
details: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Get messages for a specific room
|
||||
router.get('/rooms/:roomId/messages', async (req, res) => {
|
||||
const { roomId } = req.params;
|
||||
const { limit = 50, offset = 0 } = req.query;
|
||||
|
||||
try {
|
||||
const result = await global.pool.query(`
|
||||
SELECT m.id, m.msg, m.ts, m.u, m._updatedat
|
||||
FROM message m
|
||||
JOIN room r ON m.rid = r.mongo_id
|
||||
WHERE r.id = $1
|
||||
ORDER BY m.ts DESC
|
||||
LIMIT $2 OFFSET $3
|
||||
`, [roomId, limit, offset]);
|
||||
|
||||
res.json({
|
||||
status: 'success',
|
||||
messages: result.rows
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching messages:', error);
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
error: 'Failed to fetch messages',
|
||||
details: error.message
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user