-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
60 lines (49 loc) · 1.79 KB
/
server.js
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
import express from 'express';
import bodyParser from 'body-parser';
import axios from 'axios';
import imageType from 'image-type';
import { filterImageFromURL, deleteLocalFiles } from './util/util.js';
// Init the Express application
const app = express();
// Set the network port
const port = process.env.PORT || 8082;
// Use the body parser middleware for post requests
app.use(bodyParser.json());
// @TODO1 IMPLEMENT A RESTFUL ENDPOINT
// GET /filteredimage?image_url={{URL}}
// endpoint to filter an image from a public url.
// IT SHOULD
// 1. validate the image_url query
// 2. call filterImageFromURL(image_url) to filter the image
// 3. send the resulting file in the response
// 4. deletes any files on the server on finish of the response
// QUERY PARAMETERS
// image_url: URL of a publicly accessible image
// RETURNS
// the filtered image file [!!TIP res.sendFile(filteredpath); might be useful]
app.get('/filteredimage', async (req, res) => {
const { image_url } = req.query;
if (!image_url) {
return res.status(400).send('image_url query parameter is required.');
}
try {
const response = await axios.get(image_url, { responseType: 'arraybuffer' });
const imageBuffer = Buffer.from(response.data);
const { ext, mime } = imageType(imageBuffer) || { ext: 'jpg', mime: 'image/jpeg' };
res.set('Content-Type', mime);
res.status(200).send(imageBuffer);
} catch (error) {
res.status(500).send(`An error occurred: ${error.message}`);
}
});
//! END @TODO1
// Root Endpoint
// Displays a simple message to the user
app.get("/", async (req, res) => {
res.send("try GET /filteredimage?image_url={{}}");
});
// Start the Server
app.listen(port, () => {
console.log(`server running http://localhost:${port}`);
console.log(`press CTRL+C to stop server`);
});