forked from EGF2/file
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
95 lines (85 loc) · 3.09 KB
/
api.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
92
93
94
95
"use strict";
/* eslint camelcase: 0 */
const restify = require("restify");
const log = require("./components").logger;
const config = require("./components").config;
// HTTP controller
class Controller {
constructor(clientData, s3Bucket) {
this.clientData = clientData;
this.s3Bucket = s3Bucket;
}
// Create file
createFileHandler() {
return (req, res, next) => {
try {
let mimeType = req.query.mime_type;
let title = req.query.title;
let size = req.query.size;
let resizes = [];
if (req.query.kind) {
if (config.kinds[req.query.kind]) {
config.kinds[req.query.kind].forEach(dimensions => {
let obj = {};
obj.dimensions = dimensions;
resizes.push(obj);
});
}
}
if (!mimeType) {
return next(new restify.errors.BadRequestError("'mime_type' parameter requered"));
}
if (resizes && resizes.length > 0 && !mimeType.startsWith("image/")) {
return next(new restify.errors.BadRequestError("'mime_type' must be image type"));
}
let fileKey = this.s3Bucket.generateKey();
this.s3Bucket.getUploadURL(fileKey, mimeType).then(uploadURL => {
let file = {
user: req.session.user,
object_type: "file",
title: title,
mime_type: mimeType,
hosted: true,
resizes: resizes,
url: this.s3Bucket.getDownloadURL(uploadURL),
size: size,
standalone: true
};
return this.clientData.createObject(file).then(file => {
file.upload_url = uploadURL; // don't save upload URL to DB
return file;
}).then(file => res.send(file));
}).catch(err => {
log.error(err);
next(err);
});
} catch (err) {
log.error(err);
next(err);
}
};
}
}
module.exports.Controller = Controller;
// File server with routing
class App {
constructor(authHandler, controller) {
let server = restify.createServer({
name: "file"
});
server.use(restify.queryParser());
server.use(authHandler);
// create image
server.get("/v1/new_image", controller.createFileHandler());
// create simple file
server.get("/v1/new_file", controller.createFileHandler());
this.server = server;
}
listen(port) {
let server = this.server;
this.server.listen(port, function() {
log.info({url: server.url}, "File server started...");
});
}
}
module.exports.App = App;