-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
95 lines (81 loc) · 3.22 KB
/
index.js
File metadata and controls
95 lines (81 loc) · 3.22 KB
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
require('dotenv').config()
const express = require("express");
const helmet = require("helmet");
const axios = require("axios");
const sharp = require("sharp");
const rateLimit = require('express-rate-limit');
const app = express();
app.use(helmet());
app.use((_req, res, next) => {
if (process.env.ALLOWED_ORIGINS) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
} else {
res.setHeader('Access-Control-Allow-Origin', '*');
}
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
if (process.env.RATE_LIMIT_TIME && process.env.RATE_LIMIT_AMOUNT) {
const limiter = rateLimit({
windowMs: 60 * parseInt(process.env.RATE_LIMIT_TIME), // in example 60 * 15000 = 15 minutes
max: parseInt(process.env.RATE_LIMIT_AMOUNT), // Limit each IP to X-amount of requests per X-amount of minutes (windowMs)
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
})
// Apply the rate limiting middleware to all requests
app.use(limiter);
}
app.get("/", function (_req, res) {
res.send("Imgsharp - a high performing Node.js Image Processing Service.");
});
app.get("/tx/*", async (req, res) => {
try {
if (req.params[0]) {
const uri = encodeURI(req.params[0]);
const query = req.query;
console.log("tx", query, uri);
const ref = req.get('Referrer')
console.log("Referrer", ref);
res.header['x-imgsharp-referrer', ref]
axios({ url: uri, responseType: "arraybuffer" })
.then((arraybuffer) => {
const data = arraybuffer.data;
const tx = {};
if (query.w) {
tx.width = parseInt(query.w);
}
if (query.h) {
tx.height = parseInt(query.h);
} else if (query.aspect) {
const a = query.aspect.split(":");
const ratio = parseInt(a[0]) / parseInt(a[1])
tx.height = Math.round(tx.width / ratio);
}
sharp(data)
.resize(tx)
.withMetadata()
.webp({ quality: 90 })
.toBuffer()
.then((output) => {
res.contentType("image/webp");
res.end(output);
})
.catch((sharpErr) => {
console.error("sharpErr", sharpErr);
res.status(500).send();
});
})
.catch((err) => {
console.error("axiosErr", err);
res.status(500).send();
});
} else {
console.error("req.params[0] missing");
res.status(500).send();
}
} catch (error) {
res.status(500).send();
}
});
app.listen(3000);