@sprucelabs/data-stores 11.0.1 → 11.2.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.
@@ -0,0 +1,28 @@
1
+ import { QueryOptions } from '../types/query.types';
2
+ export interface CursorQueryOptions extends Omit<QueryOptions, 'skip'> {
3
+ limit: number;
4
+ next: string | null;
5
+ previous: string | null;
6
+ }
7
+ export interface RecordsWithCursors<Response extends Record<string, any>[] = Record<string, any>[]> {
8
+ records: Response;
9
+ next: string | null;
10
+ previous: string | null;
11
+ }
12
+ export default class CursorPager {
13
+ static find<S extends SimpleStore, Find extends S['find'] = S['find'], Query extends Parameters<Find>[0] = Parameters<Find>[0], PromisedResponse extends ReturnType<Find> = ReturnType<Find>, Response extends UnPromisify<PromisedResponse> = UnPromisify<PromisedResponse>>(store: S, query: Query, options: CursorQueryOptions): Promise<RecordsWithCursors<Response>>;
14
+ private static getSortFieldValuesFromRecord;
15
+ private static trackNewest;
16
+ private static parseCursor;
17
+ private static encodeCursor;
18
+ static prepareQueryOptions<O extends CursorQueryOptions & {
19
+ limit: number;
20
+ }>(options: O): O & {
21
+ sort: NonNullable<O['sort']>;
22
+ };
23
+ }
24
+ export interface SimpleStore {
25
+ find: (...args: any[]) => Promise<any>;
26
+ }
27
+ declare type UnPromisify<T> = T extends Promise<infer U> ? U : T;
28
+ export {};
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ const schema_1 = require("@sprucelabs/schema");
18
+ const just_clone_1 = __importDefault(require("just-clone"));
19
+ class CursorPager {
20
+ static async find(store, query, options) {
21
+ const _a = this.prepareQueryOptions(options), { next, previous } = _a, prepped = __rest(_a, ["next", "previous"]);
22
+ let cursorQuery;
23
+ let newest;
24
+ if (next || previous) {
25
+ cursorQuery = {};
26
+ const { sort } = prepped;
27
+ const cursor = this.parseCursor((next !== null && next !== void 0 ? next : previous));
28
+ let compare = sort[0].direction === 'asc' ? '$gt' : '$lt';
29
+ if (cursor.last.length > 1) {
30
+ let inverse = compare === '$lt' ? '$gte' : '$lte';
31
+ newest = cursor.newest;
32
+ let sameNameCompare = '$lt';
33
+ if (previous) {
34
+ sameNameCompare = '$gt';
35
+ inverse = compare;
36
+ }
37
+ cursorQuery = {
38
+ $or: [
39
+ {
40
+ [sort[0].field]: { [compare]: cursor.last[0] },
41
+ },
42
+ {
43
+ [sort[0].field]: cursor.last[0],
44
+ id: { [sameNameCompare]: cursor.id },
45
+ },
46
+ {
47
+ [sort[0].field]: { [inverse]: cursor.last[0] },
48
+ id: { $gt: cursor.newest },
49
+ },
50
+ ],
51
+ };
52
+ }
53
+ else {
54
+ cursorQuery = {
55
+ id: { [compare]: cursor.id },
56
+ };
57
+ }
58
+ }
59
+ const records = await store.find(!cursorQuery ? query : { $and: [cursorQuery, query] }, prepped);
60
+ let newNextCursor;
61
+ const hasExtra = records.length > options.limit;
62
+ if (hasExtra) {
63
+ records.pop();
64
+ }
65
+ if (previous) {
66
+ records.reverse();
67
+ }
68
+ if (previous || hasExtra) {
69
+ const record = records[records.length - 1];
70
+ newNextCursor = this.encodeCursor({
71
+ id: record.id,
72
+ newest: this.trackNewest(records, newest),
73
+ last: this.getSortFieldValuesFromRecord(prepped, record),
74
+ });
75
+ }
76
+ let newPreviousCursor;
77
+ if (next || previous) {
78
+ const record = records[0];
79
+ newPreviousCursor = this.encodeCursor({
80
+ id: record.id,
81
+ newest: this.trackNewest(records, newest),
82
+ last: this.getSortFieldValuesFromRecord(prepped, record),
83
+ });
84
+ }
85
+ return {
86
+ records,
87
+ next: newNextCursor !== null && newNextCursor !== void 0 ? newNextCursor : null,
88
+ previous: newPreviousCursor !== null && newPreviousCursor !== void 0 ? newPreviousCursor : null,
89
+ };
90
+ }
91
+ static getSortFieldValuesFromRecord(prepped, record) {
92
+ return prepped.sort.map((s) => { var _a; return (_a = record[s.field]) !== null && _a !== void 0 ? _a : null; });
93
+ }
94
+ static trackNewest(records, newest) {
95
+ return [...records.map((r) => r.id), newest]
96
+ .filter((id) => !!id)
97
+ .sort()
98
+ .pop();
99
+ }
100
+ static parseCursor(next) {
101
+ return JSON.parse(next);
102
+ }
103
+ static encodeCursor(cursor) {
104
+ return JSON.stringify(cursor);
105
+ }
106
+ static prepareQueryOptions(options) {
107
+ const { previous, sort = [] } = (0, just_clone_1.default)((0, schema_1.assertOptions)(options, ['limit']));
108
+ if (!sort.find((p) => p.field === 'id')) {
109
+ sort.push({
110
+ field: 'id',
111
+ direction: 'desc',
112
+ });
113
+ }
114
+ if (previous) {
115
+ for (const s of sort) {
116
+ s.direction = s.direction === 'asc' ? 'desc' : 'asc';
117
+ }
118
+ }
119
+ return Object.assign(Object.assign({}, options), { limit: options.limit + 1, sort });
120
+ }
121
+ }
122
+ exports.default = CursorPager;
@@ -0,0 +1,6 @@
1
+ import { CursorQueryOptions, RecordsWithCursors, SimpleStore } from './CursorPager';
2
+ export default class CursorPagerFaker {
3
+ private static originalFind;
4
+ static setResponse(response: (store: SimpleStore, query: Record<string, any>, options: CursorQueryOptions) => Promise<Partial<RecordsWithCursors<Record<string, any>[]>>>): void;
5
+ static beforeEach(): Promise<void>;
6
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const CursorPager_1 = __importDefault(require("./CursorPager"));
7
+ class CursorPagerFaker {
8
+ static setResponse(response) {
9
+ //@ts-ignore
10
+ CursorPager_1.default.find = response;
11
+ }
12
+ static async beforeEach() {
13
+ if (!this.originalFind) {
14
+ this.originalFind = CursorPager_1.default.find.bind(CursorPager_1.default);
15
+ }
16
+ else {
17
+ CursorPager_1.default.find = this.originalFind;
18
+ }
19
+ }
20
+ }
21
+ exports.default = CursorPagerFaker;
@@ -187,6 +187,9 @@ class NeDbDatabase extends AbstractMutexer_1.default {
187
187
  if (typeof mapped.limit === 'number') {
188
188
  cursor.limit(mapped.limit);
189
189
  }
190
+ if (mapped.skip) {
191
+ cursor.skip(mapped.skip);
192
+ }
190
193
  cursor.exec((err, results) => {
191
194
  if (err) {
192
195
  reject(err);
@@ -0,0 +1,28 @@
1
+ import { QueryOptions } from '../types/query.types';
2
+ export interface CursorQueryOptions extends Omit<QueryOptions, 'skip'> {
3
+ limit: number;
4
+ next: string | null;
5
+ previous: string | null;
6
+ }
7
+ export interface RecordsWithCursors<Response extends Record<string, any>[] = Record<string, any>[]> {
8
+ records: Response;
9
+ next: string | null;
10
+ previous: string | null;
11
+ }
12
+ export default class CursorPager {
13
+ static find<S extends SimpleStore, Find extends S['find'] = S['find'], Query extends Parameters<Find>[0] = Parameters<Find>[0], PromisedResponse extends ReturnType<Find> = ReturnType<Find>, Response extends UnPromisify<PromisedResponse> = UnPromisify<PromisedResponse>>(store: S, query: Query, options: CursorQueryOptions): Promise<RecordsWithCursors<Response>>;
14
+ private static getSortFieldValuesFromRecord;
15
+ private static trackNewest;
16
+ private static parseCursor;
17
+ private static encodeCursor;
18
+ static prepareQueryOptions<O extends CursorQueryOptions & {
19
+ limit: number;
20
+ }>(options: O): O & {
21
+ sort: NonNullable<O['sort']>;
22
+ };
23
+ }
24
+ export interface SimpleStore {
25
+ find: (...args: any[]) => Promise<any>;
26
+ }
27
+ declare type UnPromisify<T> = T extends Promise<infer U> ? U : T;
28
+ export {};
@@ -0,0 +1,127 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
21
+ import { assertOptions } from '@sprucelabs/schema';
22
+ import clone from 'just-clone';
23
+ export default class CursorPager {
24
+ static find(store, query, options) {
25
+ return __awaiter(this, void 0, void 0, function* () {
26
+ const _a = this.prepareQueryOptions(options), { next, previous } = _a, prepped = __rest(_a, ["next", "previous"]);
27
+ let cursorQuery;
28
+ let newest;
29
+ if (next || previous) {
30
+ cursorQuery = {};
31
+ const { sort } = prepped;
32
+ const cursor = this.parseCursor((next !== null && next !== void 0 ? next : previous));
33
+ let compare = sort[0].direction === 'asc' ? '$gt' : '$lt';
34
+ if (cursor.last.length > 1) {
35
+ let inverse = compare === '$lt' ? '$gte' : '$lte';
36
+ newest = cursor.newest;
37
+ let sameNameCompare = '$lt';
38
+ if (previous) {
39
+ sameNameCompare = '$gt';
40
+ inverse = compare;
41
+ }
42
+ cursorQuery = {
43
+ $or: [
44
+ {
45
+ [sort[0].field]: { [compare]: cursor.last[0] },
46
+ },
47
+ {
48
+ [sort[0].field]: cursor.last[0],
49
+ id: { [sameNameCompare]: cursor.id },
50
+ },
51
+ {
52
+ [sort[0].field]: { [inverse]: cursor.last[0] },
53
+ id: { $gt: cursor.newest },
54
+ },
55
+ ],
56
+ };
57
+ }
58
+ else {
59
+ cursorQuery = {
60
+ id: { [compare]: cursor.id },
61
+ };
62
+ }
63
+ }
64
+ const records = yield store.find(!cursorQuery ? query : { $and: [cursorQuery, query] }, prepped);
65
+ let newNextCursor;
66
+ const hasExtra = records.length > options.limit;
67
+ if (hasExtra) {
68
+ records.pop();
69
+ }
70
+ if (previous) {
71
+ records.reverse();
72
+ }
73
+ if (previous || hasExtra) {
74
+ const record = records[records.length - 1];
75
+ newNextCursor = this.encodeCursor({
76
+ id: record.id,
77
+ newest: this.trackNewest(records, newest),
78
+ last: this.getSortFieldValuesFromRecord(prepped, record),
79
+ });
80
+ }
81
+ let newPreviousCursor;
82
+ if (next || previous) {
83
+ const record = records[0];
84
+ newPreviousCursor = this.encodeCursor({
85
+ id: record.id,
86
+ newest: this.trackNewest(records, newest),
87
+ last: this.getSortFieldValuesFromRecord(prepped, record),
88
+ });
89
+ }
90
+ return {
91
+ records,
92
+ next: newNextCursor !== null && newNextCursor !== void 0 ? newNextCursor : null,
93
+ previous: newPreviousCursor !== null && newPreviousCursor !== void 0 ? newPreviousCursor : null,
94
+ };
95
+ });
96
+ }
97
+ static getSortFieldValuesFromRecord(prepped, record) {
98
+ return prepped.sort.map((s) => { var _a; return (_a = record[s.field]) !== null && _a !== void 0 ? _a : null; });
99
+ }
100
+ static trackNewest(records, newest) {
101
+ return [...records.map((r) => r.id), newest]
102
+ .filter((id) => !!id)
103
+ .sort()
104
+ .pop();
105
+ }
106
+ static parseCursor(next) {
107
+ return JSON.parse(next);
108
+ }
109
+ static encodeCursor(cursor) {
110
+ return JSON.stringify(cursor);
111
+ }
112
+ static prepareQueryOptions(options) {
113
+ const { previous, sort = [] } = clone(assertOptions(options, ['limit']));
114
+ if (!sort.find((p) => p.field === 'id')) {
115
+ sort.push({
116
+ field: 'id',
117
+ direction: 'desc',
118
+ });
119
+ }
120
+ if (previous) {
121
+ for (const s of sort) {
122
+ s.direction = s.direction === 'asc' ? 'desc' : 'asc';
123
+ }
124
+ }
125
+ return Object.assign(Object.assign({}, options), { limit: options.limit + 1, sort });
126
+ }
127
+ }
@@ -0,0 +1,6 @@
1
+ import { CursorQueryOptions, RecordsWithCursors, SimpleStore } from './CursorPager';
2
+ export default class CursorPagerFaker {
3
+ private static originalFind;
4
+ static setResponse(response: (store: SimpleStore, query: Record<string, any>, options: CursorQueryOptions) => Promise<Partial<RecordsWithCursors<Record<string, any>[]>>>): void;
5
+ static beforeEach(): Promise<void>;
6
+ }
@@ -0,0 +1,26 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import CursorPager from './CursorPager.js';
11
+ export default class CursorPagerFaker {
12
+ static setResponse(response) {
13
+ //@ts-ignore
14
+ CursorPager.find = response;
15
+ }
16
+ static beforeEach() {
17
+ return __awaiter(this, void 0, void 0, function* () {
18
+ if (!this.originalFind) {
19
+ this.originalFind = CursorPager.find.bind(CursorPager);
20
+ }
21
+ else {
22
+ CursorPager.find = this.originalFind;
23
+ }
24
+ });
25
+ }
26
+ }
@@ -212,6 +212,9 @@ export default class NeDbDatabase extends AbstractMutexer {
212
212
  if (typeof mapped.limit === 'number') {
213
213
  cursor.limit(mapped.limit);
214
214
  }
215
+ if (mapped.skip) {
216
+ cursor.skip(mapped.skip);
217
+ }
215
218
  cursor.exec((err, results) => {
216
219
  if (err) {
217
220
  reject(err);
@@ -15,3 +15,7 @@ export * from './types/query.types';
15
15
  export * from './types/stores.types';
16
16
  export * from './constants';
17
17
  export { default as generateId } from './utilities/generateId';
18
+ export { default as CursorPager } from './cursors/CursorPager';
19
+ export * from './cursors/CursorPager';
20
+ export { default as CursorPagerFaker } from './cursors/CursorPagerFaker';
21
+ export * from './cursors/CursorPager';
@@ -15,3 +15,7 @@ export * from './types/query.types.js';
15
15
  export * from './types/stores.types.js';
16
16
  export * from './constants.js';
17
17
  export { default as generateId } from './utilities/generateId.js';
18
+ export { default as CursorPager } from './cursors/CursorPager.js';
19
+ export * from './cursors/CursorPager.js';
20
+ export { default as CursorPagerFaker } from './cursors/CursorPagerFaker.js';
21
+ export * from './cursors/CursorPager.js';
@@ -21,8 +21,11 @@ const mongoUtil = {
21
21
  friendlyMessage: '`id` cannot be undefined',
22
22
  });
23
23
  }
24
- const { id, $or } = q, rest = __rest(q, ["id", "$or"]);
24
+ const { id, $or, $and } = q, rest = __rest(q, ["id", "$or", "$and"]);
25
25
  let normalizedValues = rest;
26
+ if (Array.isArray($and)) {
27
+ normalizedValues.$and = $and.map((a) => this.mapQuery(a, options));
28
+ }
26
29
  if (Array.isArray($or)) {
27
30
  normalizedValues.$or = $or.map((o) => this.mapQuery(o, options));
28
31
  }
package/build/index.d.ts CHANGED
@@ -15,3 +15,7 @@ export * from './types/query.types';
15
15
  export * from './types/stores.types';
16
16
  export * from './constants';
17
17
  export { default as generateId } from './utilities/generateId';
18
+ export { default as CursorPager } from './cursors/CursorPager';
19
+ export * from './cursors/CursorPager';
20
+ export { default as CursorPagerFaker } from './cursors/CursorPagerFaker';
21
+ export * from './cursors/CursorPager';
package/build/index.js CHANGED
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.generateId = exports.mongoUtil = exports.NeDbDatabase = exports.MongoDatabase = exports.StoreLoader = exports.DatabaseFactory = exports.StoreFactory = exports.AbstractStore = exports.DatabaseFixture = exports.AbstractDatabaseTest = void 0;
20
+ exports.CursorPagerFaker = exports.CursorPager = exports.generateId = exports.mongoUtil = exports.NeDbDatabase = exports.MongoDatabase = exports.StoreLoader = exports.DatabaseFactory = exports.StoreFactory = exports.AbstractStore = exports.DatabaseFixture = exports.AbstractDatabaseTest = void 0;
21
21
  var AbstractDatabaseTest_1 = require("./tests/AbstractDatabaseTest");
22
22
  Object.defineProperty(exports, "AbstractDatabaseTest", { enumerable: true, get: function () { return __importDefault(AbstractDatabaseTest_1).default; } });
23
23
  var DatabaseFixture_1 = require("./fixtures/DatabaseFixture");
@@ -45,3 +45,9 @@ __exportStar(require("./types/stores.types"), exports);
45
45
  __exportStar(require("./constants"), exports);
46
46
  var generateId_1 = require("./utilities/generateId");
47
47
  Object.defineProperty(exports, "generateId", { enumerable: true, get: function () { return __importDefault(generateId_1).default; } });
48
+ var CursorPager_1 = require("./cursors/CursorPager");
49
+ Object.defineProperty(exports, "CursorPager", { enumerable: true, get: function () { return __importDefault(CursorPager_1).default; } });
50
+ __exportStar(require("./cursors/CursorPager"), exports);
51
+ var CursorPagerFaker_1 = require("./cursors/CursorPagerFaker");
52
+ Object.defineProperty(exports, "CursorPagerFaker", { enumerable: true, get: function () { return __importDefault(CursorPagerFaker_1).default; } });
53
+ __exportStar(require("./cursors/CursorPager"), exports);
@@ -26,8 +26,11 @@ const mongoUtil = {
26
26
  friendlyMessage: '`id` cannot be undefined',
27
27
  });
28
28
  }
29
- const { id, $or } = q, rest = __rest(q, ["id", "$or"]);
29
+ const { id, $or, $and } = q, rest = __rest(q, ["id", "$or", "$and"]);
30
30
  let normalizedValues = rest;
31
+ if (Array.isArray($and)) {
32
+ normalizedValues.$and = $and.map((a) => this.mapQuery(a, options));
33
+ }
31
34
  if (Array.isArray($or)) {
32
35
  normalizedValues.$or = $or.map((o) => this.mapQuery(o, options));
33
36
  }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "11.0.1",
6
+ "version": "11.2.0",
7
7
  "files": [
8
8
  "build/**/*",
9
9
  "!build/__tests__",
@@ -72,10 +72,11 @@
72
72
  },
73
73
  "dependencies": {
74
74
  "@sprucelabs/error": "^5.0.452",
75
- "@sprucelabs/schema": "^28.0.5",
76
- "@sprucelabs/spruce-core-schemas": "^27.0.1",
77
- "@sprucelabs/spruce-skill-utils": "^26.0.4",
75
+ "@sprucelabs/schema": "^28.0.6",
76
+ "@sprucelabs/spruce-core-schemas": "^27.0.2",
77
+ "@sprucelabs/spruce-skill-utils": "^26.0.5",
78
78
  "globby": "^11.0.4",
79
+ "just-clone": "^5.0.1",
79
80
  "lodash": "^4.17.21",
80
81
  "mongodb": "^4.1.0",
81
82
  "nedb": "^1.8.0"