Set up backend API server with Express and Prisma

- Initialize Node.js/Express backend project structure
- Configure TypeScript for backend development
- Set up Prisma ORM with MySQL database schema
- Implement authentication middleware with Clerk
- Create photo upload endpoint with EXIF extraction
- Build report CRUD endpoints (create, read, delete)
- Add file upload handling with Multer
- Configure CORS and security middleware (helmet)
- Set up error handling and validation
- Create development environment configuration

Task 21 complete: Backend foundation ready for report submissions
This commit is contained in:
2025-11-16 17:29:26 +00:00
parent 7dc1ff740b
commit c0ec28c5c9
15 changed files with 3191 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
});
export default prisma;

View File

@@ -0,0 +1,240 @@
import { Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import { reportService } from '../services/reportService';
import { extractExifData } from '../utils/exif';
import path from 'path';
export class ReportController {
async uploadPhoto(req: AuthRequest, res: Response) {
try {
if (!req.file) {
return res.status(400).json({
error: {
code: 'NO_FILE',
message: 'No file uploaded',
timestamp: new Date().toISOString(),
},
});
}
// Extract EXIF data
const exifData = await extractExifData(req.file.path);
// Generate URL for the uploaded file
const fileUrl = `/uploads/${req.file.filename}`;
res.json({
url: fileUrl,
exifData: {
latitude: exifData.latitude,
longitude: exifData.longitude,
timestamp: exifData.timestamp,
},
});
} catch (error) {
console.error('Error uploading photo:', error);
res.status(500).json({
error: {
code: 'UPLOAD_ERROR',
message: 'Failed to upload photo',
timestamp: new Date().toISOString(),
},
});
}
}
async createReport(req: AuthRequest, res: Response) {
try {
if (!req.userId) {
return res.status(401).json({
error: {
code: 'UNAUTHORIZED',
message: 'User not authenticated',
timestamp: new Date().toISOString(),
},
});
}
const {
latitude,
longitude,
locationSource,
litterType,
quantity,
description,
photoUrls,
photoTimestamp,
environmentalConcerns,
} = req.body;
// Validation
if (!latitude || !longitude) {
return res.status(400).json({
error: {
code: 'VALIDATION_ERROR',
message: 'Latitude and longitude are required',
timestamp: new Date().toISOString(),
},
});
}
if (!photoUrls || photoUrls.length === 0) {
return res.status(400).json({
error: {
code: 'VALIDATION_ERROR',
message: 'At least one photo is required',
timestamp: new Date().toISOString(),
},
});
}
const report = await reportService.createReport({
userId: req.userId,
latitude: parseFloat(latitude),
longitude: parseFloat(longitude),
locationSource,
photoUrls,
photoTimestamp: photoTimestamp ? new Date(photoTimestamp) : undefined,
litterType,
quantity,
description,
environmentalConcerns,
});
res.status(201).json(report);
} catch (error) {
console.error('Error creating report:', error);
res.status(500).json({
error: {
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to create report',
timestamp: new Date().toISOString(),
},
});
}
}
async getReports(req: AuthRequest, res: Response) {
try {
const {
startDate,
endDate,
litterTypes,
quantities,
verificationStatus,
north,
south,
east,
west,
} = req.query;
const filters: any = {};
if (startDate) filters.startDate = new Date(startDate as string);
if (endDate) filters.endDate = new Date(endDate as string);
if (litterTypes) filters.litterTypes = (litterTypes as string).split(',');
if (quantities) filters.quantities = (quantities as string).split(',');
if (verificationStatus) filters.verificationStatus = (verificationStatus as string).split(',');
if (north && south && east && west) {
filters.bounds = {
north: parseFloat(north as string),
south: parseFloat(south as string),
east: parseFloat(east as string),
west: parseFloat(west as string),
};
}
const reports = await reportService.getReports(filters);
res.json(reports);
} catch (error) {
console.error('Error fetching reports:', error);
res.status(500).json({
error: {
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to fetch reports',
timestamp: new Date().toISOString(),
},
});
}
}
async getReportById(req: AuthRequest, res: Response) {
try {
const { id } = req.params;
const report = await reportService.getReportById(id);
if (!report) {
return res.status(404).json({
error: {
code: 'RESOURCE_NOT_FOUND',
message: 'Report not found',
timestamp: new Date().toISOString(),
},
});
}
res.json(report);
} catch (error) {
console.error('Error fetching report:', error);
res.status(500).json({
error: {
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to fetch report',
timestamp: new Date().toISOString(),
},
});
}
}
async deleteReport(req: AuthRequest, res: Response) {
try {
if (!req.userId) {
return res.status(401).json({
error: {
code: 'UNAUTHORIZED',
message: 'User not authenticated',
timestamp: new Date().toISOString(),
},
});
}
const { id } = req.params;
await reportService.deleteReport(id, req.userId);
res.status(204).send();
} catch (error: any) {
console.error('Error deleting report:', error);
if (error.message === 'Report not found') {
return res.status(404).json({
error: {
code: 'RESOURCE_NOT_FOUND',
message: 'Report not found',
timestamp: new Date().toISOString(),
},
});
}
if (error.message === 'Unauthorized to delete this report') {
return res.status(403).json({
error: {
code: 'FORBIDDEN',
message: 'You are not authorized to delete this report',
timestamp: new Date().toISOString(),
},
});
}
res.status(500).json({
error: {
code: 'INTERNAL_SERVER_ERROR',
message: 'Failed to delete report',
timestamp: new Date().toISOString(),
},
});
}
}
}
export const reportController = new ReportController();

66
server/src/index.ts Normal file
View File

@@ -0,0 +1,66 @@
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import dotenv from 'dotenv';
import path from 'path';
import reportRoutes from './routes/reportRoutes';
// Load environment variables
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(helmet());
app.use(cors({
origin: process.env.CORS_ORIGIN || 'http://localhost:5173',
credentials: true,
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve uploaded files
app.use('/uploads', express.static(path.join(__dirname, '../uploads')));
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// API Routes
app.use('/api/reports', reportRoutes);
// Error handling middleware
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error('Error:', err);
if (err.name === 'MulterError') {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({
error: {
code: 'FILE_TOO_LARGE',
message: 'File size exceeds the maximum limit of 5MB',
timestamp: new Date().toISOString(),
},
});
}
}
res.status(500).json({
error: {
code: 'INTERNAL_SERVER_ERROR',
message: err.message || 'An unexpected error occurred',
timestamp: new Date().toISOString(),
},
});
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📍 Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`🔗 API: http://localhost:${PORT}/api`);
});
export default app;

