Spaces:
Sleeping
Sleeping
File size: 9,690 Bytes
55ffa7e 97b638a 55ffa7e 97b638a 71a9cd6 97b638a 71a9cd6 dd39145 71a9cd6 97b638a 71a9cd6 97b638a 825c78a 97b638a 825c78a 97b638a 55ffa7e 97b638a 55ffa7e 97b638a 55ffa7e 97b638a 55ffa7e 97b638a 55ffa7e 97b638a 825c78a 97b638a 71a9cd6 c3e1e0e 71a9cd6 c3e1e0e 71a9cd6 55ffa7e c3e1e0e 71a9cd6 | 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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | const { supabaseAdmin, supabaseServiceRole } = require('../config/supabase');
const { success, created, error, notFound, forbidden, serverError } = require('../utils/response');
const { parsePagination } = require('../utils/pagination');
const { uploadMultipleToStorage } = require('../services/storage.service');
/**
* Adjust a denormalised counter on a post. Runs as the service role so the
* counter functions do not have to be callable by end users, and only after
* the like/bookmark row itself has actually changed.
*/
async function bumpCounter(fnName, postId) {
const { error: rpcError } = await supabaseServiceRole.rpc(fnName, { p_post_id: postId });
if (rpcError) console.error(`${fnName} failed for post ${postId}:`, rpcError);
}
/**
* Toggle a (user_id, post_id) row in `table`. Returns true if the row exists
* afterwards. The counter moves only when a row was really added or removed,
* so double clicks and concurrent requests cannot make it drift.
*/
async function toggleInteraction(table, userId, postId, incrementFn, decrementFn) {
const { data: removed, error: deleteError } = await supabaseAdmin
.from(table)
.delete()
.eq('user_id', userId)
.eq('post_id', postId)
.select('post_id');
if (deleteError) throw deleteError;
if (removed && removed.length > 0) {
await bumpCounter(decrementFn, postId);
return false;
}
const { error: insertError } = await supabaseAdmin
.from(table)
.insert({ user_id: userId, post_id: postId });
if (insertError) {
// 23505: a concurrent request already added the row β it is on, uncounted here.
if (insertError.code === '23505') return true;
throw insertError;
}
await bumpCounter(incrementFn, postId);
return true;
}
/**
* POST /api/posts β create a community post (NGO only)
*/
async function createPost(req, res) {
try {
const { content, plant_id, latitude, longitude, address, post_type } = req.body;
let imageUrls = [];
if (req.files && req.files.length > 0) {
imageUrls = await uploadMultipleToStorage('post-images', req.files);
}
const postData = {
author_id: req.user.id,
content: content || null,
image_urls: imageUrls,
plant_id: plant_id || null,
post_type: post_type || 'normal',
};
if (latitude && longitude) {
postData.latitude = parseFloat(latitude);
postData.longitude = parseFloat(longitude);
postData.address = address || null;
// `location` is trigger-maintained from latitude/longitude (migration 14)
}
const { data, error: dbError } = await supabaseAdmin
.from('posts')
.insert(postData)
.select()
.single();
if (dbError) return error(res, dbError.message, 400);
return created(res, data);
} catch (err) {
console.error('createPost error:', err);
return serverError(res);
}
}
/**
* GET /api/posts β community feed (followed NGOs first, then recent)
*/
async function getFeed(req, res) {
try {
const { page, limit, offset } = parsePagination(req.query);
// Get list of NGOs the user follows
const { data: follows } = await supabaseAdmin
.from('follows')
.select('following_id')
.eq('follower_id', req.user.id);
const followedIds = (follows || []).map((f) => f.following_id);
// Fetch posts sorted: followed NGOs first, then by recency
let query = supabaseAdmin
.from('posts')
.select('*, profiles!posts_author_id_fkey(username, display_name, avatar_url, role)', { count: 'exact' })
.order('created_at', { ascending: false })
.range(offset, offset + limit - 1);
const { data, error: dbError, count } = await query;
if (dbError) return error(res, dbError.message, 400);
// Sort: followed posts first, then rest by date
const sorted = (data || []).sort((a, b) => {
const aFollowed = followedIds.includes(a.author_id) ? 0 : 1;
const bFollowed = followedIds.includes(b.author_id) ? 0 : 1;
if (aFollowed !== bFollowed) return aFollowed - bFollowed;
return new Date(b.created_at) - new Date(a.created_at);
});
// Check if current user has liked/bookmarked each post
const postIds = sorted.map((p) => p.id);
const [likesResult, bookmarksResult] = await Promise.all([
supabaseAdmin.from('likes').select('post_id').eq('user_id', req.user.id).in('post_id', postIds),
supabaseAdmin.from('bookmarks').select('post_id').eq('user_id', req.user.id).in('post_id', postIds),
]);
const likedSet = new Set((likesResult.data || []).map((l) => l.post_id));
const bookmarkedSet = new Set((bookmarksResult.data || []).map((b) => b.post_id));
const enriched = sorted.map((post) => ({
...post,
is_liked: likedSet.has(post.id),
is_bookmarked: bookmarkedSet.has(post.id),
}));
return success(res, enriched, { page, limit, total: count });
} catch (err) {
console.error('getFeed error:', err);
return serverError(res);
}
}
/**
* GET /api/posts/:id β single post
*/
async function getPost(req, res) {
try {
const { data, error: dbError } = await supabaseAdmin
.from('posts')
.select('*, profiles!posts_author_id_fkey(username, display_name, avatar_url)')
.eq('id', req.params.id)
.single();
if (dbError || !data) return notFound(res, 'Post not found');
// Check user interactions
const [likeResult, bookmarkResult] = await Promise.all([
supabaseAdmin.from('likes').select('user_id').eq('post_id', data.id).eq('user_id', req.user.id).single(),
supabaseAdmin.from('bookmarks').select('user_id').eq('post_id', data.id).eq('user_id', req.user.id).single(),
]);
return success(res, {
...data,
is_liked: !!likeResult.data,
is_bookmarked: !!bookmarkResult.data,
});
} catch (err) {
console.error('getPost error:', err);
return serverError(res);
}
}
/**
* DELETE /api/posts/:id β delete own post
*/
async function deletePost(req, res) {
try {
const { data: post } = await supabaseAdmin.from('posts').select('author_id').eq('id', req.params.id).single();
if (!post) return notFound(res, 'Post not found');
if (post.author_id !== req.user.id) return forbidden(res);
const { error: deleteError } = await supabaseAdmin.from('posts').delete().eq('id', req.params.id);
if (deleteError) {
console.error('deletePost error:', deleteError);
return serverError(res, 'Could not delete the post');
}
return success(res, { message: 'Post deleted' });
} catch (err) {
console.error('deletePost error:', err);
return serverError(res);
}
}
/**
* POST /api/posts/:id/like β toggle like
*/
async function toggleLike(req, res) {
try {
const liked = await toggleInteraction('likes', req.user.id, req.params.id, 'increment_likes', 'decrement_likes');
return success(res, { liked });
} catch (err) {
// 23503: the post does not exist
if (err?.code === '23503') return notFound(res, 'Post not found');
console.error('toggleLike error:', err);
return serverError(res);
}
}
/**
* POST /api/posts/:id/bookmark β toggle bookmark
*/
async function toggleBookmark(req, res) {
try {
const bookmarked = await toggleInteraction('bookmarks', req.user.id, req.params.id, 'increment_bookmarks', 'decrement_bookmarks');
return success(res, { bookmarked });
} catch (err) {
if (err?.code === '23503') return notFound(res, 'Post not found');
console.error('toggleBookmark error:', err);
return serverError(res);
}
}
/**
* GET /api/posts/bookmarks β user's bookmarked posts
*/
async function myBookmarks(req, res) {
try {
const { data, error: dbError } = await supabaseAdmin
.from('bookmarks')
.select('post_id, posts!inner(*, profiles!posts_author_id_fkey(username, display_name, avatar_url))')
.eq('user_id', req.user.id)
.order('created_at', { ascending: false });
if (dbError) return error(res, dbError.message, 400);
const posts = (data || []).map((b) => ({ ...b.posts, is_bookmarked: true }));
return success(res, posts);
} catch (err) {
console.error('myBookmarks error:', err);
return serverError(res);
}
}
/**
* GET /api/posts/map β get all plantation posts for map rendering
*/
async function mapPlantations(req, res) {
try {
const { minLng, minLat, maxLng, maxLat } = req.query;
if ([minLng, minLat, maxLng, maxLat].some((v) => v === undefined)) {
return error(res, 'minLng, minLat, maxLng, maxLat query params are required', 400);
}
const bbox = {
min_lng: parseFloat(minLng),
min_lat: parseFloat(minLat),
max_lng: parseFloat(maxLng),
max_lat: parseFloat(maxLat),
};
if (Object.values(bbox).some((v) => Number.isNaN(v))) {
return error(res, 'bbox query params must be valid numbers', 400);
}
const MAX_MAP_RESULTS = 500;
const { data, error: dbError } = await supabaseAdmin.rpc('posts_in_bbox', {
...bbox,
max_results: MAX_MAP_RESULTS,
});
if (dbError) {
console.error('mapPlantations RPC error:', dbError);
return error(res, dbError.message, 400);
}
// Authenticated endpoint: cache in the user's browser only, never a shared cache.
res.set('Cache-Control', 'private, max-age=60, stale-while-revalidate=60');
return success(res, data, { truncated: (data?.length || 0) >= MAX_MAP_RESULTS });
} catch (err) {
console.error('mapPlantations error:', err);
return serverError(res);
}
}
module.exports = { createPost, getFeed, getPost, deletePost, toggleLike, toggleBookmark, myBookmarks, mapPlantations };
|