const { query } = require('../database/db'); class Camera { /** * Get all cameras * @returns {array} - All cameras */ static async getAll() { try { const result = await query('SELECT * FROM cameras ORDER BY name', []); return result.rows.map(this.formatRecord); } catch (error) { console.error('Error getting all cameras:', error); throw error; } } /** * Get camera by ID * @param {string} id - Camera ID * @returns {object|null} - Camera or null */ static async getById(id) { try { const result = await query('SELECT * FROM cameras WHERE id = $1', [id]); if (result.rows.length === 0) return null; return this.formatRecord(result.rows[0]); } catch (error) { console.error('Error getting camera by ID:', error); throw error; } } /** * Get cameras by floor * @param {string} floorId - Floor ID * @returns {array} - Cameras on floor */ static async getByFloor(floorId) { try { const result = await query('SELECT * FROM cameras WHERE floor_id = $1', [floorId]); return result.rows.map(this.formatRecord); } catch (error) { console.error('Error getting cameras by floor:', error); throw error; } } /** * Create a new camera * @param {object} cameraData - Camera data * @returns {object} - Created camera */ static async create(cameraData) { try { const { id, name, cameraType, rtspUrl, floorId, model, status } = cameraData; await query(` INSERT INTO cameras (id, name, camera_type, rtsp_url, floor_id, model, status) VALUES ($1, $2, $3, $4, $5, $6, $7) `, [ id, name, cameraType, rtspUrl || null, floorId || null, model || null, status || 'offline' ]); return this.getById(id); } catch (error) { console.error('Error creating camera:', error); throw error; } } /** * Update camera status * @param {string} id - Camera ID * @param {string} status - New status (online, offline, error) * @returns {object|null} - Updated camera or null */ static async updateStatus(id, status) { try { const result = await query(` UPDATE cameras SET status = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2 `, [status, id]); if (result.rowCount === 0) return null; return this.getById(id); } catch (error) { console.error('Error updating camera status:', error); throw error; } } /** * Delete a camera * @param {string} id - Camera ID * @returns {boolean} - True if deleted */ static async delete(id) { try { const result = await query('DELETE FROM cameras WHERE id = $1', [id]); return result.rowCount > 0; } catch (error) { console.error('Error deleting camera:', error); throw error; } } /** * Format database record to camelCase * @param {object} record - Database record * @returns {object} - Formatted record */ static formatRecord(record) { return { id: record.id, name: record.name, cameraType: record.camera_type, rtspUrl: record.rtsp_url, floorId: record.floor_id, model: record.model, status: record.status, createdAt: record.created_at, updatedAt: record.updated_at }; } } module.exports = Camera;