@keyv/mongo 3.0.0-rc.1 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017-2021 Luke Childs
4
+ Copyright (c) 2021-2022 Jared Wray
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @keyv/mongo [<img width="100" align="right" src="https://jaredwray.com/images/keyv.svg" alt="keyv">](https://github.com/jaredwra/keyv)
1
+ # @keyv/mongo [<img width="100" align="right" src="https://jaredwray.com/images/keyv-symbol.svg" alt="keyv">](https://github.com/jaredwra/keyv)
2
2
 
3
3
  > MongoDB storage adapter for Keyv
4
4
 
@@ -20,9 +20,10 @@ npm install --save keyv @keyv/mongo
20
20
  ## Usage
21
21
 
22
22
  ```js
23
- const Keyv = require('keyv');
23
+ import Keyv from 'keyv';
24
+ import KeyvMongo from '@keyv/mongo';
24
25
 
25
- const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname');
26
+ const keyv = new Keyv(new KeyvMongo('mongodb://user:pass@localhost:27017/dbname'));
26
27
  keyv.on('error', handleConnectionError);
27
28
  ```
28
29
 
@@ -36,4 +37,4 @@ const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname', { collection
36
37
 
37
38
  ## License
38
39
 
39
- MIT © Jared Wray
40
+ [MIT © Jared Wray](LISCENCE)
package/dist/index.cjs ADDED
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ KeyvMongo: () => KeyvMongo,
34
+ default: () => src_default
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+ var import_events = __toESM(require("events"), 1);
38
+ var import_buffer = require("buffer");
39
+ var import_mongodb = require("mongodb");
40
+ var keyvMongoKeys = /* @__PURE__ */ new Set(["url", "collection", "namespace", "serialize", "deserialize", "uri", "useGridFS", "dialect"]);
41
+ var KeyvMongo = class extends import_events.default {
42
+ ttlSupport = false;
43
+ opts;
44
+ connect;
45
+ namespace;
46
+ constructor(url, options) {
47
+ super();
48
+ url ??= {};
49
+ if (typeof url === "string") {
50
+ url = { url };
51
+ }
52
+ if (url.uri) {
53
+ url = { url: url.uri, ...url };
54
+ }
55
+ this.opts = {
56
+ url: "mongodb://127.0.0.1:27017",
57
+ collection: "keyv",
58
+ ...url,
59
+ ...options
60
+ };
61
+ delete this.opts.emitErrors;
62
+ const mongoOptions = Object.fromEntries(
63
+ Object.entries(this.opts).filter(
64
+ ([k]) => !keyvMongoKeys.has(k)
65
+ )
66
+ );
67
+ this.opts = Object.fromEntries(
68
+ Object.entries(this.opts).filter(
69
+ ([k]) => keyvMongoKeys.has(k)
70
+ )
71
+ );
72
+ this.connect = new Promise(async (resolve, reject) => {
73
+ try {
74
+ let url2 = "";
75
+ if (this.opts.url) {
76
+ url2 = this.opts.url;
77
+ }
78
+ const client = new import_mongodb.MongoClient(url2, mongoOptions);
79
+ await client.connect();
80
+ const database = client.db(this.opts.db);
81
+ if (this.opts.useGridFS) {
82
+ const bucket = new import_mongodb.GridFSBucket(database, {
83
+ readPreference: this.opts.readPreference,
84
+ bucketName: this.opts.collection
85
+ });
86
+ const store = database.collection(`${this.opts.collection}.files`);
87
+ await store.createIndex({ uploadDate: -1 });
88
+ await store.createIndex({ "metadata.expiresAt": 1 });
89
+ await store.createIndex({ "metadata.lastAccessed": 1 });
90
+ await store.createIndex({ "metadata.filename": 1 });
91
+ resolve({
92
+ bucket,
93
+ store,
94
+ db: database,
95
+ mongoClient: client
96
+ });
97
+ } else {
98
+ let collection = "keyv";
99
+ if (this.opts.collection) {
100
+ collection = this.opts.collection;
101
+ }
102
+ const store = database.collection(collection);
103
+ await store.createIndex({ key: 1 }, { unique: true, background: true });
104
+ await store.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0, background: true });
105
+ resolve({ store, mongoClient: client });
106
+ }
107
+ } catch (error) {
108
+ this.emit("error", error);
109
+ reject(error);
110
+ }
111
+ });
112
+ }
113
+ async get(key) {
114
+ const client = await this.connect;
115
+ if (this.opts.useGridFS) {
116
+ await client.store.updateOne({
117
+ filename: key
118
+ }, {
119
+ $set: {
120
+ "metadata.lastAccessed": /* @__PURE__ */ new Date()
121
+ }
122
+ });
123
+ const stream = client.bucket.openDownloadStreamByName(key);
124
+ return new Promise((resolve) => {
125
+ const resp = [];
126
+ stream.on("error", () => {
127
+ resolve(void 0);
128
+ });
129
+ stream.on("end", () => {
130
+ const data = import_buffer.Buffer.concat(resp).toString("utf8");
131
+ resolve(data);
132
+ });
133
+ stream.on("data", (chunk) => {
134
+ resp.push(chunk);
135
+ });
136
+ });
137
+ }
138
+ const document = await client.store.findOne({ key: { $eq: key } });
139
+ if (!document) {
140
+ return void 0;
141
+ }
142
+ return document.value;
143
+ }
144
+ async getMany(keys) {
145
+ if (this.opts.useGridFS) {
146
+ const promises = [];
147
+ for (const key of keys) {
148
+ promises.push(this.get(key));
149
+ }
150
+ const values2 = await Promise.allSettled(promises);
151
+ const data = [];
152
+ for (const value of values2) {
153
+ data.push(value.value);
154
+ }
155
+ return data;
156
+ }
157
+ const connect = await this.connect;
158
+ const values = await connect.store.s.db.collection(this.opts.collection).find({ key: { $in: keys } }).project({ _id: 0, value: 1, key: 1 }).toArray();
159
+ const results = [...keys];
160
+ let i = 0;
161
+ for (const key of keys) {
162
+ const rowIndex = values.findIndex((row) => row.key === key);
163
+ results[i] = rowIndex > -1 ? values[rowIndex].value : void 0;
164
+ i++;
165
+ }
166
+ return results;
167
+ }
168
+ async set(key, value, ttl) {
169
+ const expiresAt = typeof ttl === "number" ? new Date(Date.now() + ttl) : null;
170
+ if (this.opts.useGridFS) {
171
+ const client2 = await this.connect;
172
+ const stream = client2.bucket.openUploadStream(key, {
173
+ metadata: {
174
+ expiresAt,
175
+ lastAccessed: /* @__PURE__ */ new Date()
176
+ }
177
+ });
178
+ return new Promise((resolve) => {
179
+ stream.on("finish", () => {
180
+ resolve(stream);
181
+ });
182
+ stream.end(value);
183
+ });
184
+ }
185
+ const client = await this.connect;
186
+ await client.store.updateOne(
187
+ { key: { $eq: key } },
188
+ { $set: { key, value, expiresAt } },
189
+ { upsert: true }
190
+ );
191
+ }
192
+ async delete(key) {
193
+ if (typeof key !== "string") {
194
+ return false;
195
+ }
196
+ const client = await this.connect;
197
+ if (this.opts.useGridFS) {
198
+ try {
199
+ const connection = client.db;
200
+ const bucket = new import_mongodb.GridFSBucket(connection, {
201
+ bucketName: this.opts.collection
202
+ });
203
+ const files = await bucket.find({ filename: key }).toArray();
204
+ await client.bucket.delete(files[0]._id);
205
+ return true;
206
+ } catch {
207
+ return false;
208
+ }
209
+ }
210
+ const object = await client.store.deleteOne({ key: { $eq: key } });
211
+ return object.deletedCount > 0;
212
+ }
213
+ async deleteMany(keys) {
214
+ const client = await this.connect;
215
+ if (this.opts.useGridFS) {
216
+ const connection = client.db;
217
+ const bucket = new import_mongodb.GridFSBucket(connection, {
218
+ bucketName: this.opts.collection
219
+ });
220
+ const files = await bucket.find({ filename: { $in: keys } }).toArray();
221
+ if (files.length === 0) {
222
+ return false;
223
+ }
224
+ await Promise.all(files.map(async (file) => client.bucket.delete(file._id)));
225
+ return true;
226
+ }
227
+ const object = await client.store.deleteMany({ key: { $in: keys } });
228
+ return object.deletedCount > 0;
229
+ }
230
+ async clear() {
231
+ const client = await this.connect;
232
+ if (this.opts.useGridFS) {
233
+ try {
234
+ await client.bucket.drop();
235
+ } catch (error) {
236
+ if (!(error instanceof import_mongodb.MongoServerError && error.code === 26)) {
237
+ throw error;
238
+ }
239
+ }
240
+ }
241
+ await client.store.deleteMany({
242
+ key: { $regex: this.namespace ? `^${this.namespace}:*` : "" }
243
+ });
244
+ }
245
+ async clearExpired() {
246
+ if (!this.opts.useGridFS) {
247
+ return false;
248
+ }
249
+ return this.connect.then(async (client) => {
250
+ const connection = client.db;
251
+ const bucket = new import_mongodb.GridFSBucket(connection, {
252
+ bucketName: this.opts.collection
253
+ });
254
+ return bucket.find({
255
+ "metadata.expiresAt": {
256
+ $lte: new Date(Date.now())
257
+ }
258
+ }).toArray().then(async (expiredFiles) => Promise.all(expiredFiles.map(async (file) => client.bucket.delete(file._id))).then(() => true));
259
+ });
260
+ }
261
+ async clearUnusedFor(seconds) {
262
+ if (!this.opts.useGridFS) {
263
+ return false;
264
+ }
265
+ const client = await this.connect;
266
+ const connection = client.db;
267
+ const bucket = new import_mongodb.GridFSBucket(connection, {
268
+ bucketName: this.opts.collection
269
+ });
270
+ const lastAccessedFiles = await bucket.find({
271
+ "metadata.lastAccessed": {
272
+ $lte: new Date(Date.now() - seconds * 1e3)
273
+ }
274
+ }).toArray();
275
+ await Promise.all(lastAccessedFiles.map(async (file) => client.bucket.delete(file._id)));
276
+ return true;
277
+ }
278
+ async *iterator(namespace) {
279
+ const client = await this.connect;
280
+ const regexp = new RegExp(`^${namespace ? namespace + ":" : ".*"}`);
281
+ const iterator = this.opts.useGridFS ? client.store.find({
282
+ filename: regexp
283
+ }).map(async (x) => [x.filename, await this.get(x.filename)]) : client.store.find({
284
+ key: regexp
285
+ }).map((x) => [x.key, x.value]);
286
+ yield* iterator;
287
+ }
288
+ async has(key) {
289
+ const client = await this.connect;
290
+ const filter = { [this.opts.useGridFS ? "filename" : "key"]: { $eq: key } };
291
+ const document = await client.store.count(filter);
292
+ return document !== 0;
293
+ }
294
+ async disconnect() {
295
+ const client = await this.connect;
296
+ await client.mongoClient.close();
297
+ }
298
+ };
299
+ var src_default = KeyvMongo;
300
+ // Annotate the CommonJS export names for ESM import in node:
301
+ 0 && (module.exports = {
302
+ KeyvMongo
303
+ });
@@ -1,7 +1,28 @@
1
- /// <reference types="node" />
2
1
  import EventEmitter from 'events';
