-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
93 lines (77 loc) · 2.54 KB
/
index.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
import "dotenv/config";
import express from "express";
// import ServerlessHttp from "serverless-http";
import cors from "cors";
import multer from 'multer';
import path from 'path';
import initKnex from "knex";
import configuration from "./knexfile.js";
const knex = initKnex(configuration);
import signinRoutes from './routes/signin-signup-routes.js';
import contactRoutes from './routes/contact-routes.js';
import dealRoutes from './routes/deals-routes.js';
const app = express();
const PORT = process.env.PORT || 8080;
const BACKEND_URL = process.env.BACKEND_URL || `http://localhost:${PORT}`;
app.use(cors());
app.use(express.json());
app.use(express.static('public/images'));
// Set storage engine
const storage = multer.diskStorage({
destination: 'public/images',
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init upload
const upload = multer({
storage: storage,
fileFilter: function(req, file, cb) {
checkFileType(file, cb);
}
}).single('profileImage');
// Check file type
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb('Error: Images Only!');
}
}
app.get("/home", (req, res) => {
res.send("Welcome to my API");
});
app.use('/api/userauth', signinRoutes);
app.use('/api/contacts', contactRoutes);
app.use('/api/deals', dealRoutes);
app.use('/public/images', express.static('public/images'));
app.post('/api/upload', (req, res) => {
upload(req, res, async (err) => {
if (err) {
res.status(400).json({ message: err });
} else {
if (req.file == undefined) {
res.status(400).json({ message: 'No file selected!' });
} else {
const contactId = req.body.contact_id;
const filePath = `public/images/${req.file.filename}`;
try {
// Update the database with the file path
await knex('contacts').where('id', contactId).update({
profile_picture: `${BACKEND_URL}/${filePath}`
});
res.status(200).json({ message: 'File uploaded and contact updated!', file: `${BACKEND_URL}/${filePath}` });
} catch (error) {
res.status(500).json({ message: 'Database update failed' });
}
}
}
});
});
app.listen(PORT, () => {
console.log(`Listening at ${BACKEND_URL}`);
});
// module.exports.handler = ServerlessHttp(app);