From 054450aa3f6ecbb769f5b4f8aea4c27823d7df17 Mon Sep 17 00:00:00 2001 From: Lars Decker Date: Tue, 20 May 2025 14:06:15 +0200 Subject: [PATCH] chore: update mongo driver and code --- README.md | 15 ++-- package-lock.json | 10 +-- package.json | 2 +- src/GridFSPromise.d.ts | 188 ++++++++++++++++++----------------------- src/GridFSPromise.js | 147 ++++++++++++++++++++------------ src/GridFSPromise.ts | 23 ++--- 6 files changed, 203 insertions(+), 182 deletions(-) diff --git a/README.md b/README.md index d21ace1..8ba8594 100644 --- a/README.md +++ b/README.md @@ -14,12 +14,15 @@ That is simple ## Usage ```js -const mongoOptions: MongoClientOptions = { - autoReconnect: true, - useNewUrlParser: true -}; - -let gridFS = new GridFSPromise("test", "mongodb://localhost:27017/test", mongoOptions, __dirname, "attachments"); +const mongoOptions: MongoClientOptions = {}; + +let gridFS = new GridFSPromise( + "test", + "mongodb://localhost:27017/test", + mongoOptions, + __dirname, + "attachments", +); gridFS.getObject("59e085f272882d728e2fa4c2").then((item) => { console.log(item); }).catch((err) => { diff --git a/package-lock.json b/package-lock.json index eb73275..1756af7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "6.3.10", "license": "GPL-3.0", "dependencies": { - "mongodb": "^5.4.0" + "mongodb": "^6.0.0" }, "devDependencies": { "@types/chai": "^4.3.5", @@ -3571,8 +3571,8 @@ } }, "node_modules/mongodb": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.4.0.tgz", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.0.0.tgz", "integrity": "sha512-6GDKgO7WiYUw+ILap143VXfAou06hjxDGgYUZWGnI4hgoZfP3el0G3l69JqJF8SEQbZmC+SN/2a0aWI/aWJoxA==", "dependencies": { "bson": "^5.2.0", @@ -7431,8 +7431,8 @@ } }, "mongodb": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.4.0.tgz", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.0.0.tgz", "integrity": "sha512-6GDKgO7WiYUw+ILap143VXfAou06hjxDGgYUZWGnI4hgoZfP3el0G3l69JqJF8SEQbZmC+SN/2a0aWI/aWJoxA==", "requires": { "bson": "^5.2.0", diff --git a/package.json b/package.json index 25bb4f7..e8c3e6e 100644 --- a/package.json +++ b/package.json @@ -45,6 +45,6 @@ "typescript": "^4.9.5" }, "dependencies": { - "mongodb": "^5.4.0" + "mongodb": "^6.0.0" } } diff --git a/src/GridFSPromise.d.ts b/src/GridFSPromise.d.ts index bcea00a..ba2f7dd 100644 --- a/src/GridFSPromise.d.ts +++ b/src/GridFSPromise.d.ts @@ -1,109 +1,87 @@ -import { ObjectID } from 'bson'; -import { - GridFSBucketReadStream, - MongoClient, - MongoClientOptions, -} from 'mongodb'; +import { ObjectId } from 'mongodb'; +import { Document, GridFSBucketReadStream, MongoClient, MongoClientOptions } from 'mongodb'; export interface IGridFSObject { - _id: ObjectID; - length: number; - chunkSize: number; - uploadDate: Date; - md5: string; - filename: string; - contentType: string; - metadata: object; + _id: ObjectId; + length: number; + chunkSize: number; + uploadDate: Date; + md5?: string; + filename: string; + contentType?: string | undefined; + metadata?: Document | undefined; } export declare class GridFSPromise { - set CONNECTION(value: MongoClient); - get connection(): MongoClient | null; - private databaseName; - private readonly connectionUrl; - private readonly mongoClientOptions; - private basePath; - private bucketName; - private closeConnectionAutomatically; - private _CONNECTION; - maxTimeMS: number; - /** - * Constructor - * @param {string} mongoUrl - * @param {string} databaseName - * @param {MongoClientOptions} mongoOptions - * @param {string} bucketName - * @param {string} basePath - * @param {boolean} closeConnectionAutomatically - */ - constructor( - databaseName: string, - mongoUrl?: string | null, - mongoOptions?: MongoClientOptions | null, - bucketName?: string, - basePath?: string, - closeConnectionAutomatically?: boolean, - ); - /** - * Returns a stream of a file from the GridFS. - * @param {string} id - * @return {Promise} - */ - getFileStream(id: string): Promise; - /** - * Save the File from the GridFs to the filesystem and get the Path back - * @param {string} id - * @param {string} fileName - * @param {string} filePath - * @return {Promise} - */ - getFile(id: string, fileName?: string, filePath?: string): Promise; - /** - * Get a single Object - * @param {string} id - * @return {Promise} - */ - getObject(id: string): Promise; - /** - * Upload a file directly from a fs Path - * @param {string} uploadFilePath - * @param {string} targetFileName - * @param {string} type - * @param {object} meta - * @param {boolean} deleteFile - * @return {Promise} - */ - uploadFile( - uploadFilePath: string, - targetFileName: string, - type: string, - meta: object, - deleteFile?: boolean, - ): Promise; - /** - * Upload a file directly from a fs Path - * @param {string} uploadData - * @param {string} targetFileName - * @param {string} type - * @param {object} meta - * @return {Promise} - */ - uploadFileString( - uploadData: string, - targetFileName: string, - type: string, - meta: object, - ): Promise; - /** - * Delete an File from the GridFS - * @param {string} id - * @return {Promise} - */ - delete(id: string): Promise; - /** - * Close the Connection, if the connection is not needed anymore - */ - closeConnection(): Promise; - /** - * Connect to the Database and return a promise Object - */ - private connectDB; + set CONNECTION(value: MongoClient); + get connection(): MongoClient | null; + private databaseName; + private readonly connectionUrl; + private readonly mongoClientOptions; + private basePath; + private bucketName; + private closeConnectionAutomatically; + private _CONNECTION; + maxTimeMS: number; + /** + * Constructor + * @param {string} mongoUrl + * @param {string} databaseName + * @param {MongoClientOptions} mongoOptions + * @param {string} bucketName + * @param {string} basePath + * @param {boolean} closeConnectionAutomatically + */ + constructor(databaseName: string, mongoUrl?: string | null, mongoOptions?: MongoClientOptions | null, bucketName?: string, basePath?: string, closeConnectionAutomatically?: boolean); + /** + * Returns a stream of a file from the GridFS. + * @param {string} id + * @return {Promise} + */ + getFileStream(id: string): Promise; + /** + * Save the File from the GridFs to the filesystem and get the Path back + * @param {string} id + * @param {string} fileName + * @param {string} filePath + * @return {Promise} + */ + getFile(id: string, fileName?: string, filePath?: string): Promise; + /** + * Get a single Object + * @param {string} id + * @return {Promise} + */ + getObject(id: string): Promise; + /** + * Upload a file directly from a fs Path + * @param {string} uploadFilePath + * @param {string} targetFileName + * @param {string} type + * @param {object} meta + * @param {boolean} deleteFile + * @return {Promise} + */ + uploadFile(uploadFilePath: string, targetFileName: string, type: string, meta: object, deleteFile?: boolean): Promise; + /** + * Upload a file directly from a fs Path + * @param {string} uploadData + * @param {string} targetFileName + * @param {string} type + * @param {object} meta + * @return {Promise} + */ + uploadFileString(uploadData: string, targetFileName: string, type: string, meta: object): Promise; + /** + * Delete an File from the GridFS + * @param {string} id + * @return {Promise} + */ + delete(id: string): Promise; + /** + * Close the Connection, if the connection is not needed anymore + */ + closeConnection(): Promise; + /** + * Connect to the Database and return a promise Object + */ + private connectDB; } diff --git a/src/GridFSPromise.js b/src/GridFSPromise.js index 45cf524..6eb3a53 100644 --- a/src/GridFSPromise.js +++ b/src/GridFSPromise.js @@ -9,12 +9,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge }); }; var __generator = (this && this.__generator) || function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); - while (_) try { + while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { @@ -37,9 +37,9 @@ var __generator = (this && this.__generator) || function (thisArg, body) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.GridFSPromise = void 0; -var bson_1 = require("bson"); -var fs = require("fs"); var mongodb_1 = require("mongodb"); +var fs = require("fs"); +var mongodb_2 = require("mongodb"); var path = require("path"); var stream_1 = require("stream"); var GridFSPromise = /** @class */ (function () { @@ -63,8 +63,8 @@ var GridFSPromise = /** @class */ (function () { if (mongoOptions) { this.mongoClientOptions = mongoOptions; } - this.bucketName = bucketName || "fs"; - this.basePath = basePath || __dirname + "/../cache"; + this.bucketName = bucketName || 'fs'; + this.basePath = basePath || "".concat(__dirname, "/../cache"); if (closeConnectionAutomatically) { this.closeConnectionAutomatically = closeConnectionAutomatically; } @@ -91,10 +91,16 @@ var GridFSPromise = /** @class */ (function () { GridFSPromise.prototype.getFileStream = function (id) { var _this = this; return new Promise(function (resolve, reject) { - _this.connectDB().then(function (client) { + _this.connectDB() + .then(function (client) { var connection = client.db(_this.databaseName); - var bucket = new mongodb_1.GridFSBucket(connection, { bucketName: _this.bucketName }); - bucket.find({ _id: new bson_1.ObjectID(id) }, { maxTimeMS: _this.maxTimeMS }).toArray().then(function (result) { return __awaiter(_this, void 0, void 0, function () { + var bucket = new mongodb_2.GridFSBucket(connection, { + bucketName: _this.bucketName, + }); + bucket + .find({ _id: new mongodb_1.ObjectId(id) }, { maxTimeMS: _this.maxTimeMS }) + .toArray() + .then(function (result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -105,7 +111,7 @@ var GridFSPromise = /** @class */ (function () { _a.label = 2; case 2: if (result.length > 0) { - resolve(bucket.openDownloadStream(new bson_1.ObjectID(id))); + resolve(bucket.openDownloadStream(new mongodb_1.ObjectId(id))); } else { reject(); @@ -114,7 +120,8 @@ var GridFSPromise = /** @class */ (function () { } }); }); }); - }).catch(function (err) { + }) + .catch(function (err) { reject(err); }); }); @@ -129,34 +136,41 @@ var GridFSPromise = /** @class */ (function () { GridFSPromise.prototype.getFile = function (id, fileName, filePath) { var _this = this; return new Promise(function (resolve, reject) { - _this.connectDB().then(function (client) { + _this.connectDB() + .then(function (client) { var connection = client.db(_this.databaseName); - var bucket = new mongodb_1.GridFSBucket(connection, { bucketName: _this.bucketName }); - return bucket.find({ _id: new bson_1.ObjectID(id) }, { maxTimeMS: _this.maxTimeMS }).toArray().then(function (result) { return __awaiter(_this, void 0, void 0, function () { + var bucket = new mongodb_2.GridFSBucket(connection, { + bucketName: _this.bucketName, + }); + return bucket + .find({ _id: new mongodb_1.ObjectId(id) }, { maxTimeMS: _this.maxTimeMS }) + .toArray() + .then(function (result) { return __awaiter(_this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { if (!result || result.length === 0) { - throw new Error("Object not found"); + throw new Error('Object not found'); } if (!fileName) { fileName = result[0].filename; } else { - if (path.extname(fileName) === "") { + if (path.extname(fileName) === '') { fileName = fileName.concat(path.extname(result[0].filename)); } } if (!filePath) { - filePath = ""; + filePath = ''; } - if (this.basePath.charAt(this.basePath.length - 1) !== "/") { - filePath += "/"; + if (this.basePath.charAt(this.basePath.length - 1) !== '/') { + filePath += '/'; } - if (!fs.existsSync("" + this.basePath + filePath)) { - throw new Error("Path not found"); + if (!fs.existsSync("".concat(this.basePath).concat(filePath))) { + throw new Error('Path not found'); } - bucket.openDownloadStream(new bson_1.ObjectID(id)) - .once("error", function (error) { return __awaiter(_this, void 0, void 0, function () { + bucket + .openDownloadStream(new mongodb_1.ObjectId(id)) + .once('error', function (error) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -170,7 +184,8 @@ var GridFSPromise = /** @class */ (function () { return [2 /*return*/]; } }); - }); }).once("end", function () { return __awaiter(_this, void 0, void 0, function () { + }); }) + .once('end', function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -180,16 +195,17 @@ var GridFSPromise = /** @class */ (function () { _a.sent(); _a.label = 2; case 2: - resolve("" + this.basePath + filePath + fileName); + resolve("".concat(this.basePath).concat(filePath).concat(fileName)); return [2 /*return*/]; } }); }); }) - .pipe(fs.createWriteStream("" + this.basePath + filePath + fileName)); + .pipe(fs.createWriteStream("".concat(this.basePath).concat(filePath).concat(fileName))); return [2 /*return*/]; }); }); }); - }).catch(function (err) { + }) + .catch(function (err) { reject(err); }); }); @@ -201,11 +217,17 @@ var GridFSPromise = /** @class */ (function () { */ GridFSPromise.prototype.getObject = function (id) { var _this = this; - return new Promise((function (resolve, reject) { - _this.connectDB().then(function (client) { + return new Promise(function (resolve, reject) { + _this.connectDB() + .then(function (client) { var connection = client.db(_this.databaseName); - var bucket = new mongodb_1.GridFSBucket(connection, { bucketName: _this.bucketName }); - bucket.find({ _id: new bson_1.ObjectID(id) }, { maxTimeMS: _this.maxTimeMS }).toArray().then(function (result) { return __awaiter(_this, void 0, void 0, function () { + var bucket = new mongodb_2.GridFSBucket(connection, { + bucketName: _this.bucketName, + }); + bucket + .find({ _id: new mongodb_1.ObjectId(id) }, { maxTimeMS: _this.maxTimeMS }) + .toArray() + .then(function (result) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -219,16 +241,17 @@ var GridFSPromise = /** @class */ (function () { resolve(result[0]); } else { - reject(new Error("No Object found")); + reject(new Error('No Object found')); } return [2 /*return*/]; } }); }); }); - }).catch(function (err) { + }) + .catch(function (err) { reject(err); }); - })); + }); }; /** * Upload a file directly from a fs Path @@ -244,17 +267,20 @@ var GridFSPromise = /** @class */ (function () { if (deleteFile === void 0) { deleteFile = true; } return new Promise(function (resolve, reject) { if (!fs.existsSync(uploadFilePath)) { - reject(new Error("File not found")); + reject(new Error('File not found')); } - _this.connectDB().then(function (client) { + _this.connectDB() + .then(function (client) { var connection = client.db(_this.databaseName); - var bucket = new mongodb_1.GridFSBucket(connection, { bucketName: _this.bucketName }); + var bucket = new mongodb_2.GridFSBucket(connection, { + bucketName: _this.bucketName, + }); fs.createReadStream(uploadFilePath) .pipe(bucket.openUploadStream(targetFileName, { contentType: type, metadata: meta, })) - .on("error", function (err) { return __awaiter(_this, void 0, void 0, function () { + .on('error', function (err) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -271,7 +297,8 @@ var GridFSPromise = /** @class */ (function () { return [2 /*return*/]; } }); - }); }).on("finish", function (item) { return __awaiter(_this, void 0, void 0, function () { + }); }) + .on('finish', function (item) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -289,7 +316,8 @@ var GridFSPromise = /** @class */ (function () { } }); }); }); - }).catch(function (err) { + }) + .catch(function (err) { reject(err); }); }); @@ -305,17 +333,20 @@ var GridFSPromise = /** @class */ (function () { GridFSPromise.prototype.uploadFileString = function (uploadData, targetFileName, type, meta) { var _this = this; return new Promise(function (resolve, reject) { - _this.connectDB().then(function (client) { + _this.connectDB() + .then(function (client) { var connection = client.db(_this.databaseName); - var bucket = new mongodb_1.GridFSBucket(connection, { bucketName: _this.bucketName }); - var binary = new Buffer(uploadData, 'base64'); + var bucket = new mongodb_2.GridFSBucket(connection, { + bucketName: _this.bucketName, + }); + var binary = Buffer.from(uploadData, 'base64'); var readable = stream_1.Readable.from(binary); readable .pipe(bucket.openUploadStream(targetFileName, { contentType: type, metadata: meta, })) - .on("error", function (err) { return __awaiter(_this, void 0, void 0, function () { + .on('error', function (err) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -329,7 +360,8 @@ var GridFSPromise = /** @class */ (function () { return [2 /*return*/]; } }); - }); }).on("finish", function (item) { return __awaiter(_this, void 0, void 0, function () { + }); }) + .on('finish', function (item) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -344,7 +376,8 @@ var GridFSPromise = /** @class */ (function () { } }); }); }); - }).catch(function (err) { + }) + .catch(function (err) { reject(err); }); }); @@ -357,10 +390,13 @@ var GridFSPromise = /** @class */ (function () { GridFSPromise.prototype.delete = function (id) { var _this = this; return new Promise(function (resolve, reject) { - _this.connectDB().then(function (client) { + _this.connectDB() + .then(function (client) { var connection = client.db(_this.databaseName); - var bucket = new mongodb_1.GridFSBucket(connection, { bucketName: _this.bucketName }); - bucket.delete(new bson_1.ObjectID(id), (function (err) { return __awaiter(_this, void 0, void 0, function () { + var bucket = new mongodb_2.GridFSBucket(connection, { + bucketName: _this.bucketName, + }); + bucket.delete(new mongodb_1.ObjectId(id), function (err) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -377,8 +413,9 @@ var GridFSPromise = /** @class */ (function () { return [2 /*return*/]; } }); - }); })); - }).catch(function (err) { + }); }); + }) + .catch(function (err) { reject(err); }); }); @@ -414,11 +451,11 @@ var GridFSPromise = /** @class */ (function () { return [2 /*return*/, this._CONNECTION]; } if (!this.connectionUrl) { - throw new Error("No Connection String given. Can´t connect to MongoDB."); + throw new Error('No Connection String given. Can´t connect to MongoDB.'); } _a = this; - return [4 /*yield*/, mongodb_1.MongoClient.connect(this.connectionUrl)]; - case 1: return [2 /*return*/, _a._CONNECTION = _b.sent()]; + return [4 /*yield*/, new mongodb_2.MongoClient(this.connectionUrl, this.mongoClientOptions).connect()]; + case 1: return [2 /*return*/, (_a._CONNECTION = _b.sent())]; } }); }); diff --git a/src/GridFSPromise.ts b/src/GridFSPromise.ts index 03a9de9..8899782 100644 --- a/src/GridFSPromise.ts +++ b/src/GridFSPromise.ts @@ -1,4 +1,4 @@ -import { ObjectID } from 'bson'; +import { ObjectId } from 'mongodb'; import * as fs from 'fs'; import { Document, @@ -11,7 +11,7 @@ import * as path from 'path'; import { Readable } from 'stream'; export interface IGridFSObject { - _id: ObjectID; + _id: ObjectId; length: number; chunkSize: number; uploadDate: Date; @@ -94,7 +94,7 @@ export class GridFSPromise { }); bucket - .find({ _id: new ObjectID(id) }, { maxTimeMS: this.maxTimeMS }) + .find({ _id: new ObjectId(id) }, { maxTimeMS: this.maxTimeMS }) .toArray() .then(async (result) => { if (this.closeConnectionAutomatically) { @@ -102,7 +102,7 @@ export class GridFSPromise { } if (result.length > 0) { - resolve(bucket.openDownloadStream(new ObjectID(id))); + resolve(bucket.openDownloadStream(new ObjectId(id))); } else { reject(); } @@ -135,7 +135,7 @@ export class GridFSPromise { }); return bucket - .find({ _id: new ObjectID(id) }, { maxTimeMS: this.maxTimeMS }) + .find({ _id: new ObjectId(id) }, { maxTimeMS: this.maxTimeMS }) .toArray() .then(async (result) => { if (!result || result.length === 0) { @@ -163,7 +163,7 @@ export class GridFSPromise { } bucket - .openDownloadStream(new ObjectID(id)) + .openDownloadStream(new ObjectId(id)) .once('error', async (error) => { if (this.closeConnectionAutomatically) { await client.close(); @@ -204,7 +204,7 @@ export class GridFSPromise { }); bucket - .find({ _id: new ObjectID(id) }, { maxTimeMS: this.maxTimeMS }) + .find({ _id: new ObjectId(id) }, { maxTimeMS: this.maxTimeMS }) .toArray() .then(async (result: IGridFSObject[]) => { if (this.closeConnectionAutomatically) { @@ -310,7 +310,7 @@ export class GridFSPromise { bucketName: this.bucketName, }); - const binary = new Buffer(uploadData, 'base64'); + const binary = Buffer.from(uploadData, 'base64'); const readable = Readable.from(binary); readable @@ -355,7 +355,7 @@ export class GridFSPromise { bucketName: this.bucketName, }); - bucket.delete(new ObjectID(id), async (err) => { + bucket.delete(new ObjectId(id), async (err) => { if (this.closeConnectionAutomatically) { await client.close(); } @@ -395,6 +395,9 @@ export class GridFSPromise { throw new Error('No Connection String given. Can´t connect to MongoDB.'); } - return (this._CONNECTION = await MongoClient.connect(this.connectionUrl)); + return (this._CONNECTION = await new MongoClient( + this.connectionUrl, + this.mongoClientOptions, + ).connect()); } }