-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathGridFSBucketAdapter.js
More file actions
144 lines (128 loc) · 3.68 KB
/
Copy pathGridFSBucketAdapter.js
File metadata and controls
144 lines (128 loc) · 3.68 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/**
GridFSBucketAdapter
Stores files in Mongo using GridStore
Requires the database adapter to be based on mongoclient
@flow weak
*/
// @flow-disable-next
import { MongoClient, GridFSBucket, Db } from 'mongodb';
import { FilesAdapter } from './FilesAdapter';
import defaults from '../../defaults';
export class GridFSBucketAdapter extends FilesAdapter {
_databaseURI: string;
_connectionPromise: Promise<Db>;
_mongoOptions: Object;
constructor(mongoDatabaseURI = defaults.DefaultMongoURI, mongoOptions = {}) {
super();
this._databaseURI = mongoDatabaseURI;
const defaultMongoOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
this._mongoOptions = Object.assign(defaultMongoOptions, mongoOptions);
}
_connect() {
if (!this._connectionPromise) {
this._connectionPromise = MongoClient.connect(
this._databaseURI,
this._mongoOptions
).then(client => {
this._client = client;
return client.db(client.s.options.dbName);
});
}
return this._connectionPromise;
}
_getBucket() {
return this._connect().then(database => new GridFSBucket(database));
}
// For a given config object, filename, and data, store a file
// Returns a promise
async createFile(filename: string, data) {
const bucket = await this._getBucket();
const stream = await bucket.openUploadStream(filename);
await stream.write(data);
stream.end();
return new Promise((resolve, reject) => {
stream.on('finish', resolve);
stream.on('error', reject);
});
}
async deleteFile(filename: string) {
const bucket = await this._getBucket();
const documents = await bucket.find({ filename }).toArray();
if (documents.length === 0) {
throw new Error('FileNotFound');
}
return Promise.all(
documents.map(doc => {
return bucket.delete(doc._id);
})
);
}
async getFileData(filename: string) {
const bucket = await this._getBucket();
const stream = bucket.openDownloadStreamByName(filename);
stream.read();
return new Promise((resolve, reject) => {
const chunks = [];
stream.on('data', data => {
chunks.push(data);
});
stream.on('end', () => {
resolve(Buffer.concat(chunks));
});
stream.on('error', err => {
reject(err);
});
});
}
getFileLocation(config, filename) {
return (
config.mount +
'/files/' +
config.applicationId +
'/' +
encodeURIComponent(filename)
);
}
async getFileStream(filename: string, req, res, contentType) {
const bucket = await this._getBucket();
const files = await bucket.find({ filename }).toArray();
if (files.length === 0) {
throw new Error('FileNotFound');
}
const parts = req
.get('range')
.replace(/bytes=/, '')
.split('-');
const partialstart = parts[0];
const partialend = parts[1];
const start = parseInt(partialstart, 10);
const end = partialend ? parseInt(partialend, 10) : files[0].length - 1;
res.writeHead(206, {
'Accept-Ranges': 'bytes',
'Content-Length': end - start + 1,
'Content-Range': 'bytes ' + start + '-' + end + '/' + files[0].length,
'Content-Type': contentType,
});
const stream = bucket.openDownloadStreamByName(filename);
stream.start(start);
stream.on('data', chunk => {
res.write(chunk);
});
stream.on('error', () => {
res.sendStatus(404);
});
stream.on('end', () => {
res.end();
});
}
handleShutdown() {
if (!this._client) {
return Promise.resolve();
}
return this._client.close(false);
}
}
export default GridFSBucketAdapter;