View File

@@ -0,0 +1,56 @@
import { Request, Response, NextFunction } from 'express';
import { clerkClient } from '@clerk/clerk-sdk-node';
export interface AuthRequest extends Request {
userId?: string;
user?: any;
}
export const requireAuth = async (
req: AuthRequest,
res: Response,
next: NextFunction
) => {
try {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
error: {
code: 'UNAUTHORIZED',
message: 'No authorization token provided',
timestamp: new Date().toISOString(),
},
});
}
const token = authHeader.substring(7);
// Verify the session token with Clerk
const session = await clerkClient.sessions.verifySession(token, token);
if (!session) {
return res.status(401).json({
error: {
code: 'INVALID_TOKEN',
message: 'Invalid or expired token',
timestamp: new Date().toISOString(),
},
});
}
// Attach user ID to request
req.userId = session.userId;
next();
} catch (error) {
console.error('Auth middleware error:', error);
return res.status(401).json({
error: {
code: 'UNAUTHORIZED',
message: 'Authentication failed',
timestamp: new Date().toISOString(),
},
});
}
};

View File

@@ -0,0 +1,40 @@
import multer from 'multer';
import path from 'path';
import fs from 'fs';
// Ensure upload directory exists
const uploadDir = process.env.UPLOAD_DIR || './uploads';
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
// Configure storage
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, uploadDir);
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
},
});
// File filter
const fileFilter = (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Invalid file type. Only JPEG, PNG, and WebP images are allowed.'));
}
};
// Configure multer
export const upload = multer({
storage,
fileFilter,
limits: {
fileSize: parseInt(process.env.MAX_FILE_SIZE || '5242880'), // 5MB default
},
});

View File

@@ -0,0 +1,17 @@
import { Router } from 'express';
import { reportController } from '../controllers/reportController';
import { requireAuth } from '../middleware/auth';
import { upload } from '../middleware/upload';
const router = Router();
// Photo upload endpoint (protected)
router.post('/upload', requireAuth, upload.single('photo'), reportController.uploadPhoto.bind(reportController));
// Report CRUD endpoints
router.post('/', requireAuth, reportController.createReport.bind(reportController));
router.get('/', reportController.getReports.bind(reportController));
router.get('/:id', reportController.getReportById.bind(reportController));
router.delete('/:id', requireAuth, reportController.deleteReport.bind(reportController));
export default router;