3
- import { KeyvStoreAdapter, type StoredData } from 'keyv';
4
- import { type KeyvMongoConnect, type KeyvMongoOptions, type Options } from './types';
2
+ import { KeyvStoreAdapter, StoredData } from 'keyv';
3
+ import { ReadPreference, GridFSBucket, Collection, Db, MongoClient } from 'mongodb';
4
+
5
+ type Options = {
6
+ [key: string]: unknown;
7
+ url?: string | undefined;
8
+ collection?: string;
9
+ namespace?: string;
10
+ serialize?: any;
11
+ deserialize?: any;
12
+ useGridFS?: boolean;
13
+ uri?: string;
14
+ dialect?: string;
15
+ db?: string;
16
+ readPreference?: ReadPreference;
17
+ };
18
+ type KeyvMongoOptions = Options | string;
19
+ type KeyvMongoConnect = {
20
+ bucket?: GridFSBucket;
21
+ store: Collection;
22
+ db?: Db;
23
+ mongoClient: MongoClient;
24
+ };
25
+
5
26
  declare class KeyvMongo extends EventEmitter implements KeyvStoreAdapter {
6
27
  ttlSupport: boolean;
7
28
  opts: Options;
@@ -18,5 +39,7 @@ declare class KeyvMongo extends EventEmitter implements KeyvStoreAdapter {
18
39
  clearUnusedFor(seconds: number): Promise<boolean>;
19
40
  iterator(namespace?: string): AsyncGenerator<any[], void, void>;
20
41
  has(key: string): Promise<boolean>;
42
+ disconnect(): Promise<void>;
21
43
  }
22
- export default KeyvMongo;
44
+
45
+ export { KeyvMongo, KeyvMongo as default };
@@ -1,7 +1,28 @@
1
- /// <reference types="node" />
2
1
  import EventEmitter from 'events';
3
- import { KeyvStoreAdapter, type StoredData } from 'keyv';
4
- import { type KeyvMongoConnect, type KeyvMongoOptions, type Options } from './types';
2
+ import { KeyvStoreAdapter, StoredData } from 'keyv';
3
+ import { ReadPreference, GridFSBucket, Collection, Db, MongoClient } from 'mongodb';
4
+
5
+ type Options = {
6
+ [key: string]: unknown;
7
+ url?: string | undefined;
8
+ collection?: string;
9
+ namespace?: string;
10
+ serialize?: any;
11
+ deserialize?: any;
12
+ useGridFS?: boolean;
13
+ uri?: string;
14
+ dialect?: string;
15
+ db?: string;
16
+ readPreference?: ReadPreference;
17
+ };
18
+ type KeyvMongoOptions = Options | string;
19
+ type KeyvMongoConnect = {
20
+ bucket?: GridFSBucket;
21
+ store: Collection;
22
+ db?: Db;
23
+ mongoClient: MongoClient;
24
+ };
25
+
5
26
  declare class KeyvMongo extends EventEmitter implements KeyvStoreAdapter {
6
27
  ttlSupport: boolean;
7
28
  opts: Options;
@@ -18,5 +39,7 @@ declare class KeyvMongo extends EventEmitter implements KeyvStoreAdapter {
18
39
  clearUnusedFor(seconds: number): Promise<boolean>;
19
40
  iterator(namespace?: string): AsyncGenerator<any[], void, void>;
20
41
  has(key: string): Promise<boolean>;
42
+ disconnect(): Promise<void>;
21
43
  }
22
- export default KeyvMongo;
44
+
45
+ export { KeyvMongo, KeyvMongo as default };
package/dist/index.js ADDED
@@ -0,0 +1,272 @@
1
+ // src/index.ts
2
+ import EventEmitter from "events";
3
+ import { Buffer } from "buffer";
4
+ import {
5
+ MongoClient as mongoClient,
6
+ GridFSBucket,
7
+ MongoServerError
8
+ } from "mongodb";
9
+ var keyvMongoKeys = /* @__PURE__ */ new Set(["url", "collection", "namespace", "serialize", "deserialize", "uri", "useGridFS", "dialect"]);
10
+ var KeyvMongo = class extends EventEmitter {
11
+ ttlSupport = false;
12
+ opts;
13
+ connect;
14
+ namespace;
15
+ constructor(url, options) {
16
+ super();
17
+ url ??= {};
18
+ if (typeof url === "string") {
19
+ url = { url };
20
+ }
21
+ if (url.uri) {
22
+ url = { url: url.uri, ...url };
23
+ }
24
+ this.opts = {
25
+ url: "mongodb://127.0.0.1:27017",
26
+ collection: "keyv",
27
+ ...url,
28
+ ...options
29
+ };
30
+ delete this.opts.emitErrors;
31
+ const mongoOptions = Object.fromEntries(
32
+ Object.entries(this.opts).filter(
33
+ ([k]) => !keyvMongoKeys.has(k)
34
+ )
35
+ );
36
+ this.opts = Object.fromEntries(
37
+ Object.entries(this.opts).filter(
38
+ ([k]) => keyvMongoKeys.has(k)
39
+ )
40
+ );
41
+ this.connect = new Promise(async (resolve, reject) => {
42
+ try {
43
+ let url2 = "";
44
+ if (this.opts.url) {
45
+ url2 = this.opts.url;
46
+ }
47
+ const client = new mongoClient(url2, mongoOptions);
48
+ await client.connect();
49
+ const database = client.db(this.opts.db);
50
+ if (this.opts.useGridFS) {
51
+ const bucket = new GridFSBucket(database, {
52
+ readPreference: this.opts.readPreference,
53
+ bucketName: this.opts.collection
54
+ });
55
+ const store = database.collection(`${this.opts.collection}.files`);
56
+ await store.createIndex({ uploadDate: -1 });
57
+ await store.createIndex({ "metadata.expiresAt": 1 });
58
+ await store.createIndex({ "metadata.lastAccessed": 1 });
59
+ await store.createIndex({ "metadata.filename": 1 });
60
+ resolve({
61
+ bucket,
62
+ store,
63
+ db: database,
64
+ mongoClient: client
65
+ });
66
+ } else {
67
+ let collection = "keyv";
68
+ if (this.opts.collection) {
69
+ collection = this.opts.collection;
70
+ }
71
+ const store = database.collection(collection);
72
+ await store.createIndex({ key: 1 }, { unique: true, background: true });
73
+ await store.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0, background: true });
74
+ resolve({ store, mongoClient: client });
75
+ }
76
+ } catch (error) {
77
+ this.emit("error", error);
78
+ reject(error);
79
+ }
80
+ });
81
+ }
82
+ async get(key) {
83
+ const client = await this.connect;
84
+ if (this.opts.useGridFS) {
85
+ await client.store.updateOne({
86
+ filename: key
87
+ }, {
88
+ $set: {
89
+ "metadata.lastAccessed": /* @__PURE__ */ new Date()
90
+ }
91
+ });
92
+ const stream = client.bucket.openDownloadStreamByName(key);
93
+ return new Promise((resolve) => {
94
+ const resp = [];
95
+ stream.on("error", () => {
96
+ resolve(void 0);
97
+ });
98
+ stream.on("end", () => {
99
+ const data = Buffer.concat(resp).toString("utf8");
100
+ resolve(data);
101
+ });
102
+ stream.on("data", (chunk) => {
103
+ resp.push(chunk);
104
+ });
105
+ });
106
+ }
107
+ const document = await client.store.findOne({ key: { $eq: key } });
108
+ if (!document) {
109
+ return void 0;
110
+ }
111
+ return document.value;
112
+ }
113
+ async getMany(keys) {
114
+ if (this.opts.useGridFS) {
115
+ const promises = [];
116
+ for (const key of keys) {
117
+ promises.push(this.get(key));
118
+ }
119
+ const values2 = await Promise.allSettled(promises);
120
+ const data = [];
121
+ for (const value of values2) {
122
+ data.push(value.value);
123
+ }
124
+ return data;
125
+ }
126
+ const connect = await this.connect;
127
+ const values = await connect.store.s.db.collection(this.opts.collection).find({ key: { $in: keys } }).project({ _id: 0, value: 1, key: 1 }).toArray();
128
+ const results = [...keys];
129
+ let i = 0;
130
+ for (const key of keys) {
131
+ const rowIndex = values.findIndex((row) => row.key === key);
132
+ results[i] = rowIndex > -1 ? values[rowIndex].value : void 0;
133
+ i++;
134
+ }
135
+ return results;
136
+ }
137
+ async set(key, value, ttl) {
138
+ const expiresAt = typeof ttl === "number" ? new Date(Date.now() + ttl) : null;
139
+ if (this.opts.useGridFS) {
140
+ const client2 = await this.connect;
141
+ const stream = client2.bucket.openUploadStream(key, {
142
+ metadata: {
143
+ expiresAt,
144
+ lastAccessed: /* @__PURE__ */ new Date()
145
+ }
146
+ });
147
+ return new Promise((resolve) => {
148
+ stream.on("finish", () => {
149
+ resolve(stream);
150
+ });
151
+ stream.end(value);
152
+ });
153
+ }
154
+ const client = await this.connect;
155
+ await client.store.updateOne(
156
+ { key: { $eq: key } },
157
+ { $set: { key, value, expiresAt } },
158
+ { upsert: true }
159
+ );
160
+ }
161
+ async delete(key) {
162
+ if (typeof key !== "string") {
163
+ return false;
164
+ }
165
+ const client = await this.connect;
166
+ if (this.opts.useGridFS) {
167
+ try {
168
+ const connection = client.db;
169
+ const bucket = new GridFSBucket(connection, {
170
+ bucketName: this.opts.collection
171
+ });
172
+ const files = await bucket.find({ filename: key }).toArray();
173
+ await client.bucket.delete(files[0]._id);
174
+ return true;
175
+ } catch {
176
+ return false;
177
+ }
178
+ }
179
+ const object = await client.store.deleteOne({ key: { $eq: key } });
180
+ return object.deletedCount > 0;
181
+ }
182
+ async deleteMany(keys) {
183
+ const client = await this.connect;
184
+ if (this.opts.useGridFS) {
185
+ const connection = client.db;
186
+ const bucket = new GridFSBucket(connection, {
187
+ bucketName: this.opts.collection
188
+ });
189
+ const files = await bucket.find({ filename: { $in: keys } }).toArray();
190
+ if (files.length === 0) {
191
+ return false;
192
+ }
193
+ await Promise.all(files.map(async (file) => client.bucket.delete(file._id)));
194
+ return true;
195
+ }
196
+ const object = await client.store.deleteMany({ key: { $in: keys } });
197
+ return object.deletedCount > 0;
198
+ }
199
+ async clear() {
200
+ const client = await this.connect;
201
+ if (this.opts.useGridFS) {
202
+ try {
203
+ await client.bucket.drop();
204
+ } catch (error) {
205
+ if (!(error instanceof MongoServerError && error.code === 26)) {
206
+ throw error;
207
+ }
208
+ }
209
+ }
210
+ await client.store.deleteMany({
211
+ key: { $regex: this.namespace ? `^${this.namespace}:*` : "" }
212
+ });
213
+ }
214
+ async clearExpired() {
215
+ if (!this.opts.useGridFS) {
216
+ return false;
217
+ }
218
+ return this.connect.then(async (client) => {
219
+ const connection = client.db;
220
+ const bucket = new GridFSBucket(connection, {
221
+ bucketName: this.opts.collection
222
+ });
223
+ return bucket.find({
224
+ "metadata.expiresAt": {
225
+ $lte: new Date(Date.now())
226
+ }
227
+ }).toArray().then(async (expiredFiles) => Promise.all(expiredFiles.map(async (file) => client.bucket.delete(file._id))).then(() => true));
228
+ });
229
+ }
230
+ async clearUnusedFor(seconds) {
231
+ if (!this.opts.useGridFS) {
232
+ return false;
233
+ }
234
+ const client = await this.connect;
235
+ const connection = client.db;
236
+ const bucket = new GridFSBucket(connection, {
237
+ bucketName: this.opts.collection
238
+ });
239
+ const lastAccessedFiles = await bucket.find({
240
+ "metadata.lastAccessed": {
241
+ $lte: new Date(Date.now() - seconds * 1e3)
242
+ }
243
+ }).toArray();
244
+ await Promise.all(lastAccessedFiles.map(async (file) => client.bucket.delete(file._id)));
245
+ return true;
246
+ }
247
+ async *iterator(namespace) {
248
+ const client = await this.connect;
249
+ const regexp = new RegExp(`^${namespace ? namespace + ":" : ".*"}`);
250
+ const iterator = this.opts.useGridFS ? client.store.find({
251
+ filename: regexp
252
+ }).map(async (x) => [x.filename, await this.get(x.filename)]) : client.store.find({
253
+ key: regexp
254
+ }).map((x) => [x.key, x.value]);
255
+ yield* iterator;
256
+ }
257
+ async has(key) {
258
+ const client = await this.connect;
259
+ const filter = { [this.opts.useGridFS ? "filename" : "key"]: { $eq: key } };
260
+ const document = await client.store.count(filter);
261
+ return document !== 0;
262
+ }
263
+ async disconnect() {
264
+ const client = await this.connect;
265
+ await client.mongoClient.close();
266
+ }
267
+ };
268
+ var src_default = KeyvMongo;
269
+ export {
270
+ KeyvMongo,
271
+ src_default as default
272
+ };