devconcept / multer-gridfs-storage

🍃 GridFS storage engine for Multer to store uploaded files directly to MongoDb
MIT License
237 stars 67 forks source link

add temp id so Nest JS can save img - uncaughtException: Cannot read properties of undefin ed (reading '_id') #560 #586

Open cpalmer-ios opened 2 months ago

cpalmer-ios commented 2 months ago

PR Checklist

Verify that you did the following:

Related issue

Issue: #560

Describe what you did

Updated fromMulterStream to add the _id in a variable from Mongo DS so the object can be saved. I had some trouble compiling the code (ts errors) so I edited the system file.

    fromMulterStream(readStream, request, file) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.connecting) {
                yield this.ready();
            }

            const fileSettings = yield this._generate(request, file);
            let settings;
            const setType = typeof fileSettings;
            const allowedTypes = new Set(['undefined', 'number', 'string', 'object']);
            if (!allowedTypes.has(setType)) {
                throw new Error('Invalid type for file settings, got ' + setType);
            }

            if (fileSettings === null || fileSettings === undefined) {
                settings = {};
            } else if (setType === 'string' || setType === 'number') {
                settings = {
                    filename: fileSettings.toString(),
                };
            } else {
                settings = fileSettings;
            }

            const contentType = file ? file.mimetype : undefined;
            const streamOptions = yield GridFsStorage._mergeProps({ contentType }, settings);

            return new Promise((resolve, reject) => {
                const emitError = (streamError) => {
                    this.emit('streamError', streamError, streamOptions);
                    reject(streamError);
                };

                const emitFile = (f) => {
                    if (!f || !f._id) {
                        return emitError(new Error('File upload failed: File object is undefined or missing _id'));
                    }

                    const storedFile = {
                        id: f._id,
                        filename: f.filename,
                        metadata: f.metadata || null,
                        bucketName: streamOptions.bucketName,
                        chunkSize: f.chunkSize,
                        size: f.length,
                        md5: f.md5,
                        uploadDate: f.uploadDate,
                        contentType: f.contentType,
                    };
                    this.emit('file', storedFile);
                    resolve(storedFile);
                };

                // Create the upload stream
                const writeStream = this.createStream(streamOptions);
                writeStream.on('error', emitError);

                // When the stream finishes writing, emit the file details
                writeStream.on('finish', () => {
                    // Manually create the file object to pass to emitFile
                    const fileObj = {
                        _id: writeStream.id, // The _id generated by MongoDB
                        filename: streamOptions.filename,
                        metadata: streamOptions.metadata,
                        chunkSize: streamOptions.chunkSizeBytes,
                        length: writeStream.length, // You may need to calculate or store this separately
                        md5: writeStream.md5, // If using MD5, this might need to be calculated manually or captured
                        uploadDate: new Date(), // Or use `writeStream.uploadDate` if available
                        contentType: streamOptions.contentType,
                    };
                    emitFile(fileObj);
                });

                // Use pump to handle the stream piping and error handling
                pump_1.default([readStream, writeStream], (err) => {
                    if (err) {
                        console.error('Stream pump error:', err);
                        emitError(err);
                    }
                });
            });
        });
    }

Is this a breaking change?

Other information

the ts errors were coming from the following modules and file:

Found 7 errors in 5 files.

Errors  Files
     1  node_modules/@types/eslint/helpers.d.ts:1
     1  node_modules/@types/markdown-it/lib/index.d.ts:151
     1  node_modules/@types/mongodb/index.d.ts:58
     3  src/gridfs.ts:216
     1  ../../../../node_modules/@types/eslint/helpers.d.ts:1

Thanks, hope it helps !

theBGuy commented 2 months ago

561 I've had this open for awhile. This repo is dead

cpalmer-ios commented 2 months ago

thanks @theBGuy , i think you are right. Wasn't expecting it to be merged 😂 will keep it up incase people want to see how to save the id from Mongo