| const express = require('express'); |
| const cors = require('cors'); |
| const imageProcessor = require('./image-processing-logic'); |
|
|
| const app = express(); |
| const PORT = process.env.PORT || 7860; |
|
|
| |
| app.use(cors()); |
| app.use(express.json()); |
|
|
| |
| app.get('/ping', (req, res) => { |
| res.status(200).send('pong'); |
| }); |
|
|
| |
| |
| |
| |
| app.post('/api/process-stream', async (req, res) => { |
| try { |
| const { quality, format } = req.query; |
|
|
| if (req.is('multipart/form-data')) { |
| |
| |
| |
| |
| return res.status(400).json({ error: 'Please send image directly as request body, not as form data.' }); |
| } |
| |
| |
| const processedImageStream = imageProcessor.processImage(req, { |
| quality: quality, |
| |
| format: format |
| }); |
| |
| |
| res.setHeader('Content-Type', `image/${format}`); |
| res.setHeader('Content-Disposition', `attachment; filename=compressed_image.${format}`); |
| |
| |
| processedImageStream.on('error', (error) => { |
| console.error('Error in streaming pipeline:', error); |
| res.status(500).json({ error: 'Image processing failed' }); |
| }); |
| |
| processedImageStream.pipe(res); |
|
|
| } catch (error) { |
| console.error('Error in streaming compression route:', error); |
| res.status(500).json({ error: error.message }); |
| } |
| }); |
|
|
| |
| app.use((err, req, res, next) => { |
| console.error(err.stack); |
| res.status(500).json({ error: err.message }); |
| }); |
|
|
| app.listen(PORT, () => { |
| console.log(`Server running on port ${PORT}`); |
| }); |