-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
91 lines (70 loc) · 2.51 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
const express = require('express');
const trackRoute = express.Router();
const multer = require('multer');
const mongoose = require('mongoose');
const {Readable} = require('stream')
const app = express();
app.use('/tracks', trackRoute);
let db;
mongoose.connect('mongodb://localhost/trackDB', (err, database) => {
if(err){
console.log(`Connection Failed`);
process.exit(1);
}
db = database;
})
// Get tracks
trackRoute.get('/:trackID', (req, res) => {
try {
var trackID = new mongoose.mongo.ObjectId(req.params.trackID);
} catch(err) {
return res.status(400).json({ message: "Invalid trackID in URL parameter. Must be a single String of 12 bytes or a string of 24 hex characters" });
}
res.set('content-type', 'audio/mp3');
res.set('accept-ranges', 'bytes');
let bucket = new mongoose.mongo.GridFSBucket(db, {
bucketName: 'tracks'
});
let downloadStream = bucket.openDownloadStream(trackID);
// console.log(downloadStream);
downloadStream.on('data', (chunk) => {
return res.write(chunk);
});
downloadStream.on('error', (err) => {
res.sendStatus(404);
});
downloadStream.on('end', () => {
res.end();
});
});
// Post
trackRoute.post('/', (req, res) => {
const storage = multer.memoryStorage()
const upload = multer({storage: storage, limits: {fields: 1, fileSize: 12000000, files: 1, parts: 2}})
upload.single('track')(req, res, (err) => {
if(err){
console.log(err);
return res.status(400).json({message: 'upload validation Failed'})
} else if(!req.body.name){
return res.status(400).json({message: "No track name in request body"})
}
let trackName = req.body.name
//convert buffer to Readable Streaming
const readableTrackStream = new Readable();
readableTrackStream.push(req.file.buffer)
readableTrackStream.push(null)
let bucket = new mongoose.mongo.GridFSBucket(db, {
bucketName: 'tracks'
})
let uploadStream = bucket.openUploadStream(trackName);
let id = uploadStream.id;
readableTrackStream.pipe(uploadStream);
uploadStream.on('error', err => {
return res.status(500).json({message: "Error uploading file"})
})
uploadStream.on('finish', () => {
return res.status(200).json({message: "File uploaded successfully, stored under id " + id})
})
})
})
app.listen(5000, console.log("Server Up"))