-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimagesDAO.js
80 lines (72 loc) · 2.3 KB
/
imagesDAO.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
import { GridFSBucket, ObjectId } from "mongodb";
import fs from "fs";
export default class ImagesDAO {
constructor() {
this.files = null;
this.chunks = null;
this.database = null;
}
static async injectDB(conn) {
if (this.files) {
return;
}
try {
this.files = await conn
.db(process.env.DB_NAME)
.collection("images.files");
this.chunks = await conn
.db(process.env.DB_NAME)
.collection("images.chunks");
this.database = await conn.db(process.env.DB_NAME);
} catch (err) {
console.log(`Unable to connect to MongoDB: ${err.message}`);
}
}
static async downloadImages(menu, res) {
try {
let names = Object.values(menu.image);
let fileInfos = await this.files
.find({ filename: { $in: names } })
.toArray();
const bucket = new GridFSBucket(this.database, {
bucketName: "images",
});
for (let i = 0; i < names.length; i++) {
bucket
.openDownloadStream(fileInfos[i]._id)
.pipe(fs.createWriteStream("./images/" + names[i]));
}
} catch (err) {
console.log(`Unable to download files: ${err.message}`);
}
}
static async getFileID(fileName) {
try {
const option = {
projection: {
_id: 1,
length: 0,
chunkSize: 0,
uploadDate: 0,
filename: 0,
contentType: 0,
},
};
return await this.files
.find({ filename: { $in: fileName } }, option)
.toArray();
} catch (err) {
console.log(`Unable to get file information: ${err.message}`);
}
}
static async deleteImage(fileID) {
try {
for (const id of fileID) {
await this.chunks.deleteOne({ files_id: id._id });
await this.files.deleteOne({ _id: id._id });
}
} catch (err) {
console.log(`Unable to delete files: ${err.message}`);
}
}
}