-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
87 lines (75 loc) · 2.4 KB
/
index.ts
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
import * as express from 'express'
import * as multer from 'multer'
import * as cors from 'cors'
import * as fs from 'fs'
import * as path from 'path'
import * as Loki from 'lokijs'
import { loadCollection, fileTypeFilter, cleanFolder } from './utils'
const DB_NAME = "db.json";
const COLLECTION_NAME = "clips";
const UPLOAD_PATH = "uploads";
const upload = multer({ dest: `${UPLOAD_PATH}`, fileFilter: fileTypeFilter });
const db = new Loki(`${UPLOAD_PATH}/${DB_NAME}`, { persistenceMethod: "fs" });
//Clean all the folder before start
cleanFolder(UPLOAD_PATH);
const app = express();
app.use(cors());
app.listen(3000, function () {
console.log("Listening on port 3000!");
})
//post call to upload single file
app.post('/singleUpload', upload.single('media'), async (req, res) => {
try {
const col = await loadCollection(COLLECTION_NAME, db);
const data = col.insert(req.file);
db.saveDatabase();
res.send({
id: data.$loki,
fileName: data.filename,
originalName: data.originalname
})
} catch(error) {
res.sendStatus(400);
}
})
//post call to upload multiple files
app.post('/multipleMedia/upload', upload.array('media', 10), async (req, res) => {
try {
const col = await loadCollection(COLLECTION_NAME, db);
const data = [].concat(col.insert(req.files));
db.saveDatabase();
res.send(
data.map(x => ({
id: x.$loki,
fileName: x.filename,
originalName: x.originalname
}))
)
} catch(error) {
res.sendStatus(400);
}
})
//get call to retrive the media
app.get('/media', async(req, res) => {
try {
const col = await loadCollection(COLLECTION_NAME, db);
res.send(col.data);
} catch (error) {
res.sendStatus(400);
}
})
//Get call to retrive media using Id
app.get('/media/:id', async(req,res) => {
try {
const col = await loadCollection(COLLECTION_NAME, db);
const result = col.get(req.params.id);
if(!result){
res.sendStatus(404);
return;
}
res.setHeader('Content-Type', result.mimetype);
fs.createReadStream(path.join(UPLOAD_PATH, result.filename)).pipe(res);
} catch (error) {
res.sendStatus(400);
}
})