@routier/pouchdb-plugin 0.0.1-alpha.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.
@@ -0,0 +1,96 @@
1
+ import { assertIsArray } from "@routier/core/assertions";
2
+ import { Filter, ParamsFilter } from "@routier/core/expressions";
3
+ import { IQuery, JsonTranslator, QueryCollectionItem, QueryOption } from "@routier/core/plugins";
4
+ import { CompiledSchema, InferType } from "@routier/core/schema";
5
+
6
+ export class PouchDbTranslator<TEntity extends {}, TShape extends unknown = TEntity> extends JsonTranslator<TEntity, TShape> {
7
+
8
+ private schema: CompiledSchema<TEntity>;
9
+ private cachedMatches: ((item: unknown) => boolean) | null = null;
10
+
11
+ constructor(query: IQuery<TEntity, TShape>) {
12
+ super(query);
13
+ this.schema = query.schema;
14
+ }
15
+
16
+ matches(item: unknown) {
17
+ // Get or build cached filter chain
18
+ const filterChain = this.resolveFilterChain();
19
+
20
+ // Execute the chain (no loops, just recursive function calls)
21
+ return filterChain(item);
22
+ }
23
+
24
+ private resolveFilterChain(): (item: unknown) => boolean {
25
+ // Return cached chain if available
26
+ if (this.cachedMatches !== null) {
27
+ return this.cachedMatches;
28
+ }
29
+
30
+ // Build and cache the filter chain
31
+ const filters = this.query.options.get("filter");
32
+ const databaseFilters = filters.filter(x => x.option.target === "database");
33
+
34
+ this.cachedMatches = this.buildFilterChain(databaseFilters, 0);
35
+
36
+ return this.cachedMatches;
37
+ }
38
+
39
+ private buildFilterChain(filters: QueryCollectionItem<TShape, "filter">[], index: number): (item: unknown) => boolean {
40
+ // Base case: no more filters, return true
41
+ if (index >= filters.length) {
42
+ return () => true;
43
+ }
44
+
45
+ // Get current filter function
46
+ const currentFilter = this.evaluateFilter(filters[index].option);
47
+
48
+ // Build the rest of the chain
49
+ const nextFilter = this.buildFilterChain(filters, index + 1);
50
+
51
+ // Return a function that checks current filter and calls next
52
+ return (item: unknown) => {
53
+ if (!currentFilter(item)) {
54
+ return false; // Early termination
55
+ }
56
+ return nextFilter(item); // Recursive call to next filter
57
+ };
58
+ }
59
+
60
+ private evaluateFilter(filter: QueryOption<TShape, "filter">): (item: unknown) => boolean {
61
+ if (filter.value.params == null) {
62
+ const selector = filter.value.filter as Filter<unknown>;
63
+ return (item: unknown) => selector(item) !== false;
64
+ }
65
+
66
+ const selector = filter.value.filter as ParamsFilter<unknown, {}>;
67
+ const params = filter.value.params;
68
+ return (item: unknown) => selector([item, params]) !== false;
69
+ }
70
+
71
+ override translate(data: unknown): TShape {
72
+ assertIsArray(data);
73
+
74
+ const result: unknown[] = [];
75
+
76
+ for (let i = 0, length = data.length; i < length; i++) {
77
+ const entity: any = data[i];
78
+
79
+ // design docs can be included in the result, ignore them
80
+ if ("_id" in entity && typeof entity._id === "string" && entity._id.startsWith("_design")) {
81
+ continue;
82
+ }
83
+
84
+ try {
85
+ // PouchDB converts a Date to a string when it is saved, we need to convert it back when it's selected
86
+ result.push(this.schema.deserialize(entity as InferType<TEntity>));
87
+ data[i] = null;
88
+ } catch (e) {
89
+ throw new Error(`Error deserializing entity from db. Message: ${e.message}, Entity: ${JSON.stringify(entity, null, 2)}`)
90
+ }
91
+ }
92
+
93
+ return super.translate(result);
94
+ }
95
+
96
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { PouchDbPlugin } from './PouchDbPlugin';
@@ -0,0 +1,46 @@
1
+ import { generateData } from '@routier/testing-plugin';
2
+ import { describe, it, expect, afterAll } from 'vitest';
3
+ import { IDbPlugin, uuidv4 } from '@routier/core';
4
+ import { PouchDbPlugin } from '../PouchDbPlugin';
5
+ import { TestDataStore } from './datastore/PouchDbDatastore';
6
+
7
+ const pluginFactory: () => IDbPlugin = () => new PouchDbPlugin(uuidv4());
8
+ const stores: TestDataStore[] = [];
9
+ const factory = () => {
10
+
11
+ const store = new TestDataStore(pluginFactory());
12
+
13
+ stores.push(store);
14
+
15
+ return store;
16
+ };
17
+
18
+ describe("Comments Tests", () => {
19
+
20
+ afterAll(async () => {
21
+ await Promise.all(stores.map(x => x.destroyAsync()));
22
+ });
23
+
24
+
25
+ describe('Add Operations', () => {
26
+ it("Can add item with default", async () => {
27
+ const dataStore = factory();
28
+ // Arrange
29
+ const [item] = generateData(dataStore.comments.schema, 1);
30
+
31
+ // Act
32
+ const [added] = await dataStore.comments.addAsync(item);
33
+ const response = await dataStore.saveChangesAsync();
34
+
35
+ // Assert
36
+ expect(response.aggregate.size).toBe(1);
37
+ expect(added._id).toStrictEqual(expect.any(String));
38
+ expect(added.author).toStrictEqual(item.author);
39
+ expect(added.content).toBe(item.content);
40
+ expect(added.replies).toStrictEqual(item.replies);
41
+ expect(added.createdAt).toBe(item.createdAt);
42
+ expect(added.createdAt).toBeDefined()
43
+ });
44
+ });
45
+
46
+ });
@@ -0,0 +1,26 @@
1
+ import { IDbPlugin } from "@routier/core";
2
+ import { DataStore } from "@routier/datastore";
3
+ import { productsSchema } from "../schemas/product";
4
+ import { commentsSchema } from "../schemas/comments";
5
+ import { eventsSchema } from "../schemas/event";
6
+ import { usersSchema } from "../schemas/user";
7
+ import { userProfileSchema } from "../schemas/userProfile";
8
+ import { inventoryItemsSchema } from "../schemas/inventoryItem";
9
+ import { playerSchema } from "../schemas/player";
10
+ import { playerMatchSchema } from "../schemas/playerMatch";
11
+
12
+ export class TestDataStore extends DataStore {
13
+ constructor(plugin: IDbPlugin) {
14
+ super(plugin);
15
+ }
16
+
17
+ products = this.collection(productsSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...productsSchema }).create();
18
+ comments = this.collection(commentsSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...commentsSchema }).create();
19
+ events = this.collection(eventsSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...eventsSchema }).create();
20
+ users = this.collection(usersSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...usersSchema }).create();
21
+ userProfiles = this.collection(userProfileSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...userProfileSchema }).create();
22
+ inventoryItems = this.collection(inventoryItemsSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...inventoryItemsSchema }).create();
23
+
24
+ players = this.collection(playerSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...playerSchema }).create();
25
+ playerMatches = this.collection(playerMatchSchema).scope(([x, p]) => x.documentType === p.collectionName, { ...playerMatchSchema }).create();
26
+ }
@@ -0,0 +1,65 @@
1
+ import { describe, it, expect, afterAll } from 'vitest';
2
+ import { generateData } from '../../../../test-utils/dist';
3
+ import { IDbPlugin, uuidv4 } from '@routier/core';
4
+ import { PouchDbPlugin } from '../PouchDbPlugin';
5
+ import { TestDataStore } from './datastore/PouchDbDatastore';
6
+
7
+ const pluginFactory: () => IDbPlugin = () => new PouchDbPlugin(uuidv4());
8
+ const stores: TestDataStore[] = [];
9
+ const factory = () => {
10
+
11
+ const store = new TestDataStore(pluginFactory());
12
+
13
+ stores.push(store);
14
+
15
+ return store;
16
+ };
17
+
18
+ describe("Events Tests", () => {
19
+
20
+ afterAll(async () => {
21
+ await Promise.all(stores.map(x => x.destroyAsync()));
22
+ });
23
+
24
+
25
+ describe('Add Operations', () => {
26
+ it("Can add item with default date", async () => {
27
+ const dataStore = factory();
28
+ // Arrange
29
+ const [item] = generateData(dataStore.events.schema, 1);
30
+
31
+ // Act
32
+ const [added] = await dataStore.events.addAsync(item);
33
+ const response = await dataStore.saveChangesAsync();
34
+
35
+ // Assert
36
+ expect(response.aggregate.size).toBe(1);
37
+ expect(added.endTime?.toISOString()).toBe(item.endTime?.toISOString());
38
+ });
39
+
40
+ it("Can add item with default static value", async () => {
41
+ const dataStore = factory();
42
+ // Arrange
43
+ const [item] = generateData(dataStore.events.schema, 1);
44
+
45
+ // Act
46
+ const [added] = await dataStore.events.addAsync(item);
47
+ const response = await dataStore.saveChangesAsync();
48
+ // Assert
49
+ expect(response.aggregate.size).toBe(1);
50
+ expect(added.name).toBe(item.name);
51
+ expect(added.name).toBe("James");
52
+ });
53
+ });
54
+
55
+ describe('Subscription Management', () => {
56
+ it("Should return unsubscribe function", async () => {
57
+ const dataStore = factory();
58
+ await dataStore.events.firstOrUndefinedAsync(w => w._id != "")
59
+ const unsubscribe = dataStore.products.subscribe().where(w => w._id != null).firstOrUndefined(() => { });
60
+ expect(typeof unsubscribe).toBe('function');
61
+ unsubscribe();
62
+ });
63
+ });
64
+
65
+ });
@@ -0,0 +1,59 @@
1
+ import { describe, it, expect, afterAll } from 'vitest';
2
+ import { generateData } from '../../../../test-utils/dist';
3
+ import { IDbPlugin, uuidv4 } from '@routier/core';
4
+ import { PouchDbPlugin } from '../PouchDbPlugin';
5
+ import { TestDataStore } from './datastore/PouchDbDatastore';
6
+
7
+ const pluginFactory: () => IDbPlugin = () => new PouchDbPlugin(uuidv4());
8
+ const stores: TestDataStore[] = [];
9
+ const factory = () => {
10
+
11
+ const store = new TestDataStore(pluginFactory());
12
+
13
+ stores.push(store);
14
+
15
+ return store;
16
+ };
17
+
18
+ describe("Player Tests", () => {
19
+
20
+ afterAll(async () => {
21
+ await Promise.all(stores.map(x => x.destroyAsync()));
22
+ });
23
+
24
+
25
+ describe('One -> Many Operations', () => {
26
+ it("Can add item with default date", async () => {
27
+ const dataStore = factory();
28
+ // Arrange
29
+ const players = generateData(dataStore.players.schema, 4);
30
+
31
+ // Act
32
+ const savedPlayers = await dataStore.players.addAsync(...players);
33
+ const firstSave = await dataStore.saveChangesAsync();
34
+
35
+ expect(firstSave.aggregate.size).toBe(4);
36
+
37
+ for (let i = 0; i < 10; i++) {
38
+ const matchId = `match.${i + 1}`;
39
+
40
+ for (const savedPlayer of savedPlayers) {
41
+ await dataStore.playerMatches.addAsync({
42
+ matchId,
43
+ playerId: savedPlayer._id,
44
+ seasonId: "one"
45
+ });
46
+ }
47
+ }
48
+
49
+ const secondSave = await dataStore.saveChangesAsync();
50
+ expect(secondSave.aggregate.size).toBe(40);
51
+
52
+ const distinctPlayers = await dataStore.players.map(x => x._id).toArrayAsync();
53
+
54
+ const matches = await dataStore.playerMatches.where(([x, p]) => p.distinctPlayers.includes(x.playerId), { distinctPlayers }).toArrayAsync();
55
+
56
+ expect(matches.length).toBe(40);
57
+ });
58
+ });
59
+ });