-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.ts
89 lines (76 loc) · 2.59 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
88
89
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 { imageFilter, loadCollection, cleanFolder } from './utils';
// setup
const DB_NAME = 'db.json';
const COLLECTION_NAME = 'images';
const UPLOAD_PATH = 'uploads';
const upload = multer({ dest: `${UPLOAD_PATH}/`, fileFilter: imageFilter });
const db = new Loki(`${UPLOAD_PATH}/${DB_NAME}`, { persistenceMethod: 'fs' });
// optional: clean all data before start
// cleanFolder(UPLOAD_PATH);
// app
const app = express();
app.use(cors());
app.get('/', async (req, res) => {
// default route
res.send(`
<h1>Demo file upload</h1>
<p>Please refer to <a href="https://scotch.io/tutorials/express-file-uploads-with-multer">my tutorial</a> for details.</p>
<ul>
<li>GET /images - list all upload images</li>
<li>GET /images/{id} - get one uploaded image</li>
<li>POST /profile - handle single image upload</li>
<li>POST /photos/upload - handle multiple images upload</li>
</ul>
`);
})
app.post('/profile', upload.single('avatar'), 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 (err) {
res.sendStatus(400);
}
})
app.post('/photos/upload', upload.array('photos', 12), async (req, res) => {
try {
const col = await loadCollection(COLLECTION_NAME, db)
let data = [].concat(col.insert(req.files));
db.saveDatabase();
res.send(data.map(x => ({ id: x.$loki, fileName: x.filename, originalName: x.originalname })));
} catch (err) {
res.sendStatus(400);
}
})
app.get('/images', async (req, res) => {
try {
const col = await loadCollection(COLLECTION_NAME, db);
res.send(col.data);
} catch (err) {
res.sendStatus(400);
}
})
app.get('/images/: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 (err) {
res.sendStatus(400);
}
})
app.listen(3000, function () {
console.log('listening on port 3000!');
})