-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
353 lines (305 loc) · 9.53 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
require('dotenv').config()
const express = require('express');
const ejs = require('ejs');
const path = require('path');
const app = express();
const expressLayouts = require('express-ejs-layouts');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const compression = require('compression');
const cron = require('node-cron');
const axios = require('axios');
// const apiRoute = require('./api/routes/uigeneratorkit.routes');
const LinearGradientColor = require('./api/models/lineargradient.model');
const SocialMediaColors = require('./api/models/socialmedia.model');
const UiGeneratorkitPalette = require('./api/models/uigeneratorkit.model');
const port = process.env.PORT || 3000;
// const connectDB= require("./libs/db");
const multer = require("multer");
// Schedule a task to run every 14 minutes
cron.schedule('*/14 * * * *', () => {
console.log('Calling uigenkit API every 14 minutes...');
axios.get('https://uigenkit.in/api/test')
.then(response => {
// console.log('API response:', response.data);
})
.catch(error => {
console.error('Error calling the API:', error);
});
});
console.log('Cron job started');
// const sharp = require("sharp");
const mongooseSets={
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
};
// Connecting to the database
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI, mongooseSets);
console.log("MongoDB Connected...");
} catch (error) {
console.error(error.message);
process.exit(1);
}
};
connectDB();
//dataPaths
//middlewares
app.use(cors());
app.use('/uploads', express.static(path.join(__dirname + '/uploads')));
app.use(compression({
level:6,
threshold:10*1000, //10kb
filter: (req, res)=>{
if (req.headers['x-no-compression']) {
// don't compress responses with this request header
return false
}
// fallback to standard filter function
return compression.filter(req, res)
}
}))
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === "OPTIONS") {
res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
return res.status(200).json({});
}
next();
});
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
app.use(expressLayouts);
// app.use('/api',apiRoute);
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "uploads");
},
filename: function(req, file, cb) {
cb(
null,
file.fieldname + "-" + Date.now() + path.extname(file.originalname)
);
}
});
const upload = multer({
storage: storage
});
app.post("/preview", upload.single("image"), (req, res, next) => {
const file = req.file;
var ext;
if (!file) {
const error = new Error("Please Upload a file");
error.httpStatusCode = 404;
return next(error);
}
if (file.mimetype == "image/jpeg") {
ext = "jpg";
}
if (file.mimetype == "image/png") {
ext = "png";
}
console.log(file.path)
res.render("./partials/imageoptimizer/preview", { url: file.path, name: file.filename, ext: ext });
});
app.post("/compress/uploads/:name/:ext", (req, res) => {
let name =req.params.name;
let ext =req.params.ext;
console.log(name);
console.log(__dirname);
let file =name;
console.log(file);
const fileFormat = ext;
if (fileFormat === 'svg') {
console.log('svg not processed with sharp');
return;
}
let sh = sharp('./uploads/' + file);
if (fileFormat === 'jpg' || fileFormat === 'jpeg') {
sh = sh.jpeg({ quality: 70 });
} else if (fileFormat === 'png') {
sh = sh.png({ quality: 70 });
}
sh.toFile('output/' + file, function (err, info) {
// console.log(info);
if (err) {
console.log('error in image optimization');
return;
}
});
setTimeout(()=>{
res.download(path.join(__dirname,`output/${file}`));
},1000)
});
app.get("/", function(req, res) {
res.render("./partials/home");
});
app.get("/home", function(req, res) {
// res.setHeader('Cache-Control', 'public, max-age=86400');
res.render("./partials/home");
});
app.get("/imageoptimizer", function(req, res) {
res.render("./partials/imageoptimizer/imageoptimizer");
});
app.get("/api/test", function(req, res) {
res.send("test ".repeat(100));
});
app.get("/neumorphism", function(req, res) {
res.render("./partials/neumorphism/neumorphism");
});
app.get("/pattern", function(req, res) {
res.render("./partials/bgPattern/bgPattern");
});
app.get("/colorpalette", function(req, res) {
res.render("./partials/colorPalette/colorPalette");
});
app.get("/lineargradient", function(req, res) {
res.render("./partials/linearGradient/linearGradient");
});
app.get("/about", function(req, res) {
res.render("./partials/about/about");
});
app.get("/api/custompalette", function(req, res) {
UiGeneratorkitPalette.find()
.then(customPalette => {
res.status(200).send(customPalette);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving the customPalette."
});
});
});
app.get("/api/socialmediapalette", function(req, res) {
SocialMediaColors.find()
.then(socialMediaColors => {
res.status(200).send(socialMediaColors);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving the socialMediaColors."
});
});
});
app.get("/api/lineargradientcolors", function(req, res) {
LinearGradientColor.find()
.then(gradients => {
res.status(200).send(gradients);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving the gradients."
});
});
});
// UPDATE
app.put("/api/updatelikesbyid/:paletteid", function(req, res) {
// Validate Request
let paletteid =req.params.paletteid;
let likes =req.body.likes;
let isLiked =req.body.isLiked;
console.log(paletteid);
UiGeneratorkitPalette.findOneAndUpdate(
{ "id": paletteid}, {
likes: req.body.likes,
isLiked:req.body.isLiked,
}, {new: true})
.then(palette => {
if(!palette) {
return res.status(404).send({
message: "palette not found with id " +paletteid
});
}
UiGeneratorkitPalette.find()
.then(customPalette => {
res.send(customPalette);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving the customPalette."
});
});
}).catch(err => {
return res.status(500).send({
message:err.message+ "Error updating palette with id " +paletteid
});
});
});
app.post("/api/custompalette", function(req, res) {
const lineargradient = new UiGeneratorkitPalette({
id: req.body.id ,
createdAt: req.body.createdAt ,
isLiked: req.body.isLiked ,
likes: req.body.likes,
hex: {
layer1:req.body.hex.layer1,
layer2:req.body.hex.layer2,
layer3:req.body.hex.layer3,
layer4:req.body.hex.layer4,
},
rgb: {
layer1:req.body.rgb.layer1,
layer2:req.body.rgb.layer2,
layer3:req.body.rgb.layer3,
layer4:req.body.rgb.layer4,
},
rgba: {
layer1:req.body.rgba.layer1,
layer2:req.body.rgba.layer2,
layer3:req.body.rgba.layer3,
layer4:req.body.rgba.layer4,
}
});
lineargradient.save(function(err, rec) {
if(err) {
return res.status(400).send("error while creting a post")
}
UiGeneratorkitPalette.find()
.then(customPalette => {
res.send(customPalette);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving the customPalette."
});
});
})
});
app.post('/lineargradientposts', function(req, res) {
const lineargradient = new LinearGradientColor({
gradientName: req.body.gradientName,
colorStopOne: req.body.colorStopOne,
colorStopTwo: req.body.colorStopTwo
})
// const lineargradient = new SocialMediaColors({
// brandName: req.body.brandName,
// colorFormats: {
// hex:req.body.colorFormats.hex,
// hashhex:req.body.colorFormats.hashhex,
// rgb:req.body.colorFormats.rgb,
// rgba:req.body.colorFormats.rgba,
// }
// })
console.log(req.body);
lineargradient.save(function(err, rec) {
if(err) {
return res.status(400).send("error while creting a post")
}
console.log(rec);
res.send(rec);
})
})
app.listen(port, () => console.log(`Server started on Port ${port}`));
function getExtension(filename) {
let ext = path.extname(filename || '').split('.');
return ext[ext.length - 1];
}