liwi-mongo 12.0.0 → 13.1.0

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.
Files changed (34) hide show
  1. package/README.md +7 -7
  2. package/dist/definitions/MongoBaseModel.d.ts +2 -2
  3. package/dist/definitions/MongoBaseModel.d.ts.map +1 -1
  4. package/dist/definitions/MongoConnection.d.ts +10 -3
  5. package/dist/definitions/MongoConnection.d.ts.map +1 -1
  6. package/dist/definitions/MongoCursor.d.ts +6 -6
  7. package/dist/definitions/MongoQueryCollection.d.ts +5 -5
  8. package/dist/definitions/MongoQueryCollection.d.ts.map +1 -1
  9. package/dist/definitions/MongoQueryCollection.test.d.ts +2 -0
  10. package/dist/definitions/MongoQueryCollection.test.d.ts.map +1 -0
  11. package/dist/definitions/MongoQuerySingleItem.d.ts +5 -5
  12. package/dist/definitions/MongoQuerySingleItem.d.ts.map +1 -1
  13. package/dist/definitions/MongoStore.d.ts +12 -12
  14. package/dist/definitions/MongoStore.d.ts.map +1 -1
  15. package/dist/definitions/createMongoSubscribeStore.d.ts +6 -5
  16. package/dist/definitions/createMongoSubscribeStore.d.ts.map +1 -1
  17. package/dist/definitions/index.d.ts +5 -5
  18. package/dist/definitions/index.d.ts.map +1 -1
  19. package/dist/index-node.mjs +555 -0
  20. package/dist/index-node.mjs.map +1 -0
  21. package/package.json +43 -38
  22. package/src/MongoBaseModel.ts +5 -4
  23. package/src/MongoConnection.ts +47 -43
  24. package/src/MongoCursor.ts +7 -7
  25. package/src/MongoQueryCollection.test.ts +108 -0
  26. package/src/MongoQueryCollection.ts +26 -25
  27. package/src/MongoQuerySingleItem.ts +27 -26
  28. package/src/MongoStore.ts +52 -43
  29. package/src/createMongoSubscribeStore.ts +7 -5
  30. package/src/index.ts +11 -5
  31. package/CHANGELOG.md +0 -628
  32. package/dist/index-node18.mjs +0 -588
  33. package/dist/index-node18.mjs.map +0 -1
  34. package/src/.eslintrc.json +0 -38
