-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
68 lines (56 loc) · 1.85 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
const express = require('express');
const cors = require('cors');
const path = require('path');
const crypto = require('crypto');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(methodOverride('_method'));
app.use(express.urlencoded({ extended : false }));
let gfs;
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open',
() => {
console.log("mongoose database connection established succesfully");
gfs = Grid(connection.db, mongoose.mongo);
gfs.collection('uploads');
});
const storage = new GridFsStorage({
url: uri,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
app.post('/upload', upload.single('file'), (req, res) => {
res.json({file: req.file, id: req.body});
})
const userRouter = require('./routes/user');
const postsRouter = require('./routes/posts');
const imageRouter = require('./routes/image');
app.use('/user', userRouter);
app.use('/posts', postsRouter);
app.use('/image', imageRouter);
app.listen(port, () => { console.log(`server is running on port: ${port}`)});