This repository has been archived by the owner on Apr 17, 2023. It is now read-only.
/
FileRoutes.ts
61 lines (56 loc) · 1.8 KB
/
FileRoutes.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
/**
* @module @raincatcher/filestore
*/
import { getLogger } from '@raincatcher/logger';
import { promisify } from 'bluebird';
import { Router } from 'express';
import { Request } from 'express';
import { rename } from 'fs';
import * as uuid from 'uuid-js';
import { FileMetadata } from './file-api/FileMetadata';
import { FileStorage } from './file-api/FileStorage';
import * as fileService from './services/FileService';
const renameAsync: any = promisify(rename);
type SingleFileRequest = Request & {
file: {
path: string
}
};
/**
* Create express based router router for fileService
*
* @param storageEngine - engine used to store files
* @returns router instance of {@link express.Router}
*/
export function createRouter(storageEngine: FileStorage) {
fileService.createTemporaryStorageFolder();
const router = Router();
router.route('/').post(fileService.multerMiddleware().single('file'),
function(req: SingleFileRequest, res, next) {
const id = req.body.id;
const metadata: FileMetadata = {
id
};
// Move file from generated path to id
// We can't rely on multer's DiskStorage destination config since req.body.id might not be populated earlier
const location = fileService.buildFilePath(id);
return renameAsync(req.file.path, location)
.then(() => storageEngine.writeFile(metadata, location))
.then(() => res.json(metadata))
.catch(function(err) {
getLogger().error(err);
next(err);
});
});
router.route('/:id').get(function(req, res) {
const fileName = req.params.id;
storageEngine.readFile(fileName).then(function(buffer) {
if (buffer) {
buffer.pipe(res);
} else {
res.sendFile(fileService.buildFilePath(fileName));
}
});
});
return router;
}