package/package.json CHANGED
@@ -1,67 +1,72 @@
1
1
  {
2
2
  "name": "liwi-mongo",
3
- "version": "12.0.0",
3
+ "version": "13.1.0",
4
4
  "description": "mongo implementation for liwi",
5
5
  "keywords": [],
6
- "author": "Christophe Hurpeau <christophe@hurpeau.com> (https://christophe.hurpeau.com)",
6
+ "homepage": "https://github.com/christophehurpeau/liwi",
7
+ "bugs": {
8
+ "url": "https://github.com/christophehurpeau/liwi/issues"
9
+ },
7
10
  "license": "ISC",
11
+ "author": "Christophe Hurpeau <christophe@hurpeau.com> (https://christophe.hurpeau.com)",
8
12
  "repository": {
9
13
  "type": "git",
10
- "url": "https://github.com/liwijs/liwi.git",
14
+ "url": "https://github.com/christophehurpeau/liwi.git",
11
15
  "directory": "packages/liwi-mongo"
12
16
  },
13
- "homepage": "https://github.com/liwijs/liwi",
17
+ "files": [
18
+ "src",
19
+ "dist"
20
+ ],
14
21
  "type": "module",
15
- "engines": {
16
- "node": ">=18.12.0"
17
- },
18
22
  "sideEffects": false,
19
- "main": "./dist/index-node18.mjs",
23
+ "main": "./dist/index-node.mjs",
20
24
  "types": "./dist/definitions/index.d.ts",
21
25
  "exports": {
22
26
  "./package.json": "./package.json",
23
27
  ".": {
24
28
  "types": "./dist/definitions/index.d.ts",
25
29
  "node": {
26
- "import": "./dist/index-node18.mjs"
30
+ "import": "./dist/index-node.mjs"
27
31
  }
28
32
  }
29
33
  },
30
- "files": [
31
- "src",
32
- "dist"
33
- ],
34
- "scripts": {
35
- "build": "yarn clean:build && rollup --config rollup.config.mjs && yarn run build:definitions",
36
- "build:definitions": "tsc -p tsconfig.json",
37
- "clean": "yarn clean:build",
38
- "clean:build": "pob-babel-clean-out dist",
39
- "lint": "yarn run lint:eslint",
40
- "lint:eslint": "yarn ../.. run eslint --report-unused-disable-directives --resolve-plugins-relative-to . --quiet packages/liwi-mongo",
41
- "watch": "yarn clean:build && rollup --config rollup.config.mjs --watch"
34
+ "dependencies": {
35
+ "mingo": "~6.2.7",
36
+ "mongodb": "^7.4.0",
37
+ "nightingale-logger": "^18.2.0",
38
+ "liwi-store": "13.1.0",
39
+ "liwi-subscribe-store": "13.1.0"
40
+ },
41
+ "devDependencies": {
42
+ "@pob/rollup-esbuild": "9.1.1",
43
+ "typescript": "6.0.3"
44
+ },
45
+ "engines": {
46
+ "node": ">=22.18.0"
42
47
  },
43
48
  "pob": {
44
- "babelEnvs": [
49
+ "bundler": "rollup-esbuild",
50
+ "entries": [
51
+ "index"
52
+ ],
53
+ "envs": [
45
54
  {
46
55
  "target": "node",
47
- "version": "18"
56
+ "version": "22",
57
+ "omitVersionInFileName": true
48
58
  }
49
59
  ],
50
- "entries": [
51
- "index"
52
- ]
53
- },
54
- "prettier": "@pob/root/prettier-config",
55
- "dependencies": {
56
- "liwi-store": "12.0.0",
57
- "liwi-subscribe-store": "12.0.0",
58
- "mingo": "^6.2.7",
59
- "mongodb": "^6.0.0",
60
- "nightingale-logger": "^15.0.0"
60
+ "typescript": true
61
61
  },
62
- "devDependencies": {
63
- "@babel/core": "7.24.3",
64
- "pob-babel": "38.0.3",
65
- "typescript": "5.3.3"
62
+ "scripts": {
63
+ "build": "pnpm run clean:build && rollup --config rollup.config.mjs && pnpm run build:definitions",
64
+ "build:definitions": "tsc -p tsconfig.json",
65
+ "clean": "yarn clean:build",
66
+ "clean:build": "pob-esbuild-clean-out dist",
67
+ "lint": "pnpm run lint:eslint",
68
+ "lint:eslint": "pnpm run --dir '../..' eslint --quiet 'packages/liwi-mongo'",
69
+ "tsc": "tsc",
70
+ "watch": "yarn clean:build && rollup --config rollup.config.mjs --watch"
66
71
  }
67
72
  }
@@ -1,9 +1,10 @@
1
- import type { BaseModel, AllowedKeyValue, InsertType } from 'liwi-store';
1
+ import type { AllowedKeyValue, BaseModel, InsertType } from "liwi-store";
2
2
 
3
- export type MongoKeyPath = '_id';
3
+ export type MongoKeyPath = "_id";
4
4
 
5
- export interface MongoBaseModel<KeyValue extends AllowedKeyValue = string>
6
- extends BaseModel {
5
+ export interface MongoBaseModel<
6
+ KeyValue extends AllowedKeyValue = string,
7
+ > extends BaseModel {
7
8
  _id: KeyValue;
8
9
  }
9
10
 
@@ -1,8 +1,16 @@
1
- import { AbstractConnection } from 'liwi-store';
2
- import mongodb from 'mongodb';
3
- import { Logger } from 'nightingale-logger';
4
-
5
- const logger = new Logger('liwi:mongo:MongoConnection');
1
+ import { AbstractConnection } from "liwi-store";
2
+ import mongodb from "mongodb";
3
+ import { Logger } from "nightingale-logger";
4
+
5
+ const logger = new Logger("liwi:mongo:MongoConnection");
6
+
7
+ export interface MongoConfig {
8
+ host?: string;
9
+ port?: number | string;
10
+ database: string;
11
+ user?: string;
12
+ password?: string;
13
+ }
6
14
 
7
15
  export default class MongoConnection extends AbstractConnection {
8
16
  _connection?: mongodb.MongoClient;
@@ -12,36 +20,33 @@ export default class MongoConnection extends AbstractConnection {
12
20
  connectionFailed?: boolean;
13
21
 
14
22
  // TODO interface
15
- constructor(config: Map<string, number | string>) {
23
+ constructor({
24
+ host = "localhost",
25
+ port = "27017",
26
+ database,
27
+ user,
28
+ password,
29
+ }: MongoConfig) {
16
30
  super();
17
31
 
18
- if (!config.has('host')) {
19
- config.set('host', 'localhost');
20
- }
21
- if (!config.has('port')) {
22
- config.set('port', '27017');
23
- }
24
- if (!config.has('database')) {
25
- throw new Error('Missing config database');
32
+ if (!database) {
33
+ throw new Error("Missing config database");
26
34
  }
27
35
 
28
36
  const buildConnectionString = (redactCredentials: boolean): string =>
29
37
  `mongodb://${
30
- config.has('user')
38
+ user
31
39
  ? `${
32
40
  redactCredentials
33
- ? `${(config.get('user') as string).slice(0, 2)}[redacted]`
34
- : (config.get('user') as string)
41
+ ? `${user.slice(0, 2)}[redacted]`
42
+ : encodeURIComponent(user)
35
43
  }:${
36
44
  redactCredentials
37
- ? '[redacted]'
38
- : (config.get('password') as string)
45
+ ? "[redacted]"
46
+ : encodeURIComponent(password ?? "")
39
47
  }@`
40
- : ''
41
- }` +
42
- `${config.get('host') as string}:${config.get('port') as string}/${
43
- config.get('database') as string
44
- }`;
48
+ : ""
49
+ }${host}:${port}/${encodeURIComponent(database)}`;
45
50
 
46
51
  const connectionString = buildConnectionString(false);
47
52
  const connectionStringRedacted = buildConnectionString(true);
@@ -50,32 +55,32 @@ export default class MongoConnection extends AbstractConnection {
50
55
  }
51
56
 
52
57
  connect(connectionString: string, connectionStringRedacted: string): void {
53
- logger.info('connecting', { connectionStringRedacted });
58
+ logger.info("connecting", { connectionStringRedacted });
54
59
 
55
60
  const connectPromise = mongodb.MongoClient.connect(connectionString)
56
61
  .then((connection) => {
57
- logger.info('connected', { connectionStringRedacted });
58
- connection.on('close', () => {
59
- logger.warn('close', { connectionStringRedacted });
62
+ logger.info("connected", { connectionStringRedacted });
63
+ connection.on("close", () => {
64
+ logger.warn("close", { connectionStringRedacted });
60
65
  this.connectionFailed = true;
61
66
  this.getConnection = () => {
62
- throw new Error('MongoDB connection closed');
67
+ throw new Error("MongoDB connection closed");
63
68
  };
64
69
  });
65
- connection.on('timeout', () => {
66
- logger.warn('timeout', { connectionStringRedacted });
70
+ connection.on("timeout", () => {
71
+ logger.warn("timeout", { connectionStringRedacted });
67
72
  this.connectionFailed = true;
68
73
  this.getConnection = () => {
69
- throw new Error('MongoDB connection timeout');
74
+ throw new Error("MongoDB connection timeout");
70
75
  };
71
76
  });
72
- connection.on('reconnect', () => {
73
- logger.warn('reconnect', { connectionStringRedacted });
77
+ connection.on("reconnect", () => {
78
+ logger.warn("reconnect", { connectionStringRedacted });
74
79
  this.connectionFailed = false;
75
80
  this.getConnection = () => Promise.resolve(this._connection!);
76
81
  });
77
- connection.on('error', (err) => {
78
- logger.warn('error', { connectionStringRedacted, err });
82
+ connection.on("error", (err) => {
83
+ logger.warn("error", { connectionStringRedacted, err });
79
84
  });
80
85
 
81
86
  this._connection = connection;
@@ -83,12 +88,12 @@ export default class MongoConnection extends AbstractConnection {
83
88
  this.getConnection = () => Promise.resolve(this._connection!);
84
89
  return connection;
85
90
  })
86
- .catch((error) => {
87
- logger.info('not connected', { connectionStringRedacted });
88
- console.error(error.message || error);
91
+ .catch((error: unknown) => {
92
+ logger.info("not connected", { connectionStringRedacted });
93
+ console.error((error as Error).message || error);
89
94
  // throw err;
90
95
  process.nextTick(() => {
91
- // eslint-disable-next-line unicorn/no-process-exit, n/no-process-exit
96
+ // eslint-disable-next-line unicorn/no-process-exit
92
97
  process.exit(1);
93
98
  });
94
99
 
@@ -99,13 +104,12 @@ export default class MongoConnection extends AbstractConnection {
99
104
  this._connecting = this.getConnection();
100
105
  }
101
106
 
102
- // eslint-disable-next-line @typescript-eslint/class-methods-use-this
103
107
  getConnection(): Promise<mongodb.MongoClient> {
104
- throw new Error('call connect()');
108
+ throw new Error("call connect()");
105
109
  }
106
110
 
107
111
  async close(): Promise<void> {
108
- this.getConnection = () => Promise.reject(new Error('Connection closed'));
112
+ this.getConnection = () => Promise.reject(new Error("Connection closed"));
109
113
  if (this._connection) {
110
114
  await this._connection.close();
111
115
  this._connection = undefined;
@@ -1,13 +1,13 @@
1
- import { AbstractStoreCursor } from 'liwi-store';
2
- import type { AllowedKeyValue } from 'liwi-store';
3
- import type { FindCursor } from 'mongodb';
4
- import type { MongoBaseModel } from './MongoBaseModel';
5
- import type MongoStore from './MongoStore';
1
+ import { AbstractStoreCursor } from "liwi-store";
2
+ import type { AllowedKeyValue } from "liwi-store";
3
+ import type { FindCursor } from "mongodb";
4
+ import type { MongoBaseModel } from "./MongoBaseModel";
5
+ import type MongoStore from "./MongoStore";
6
6
 
7
7
  export default class MongoCursor<
8
8
  Model extends MongoBaseModel<KeyValue>,
9
9
  Result extends Partial<Model> = Model,
10
- KeyValue extends AllowedKeyValue = Model['_id'],
10
+ KeyValue extends AllowedKeyValue = Model["_id"],
11
11
  > extends AbstractStoreCursor<
12
12
  MongoStore<Model, KeyValue>,
13
13
  KeyValue,
@@ -51,7 +51,7 @@ export default class MongoCursor<
51
51
  }
52
52
 
53
53
  override result(): Promise<Result> {
54
- if (!this._result) throw new Error('Cannot call result() before next()');
54
+ if (!this._result) throw new Error("Cannot call result() before next()");
55
55
  return Promise.resolve(this._result);
56
56
  }
57
57
 
@@ -0,0 +1,108 @@
1
+ import assert from "node:assert/strict";
2
+ import { beforeEach, describe, it, mock } from "node:test";
3
+ import type { MongoBaseModel } from "./MongoBaseModel.ts";
4
+
5
+ interface TestModel extends MongoBaseModel {
6
+ name: string;
7
+ age: number;
8
+ }
9
+
10
+ interface FakeCursor {
11
+ sortArg?: unknown;
12
+ projectArg?: unknown;
13
+ skipArg?: number;
14
+ limitArg?: number;
15
+ sort: (arg: unknown) => FakeCursor;
16
+ project: (arg: unknown) => FakeCursor;
17
+ skip: (arg: number) => FakeCursor;
18
+ limit: (arg: number) => FakeCursor;
19
+ toArray: () => Promise<TestModel[]>;
20
+ }
21
+
22
+ const documents: TestModel[] = [
23
+ { _id: "1", name: "a", age: 1, created: new Date(), updated: new Date() },
24
+ ];
25
+
26
+ let cursor: FakeCursor;
27
+
28
+ const createCursor = (): FakeCursor => ({
29
+ sort(arg) {
30
+ this.sortArg = arg;
31
+ return this;
32
+ },
33
+ project(arg) {
34
+ this.projectArg = arg;
35
+ return this;
36
+ },
37
+ skip(arg) {
38
+ this.skipArg = arg;
39
+ return this;
40
+ },
41
+ limit(arg) {
42
+ this.limitArg = arg;
43
+ return this;
44
+ },
45
+ toArray: () => Promise.resolve(documents),
46
+ });
47
+
48
+ const collection = {
49
+ find: () => cursor,
50
+ countDocuments: () => Promise.resolve(documents.length),
51
+ };
52
+
53
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins
54
+ mock.module("mongodb", {
55
+ // @ts-expect-error: not yet typed
56
+ exports: {
57
+ default: {
58
+ MongoClient: {
59
+ connect: () =>
60
+ Promise.resolve({
61
+ on: () => undefined,
62
+ db: () => ({ collection: () => collection }),
63
+ }),
64
+ },
65
+ ObjectId: class {
66
+ toString(): string {
67
+ return "generated-id";
68
+ }
69
+ },
70
+ },
71
+ },
72
+ });
73
+
74
+ const { default: MongoConnection } = await import("./MongoConnection.ts");
75
+ const { default: MongoStore } = await import("./MongoStore.ts");
76
+
77
+ const createStore = (): InstanceType<typeof MongoStore<TestModel>> => {
78
+ const connection = new MongoConnection({ database: "test" });
79
+ return new MongoStore<TestModel>(connection, "test");
80
+ };
81
+
82
+ describe("MongoQueryCollection fields", () => {
83
+ beforeEach(() => {
84
+ cursor = createCursor();
85
+ });
86
+
87
+ it("applies the projection from options.fields", async () => {
88
+ const query = createStore().createQueryCollection({
89
+ criteria: { age: { $gt: 0 } },
90
+ fields: { name: 1 },
91
+ transformer: ({ _id, name }) => ({ _id, name }),
92
+ });
93
+
94
+ await query.fetch((result) => result);
95
+
96
+ assert.deepEqual(cursor.projectArg, { name: 1 });
97
+ });
98
+
99
+ it("does not call project when options.fields is omitted", async () => {
100
+ const query = createStore().createQueryCollection({
101
+ criteria: { age: { $gt: 0 } },
102
+ });
103
+
104
+ await query.fetch((result) => result);
105
+
106
+ assert.equal(cursor.projectArg, undefined);
107
+ });
108
+ });
@@ -1,24 +1,24 @@
1
- /* eslint-disable complexity, max-lines */
1
+ /* eslint-disable complexity */
2
2
  import type {
3
- QuerySubscription,
4
- SubscribeCallback,
5
- QueryResult,
6
- QueryParams,
3
+ AllowedKeyValue,
7
4
  Changes,
8
5
  QueryOptions,
6
+ QueryParams,
7
+ QueryResult,
8
+ QuerySubscription,
9
+ SubscribeCallback,
9
10
  Transformer,
10
- AllowedKeyValue,
11
- } from 'liwi-store';
12
- import type { Actions } from 'liwi-subscribe-store';
13
- import { AbstractSubscribableStoreQuery } from 'liwi-subscribe-store';
14
- import mingo from 'mingo';
11
+ } from "liwi-store";
12
+ import type { Actions } from "liwi-subscribe-store";
13
+ import { AbstractSubscribableStoreQuery } from "liwi-subscribe-store";
14
+ import mingo from "mingo";
15
15
  import type {
16
16
  MongoBaseModel,
17
17
  MongoInsertType,
18
18
  MongoKeyPath,
19
- } from './MongoBaseModel';
20
- import type MongoCursor from './MongoCursor';
21
- import type MongoStore from './MongoStore';
19
+ } from "./MongoBaseModel";
20
+ import type MongoCursor from "./MongoCursor";
21
+ import type MongoStore from "./MongoStore";
22
22
 
23
23
  const identityTransformer = <
24
24
  Model extends MongoBaseModel<any>,
@@ -32,7 +32,7 @@ type TestCriteria = (obj: any) => boolean;
32
32
  export default class MongoQueryCollection<
33
33
  Model extends MongoBaseModel<KeyValue>,
34
34
  Params extends QueryParams<Params> = never,
35
- KeyValue extends AllowedKeyValue = Model['_id'],
35
+ KeyValue extends AllowedKeyValue = Model["_id"],
36
36
  Item extends Record<MongoKeyPath, KeyValue> = Model,
37
37
  > extends AbstractSubscribableStoreQuery<
38
38
  MongoKeyPath,
@@ -68,7 +68,7 @@ export default class MongoQueryCollection<
68
68
  }
69
69
 
70
70
  // criteria not supported by mingo: updates will not work
71
- if ('$text' in this.options.criteria) {
71
+ if ("$text" in this.options.criteria) {
72
72
  return () => false;
73
73
  }
74
74
 
@@ -106,7 +106,7 @@ export default class MongoQueryCollection<
106
106
  ? this.fetch(({ result, meta, info }: QueryResult<Item[]>) => {
107
107
  callback(null, [
108
108
  {
109
- type: 'initial',
109
+ type: "initial",
110
110
  initial: result,
111
111
  queryInfo: info,
112
112
  meta,
@@ -118,27 +118,27 @@ export default class MongoQueryCollection<
118
118
  const unsubscribe = store.subscribe((action: Actions<Model>) => {
119
119
  const changes: Changes<KeyValue, Item[]> = [];
120
120
  switch (action.type) {
121
- case 'inserted': {
121
+ case "inserted": {
122
122
  const filtered = action.next.filter(testCriteria);
123
123
  if (filtered.length > 0) {
124
124
  changes.push({
125
- type: 'inserted',
125
+ type: "inserted",
126
126
  result: filtered.map(this.transformer),
127
127
  });
128
128
  }
129
129
  break;
130
130
  }
131
- case 'deleted': {
131
+ case "deleted": {
132
132
  const filtered = action.prev.filter(testCriteria);
133
133
  if (filtered.length > 0) {
134
134
  changes.push({
135
- type: 'deleted',
135
+ type: "deleted",
136
136
  keys: filtered.map((object) => object[this.store.keyPath]),
137
137
  });
138
138
  }
139
139
  break;
140
140
  }
141
- case 'updated': {
141
+ case "updated": {
142
142
  const {
143
143
  deleted,
144
144
  updated,
@@ -162,19 +162,19 @@ export default class MongoQueryCollection<
162
162
  });
163
163
 
164
164
  if (deleted.length > 0) {
165
- changes.push({ type: 'deleted', keys: deleted });
165
+ changes.push({ type: "deleted", keys: deleted });
166
166
  }
167
167
  if (updated.length > 0) {
168
- changes.push({ type: 'updated', result: updated });
168
+ changes.push({ type: "updated", result: updated });
169
169
  }
170
170
  if (inserted.length > 0) {
171
- changes.push({ type: 'inserted', result: inserted });
171
+ changes.push({ type: "inserted", result: inserted });
172
172
  }
173
173
 
174
174
  break;
175
175
  }
176
176
  default:
177
- throw new Error('Unsupported type');
177
+ throw new Error("Unsupported type");
178
178
  }
179
179
 
180
180
  if (changes.length === 0) return;
@@ -217,6 +217,7 @@ export default class MongoQueryCollection<
217
217
  const cursor = await this.store.cursor(
218
218
  this.options.criteria,
219
219
  this.options.sort,
220
+ this.options.fields,
220
221
  );
221
222
 
222
223
  if (this.options.skip) {