View File

@@ -0,0 +1,168 @@
import prisma from '../config/database';
import { Prisma } from '@prisma/client';
export interface CreateReportData {
userId: string;
latitude: number;
longitude: number;
locationSource: 'exif' | 'gps' | 'manual';
photoUrls: string[];
photoTimestamp?: Date;
litterType: string;
quantity: string;
description?: string;
environmentalConcerns?: Array<{
type: string;
severity: string;
description: string;
}>;
}
export class ReportService {
async createReport(data: CreateReportData) {
const report = await prisma.report.create({
data: {
userId: data.userId,
latitude: new Prisma.Decimal(data.latitude),
longitude: new Prisma.Decimal(data.longitude),
locationSource: data.locationSource,
photoUrls: data.photoUrls,
photoTimestamp: data.photoTimestamp,
litterType: data.litterType,
quantity: data.quantity,
description: data.description,
environmentalConcerns: data.environmentalConcerns
? {
create: data.environmentalConcerns.map((concern) => ({
concernType: concern.type,
severity: concern.severity,
description: concern.description,
})),
}
: undefined,
},
include: {
user: {
select: {
id: true,
username: true,
avatarUrl: true,
},
},
environmentalConcerns: true,
},
});
return report;
}
async getReports(filters?: {
startDate?: Date;
endDate?: Date;
litterTypes?: string[];
quantities?: string[];
verificationStatus?: string[];
bounds?: { north: number; south: number; east: number; west: number };
}) {
const where: any = {};
if (filters?.startDate || filters?.endDate) {
where.createdAt = {};
if (filters.startDate) where.createdAt.gte = filters.startDate;
if (filters.endDate) where.createdAt.lte = filters.endDate;
}
if (filters?.litterTypes?.length) {
where.litterType = { in: filters.litterTypes };
}
if (filters?.quantities?.length) {
where.quantity = { in: filters.quantities };
}
if (filters?.verificationStatus?.length) {
where.verificationStatus = { in: filters.verificationStatus };
}
if (filters?.bounds) {
where.latitude = {
gte: new Prisma.Decimal(filters.bounds.south),
lte: new Prisma.Decimal(filters.bounds.north),
};
where.longitude = {
gte: new Prisma.Decimal(filters.bounds.west),
lte: new Prisma.Decimal(filters.bounds.east),
};
}
const reports = await prisma.report.findMany({
where,
include: {
user: {
select: {
id: true,
username: true,
avatarUrl: true,
},
},
environmentalConcerns: true,
verifications: true,
},
orderBy: {
createdAt: 'desc',
},
});
return reports;
}
async getReportById(id: string) {
const report = await prisma.report.findUnique({
where: { id },
include: {
user: {
select: {
id: true,
username: true,
avatarUrl: true,
},
},
environmentalConcerns: true,
verifications: {
include: {
user: {
select: {
id: true,
username: true,
},
},
},
},
},
});
return report;
}
async deleteReport(id: string, userId: string) {
// Verify ownership
const report = await prisma.report.findUnique({
where: { id },
select: { userId: true },
});
if (!report) {
throw new Error('Report not found');
}
if (report.userId !== userId) {
throw new Error('Unauthorized to delete this report');
}
await prisma.report.delete({
where: { id },
});
}
}
export const reportService = new ReportService();

33
server/src/utils/exif.ts Normal file
View File

@@ -0,0 +1,33 @@
import exifr from 'exifr';
export interface ExifData {
latitude?: number;
longitude?: number;
timestamp?: Date;
make?: string;
model?: string;
}
export async function extractExifData(filePath: string): Promise<ExifData> {
try {
const exif = await exifr.parse(filePath, {
gps: true,
pick: ['latitude', 'longitude', 'DateTimeOriginal', 'Make', 'Model'],
});
if (!exif) {
return {};
}
return {
latitude: exif.latitude,
longitude: exif.longitude,
timestamp: exif.DateTimeOriginal,
make: exif.Make,
model: exif.Model,
};
} catch (error) {
console.error('Error extracting EXIF data:', error);
return {};
}
}