-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongo.js
More file actions
43 lines (40 loc) · 1.22 KB
/
mongo.js
File metadata and controls
43 lines (40 loc) · 1.22 KB
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
import { MongoClient, GridFSBucket } from "mongodb";
import { config } from "dotenv";
import fs from "fs";
import { v4 } from "uuid";
config();
export const getDbClient = () => {
const client = new MongoClient(process.env.DB_URL);
client.connect();
const db = client.db(process.env.DB_NAME);
return db;
};
export const insertToDb = (file, fileName, bucketName) => {
const db = getDbClient();
const bucket = new GridFSBucket(db, { bucketName });
console.log(file);
const id = v4();
return new Promise((resolve, reject) => {
fs.createReadStream(Buffer.from(file.path)).pipe(
bucket
.openUploadStreamWithId(id, fileName, {
chunkSizeBytes: 1048576,
contentType: file.mimetype,
metadata: { hash: file.fileHash },
})
.on("close", () => {
resolve(id);
})
.on("error", (e) => {
reject(new Error(e.message));
})
);
});
};
export const fetchFromDb = async (bucketName, id, start, end) => {
const db = getDbClient();
const bucket = new GridFSBucket(db, { bucketName });
if (!start) return bucket.openDownloadStream(id);
const downloadStream = bucket.openDownloadStream(id, { start, end });
return downloadStream;
};