Spaces:
Sleeping
Sleeping
File size: 2,403 Bytes
83f4356 | 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 | const { supabaseAdmin } = require('../config/supabase');
const { success, error, serverError } = require('../utils/response');
const { parsePagination } = require('../utils/pagination');
/**
* GET /api/notifications — list user's notifications (paginated)
*/
async function listNotifications(req, res) {
try {
const { page, limit, offset } = parsePagination(req.query);
const { data, error: dbError, count } = await supabaseAdmin
.from('notifications')
.select('*', { count: 'exact' })
.eq('user_id', req.user.id)
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1);
if (dbError) return error(res, dbError.message, 400);
return success(res, data, { page, limit, total: count });
} catch (err) {
console.error('listNotifications error:', err);
return serverError(res);
}
}
/**
* PATCH /api/notifications/:id/read
*/
async function markRead(req, res) {
try {
const { data, error: dbError } = await supabaseAdmin
.from('notifications')
.update({ is_read: true })
.eq('id', req.params.id)
.eq('user_id', req.user.id)
.select()
.single();
if (dbError || !data) return error(res, 'Notification not found', 404);
return success(res, data);
} catch (err) {
console.error('markRead error:', err);
return serverError(res);
}
}
/**
* PATCH /api/notifications/read-all — mark all as read
*/
async function markAllRead(req, res) {
try {
await supabaseAdmin
.from('notifications')
.update({ is_read: true })
.eq('user_id', req.user.id)
.eq('is_read', false);
return success(res, { message: 'All notifications marked as read' });
} catch (err) {
console.error('markAllRead error:', err);
return serverError(res);
}
}
/**
* GET /api/notifications/unread-count
*/
async function unreadCount(req, res) {
try {
const { count, error: dbError } = await supabaseAdmin
.from('notifications')
.select('id', { count: 'exact', head: true })
.eq('user_id', req.user.id)
.eq('is_read', false);
if (dbError) return error(res, dbError.message, 400);
return success(res, { unread_count: count || 0 });
} catch (err) {
console.error('unreadCount error:', err);
return serverError(res);
}
}
module.exports = { listNotifications, markRead, markAllRead, unreadCount };
|