-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathfile.service.js
83 lines (73 loc) · 1.87 KB
/
file.service.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
const fs = require("fs");
const path = require("path");
const { NotFoundError } = require("../src/errors");
const mkdir = require("mkdirp").sync;
const mime = require("mime-types");
const uploadDir = path.join(__dirname, "__uploads");
mkdir(uploadDir);
module.exports = {
name: "file",
actions: {
image: {
handler(ctx) {
ctx.meta.$responseType = "image/png";
// Return as stream
return fs.createReadStream(path.join(__dirname, "full", "assets", "images", "logo.png"));
}
},
html: {
handler(ctx) {
ctx.meta.$responseType = "text/html";
return Buffer.from(`
<html>
<body>
<h1>Hello API Gateway!</h1>
<img src="/api/file.image" />
</body>
</html>
`);
}
},
get: {
handler(ctx) {
const filePath = path.join(uploadDir, ctx.params.file);
if (!fs.existsSync(filePath))
return new NotFoundError();
ctx.meta.$responseType = mime.lookup(ctx.params.file);
// Return as stream
return fs.createReadStream(filePath);
}
},
save: {
handler(ctx) {
this.logger.info("Received upload $params:", ctx.meta.$params);
return new this.Promise((resolve, reject) => {
//reject(new Error("Disk out of space"));
const filePath = path.join(uploadDir, ctx.meta.filename || this.randomName());
const f = fs.createWriteStream(filePath);
f.on("close", () => {
// File written successfully
this.logger.info(`Uploaded file stored in '${filePath}'`);
resolve({ filePath, meta: ctx.meta });
});
ctx.params.on("error", err => {
this.logger.info("File error received", err.message);
reject(err);
// Destroy the local file
f.destroy(err);
});
f.on("error", () => {
// Remove the errored file.
fs.unlinkSync(filePath);
});
ctx.params.pipe(f);
});
}
}
},
methods: {
randomName() {
return "unnamed_" + Date.now() + ".png";
}
}
};