MCPcopy
hub / github.com/mongodb/node-mongodb-native / init

Function init

src/gridfs/download.ts:305–413  ·  view source on GitHub ↗
(stream: GridFSBucketReadStream)

Source from the content-addressed store, hash-verified

303}
304
305function init(stream: GridFSBucketReadStream): void {
306 const findOneOptions: FindOptions = {};
307 if (stream.s.readPreference) {
308 findOneOptions.readPreference = stream.s.readPreference;
309 }
310 if (stream.s.options && stream.s.options.sort) {
311 findOneOptions.sort = stream.s.options.sort;
312 }
313 if (stream.s.options && stream.s.options.skip) {
314 findOneOptions.skip = stream.s.options.skip;
315 }
316
317 const handleReadResult = (doc: Document | null) => {
318 if (stream.destroyed) return;
319
320 if (!doc) {
321 const identifier = stream.s.filter._id
322 ? stream.s.filter._id.toString()
323 : stream.s.filter.filename;
324 const errmsg = `FileNotFound: file ${identifier} was not found`;
325 // TODO(NODE-3483)
326 const err = new MongoRuntimeError(errmsg);
327 err.code = 'ENOENT'; // TODO: NODE-3338 set property as part of constructor
328 return stream.destroy(err);
329 }
330
331 // If document is empty, kill the stream immediately and don't
332 // execute any reads
333 if (doc.length <= 0) {
334 stream.push(null);
335 return;
336 }
337
338 if (stream.destroyed) {
339 // If user destroys the stream before we have a cursor, wait
340 // until the query is done to say we're 'closed' because we can't
341 // cancel a query.
342 stream.destroy();
343 return;
344 }
345
346 try {
347 stream.s.bytesToSkip = handleStartOption(stream, doc, stream.s.options);
348 } catch (error) {
349 return stream.destroy(error);
350 }
351
352 const filter: Document = { files_id: doc._id };
353
354 // Currently (MongoDB 3.4.4) skip function does not support the index,
355 // it needs to retrieve all the documents first and then skip them. (CS-25811)
356 // As work around we use $gte on the "n" field.
357 if (stream.s.options && stream.s.options.start != null) {
358 const skip = Math.floor(stream.s.options.start / doc.chunkSize);
359 if (skip > 0) {
360 filter['n'] = { $gte: skip };
361 }
362 }

Callers 1

waitForFileFunction · 0.70

Calls 3

findOneMethod · 0.80
destroyMethod · 0.45

Tested by

no test coverage detected