@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,13 @@
1
+ import { s } from '@routier/core';
2
+
3
+ export const blogPostsSchema = s.define("blogPosts", {
4
+ id: s.string().key().identity(),
5
+ title: s.string(),
6
+ authorId: s.string(),
7
+ content: s.string(),
8
+ tags: s.string().array(),
9
+ isPublished: s.boolean(),
10
+ publishedAt: s.date()
11
+ }).modify(x => ({
12
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
13
+ })).compile();
@@ -0,0 +1,12 @@
1
+ import { s } from "@routier/core/schema";
2
+
3
+ export const commentsSchema = s.define("comments", {
4
+ _id: s.string().key().identity(),
5
+ _rev: s.string().identity(),
6
+ author: s.string(),
7
+ content: s.string(),
8
+ replies: s.number().default(0),
9
+ createdAt: s.date().default(() => new Date()).deserialize(x => (typeof x === "object" && (x as unknown) instanceof Date) ? x : new Date(x))
10
+ }).modify(x => ({
11
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
12
+ })).compile();
@@ -0,0 +1,14 @@
1
+ import { s } from '@routier/core';
2
+
3
+ export const eventsSchema = s.define("events", {
4
+ _id: s.string().key().identity(),
5
+ _rev: s.string().identity(),
6
+ name: s.string().default(x => x.name, { name: "James" }),
7
+ location: s.string().optional(),
8
+ startTime: s.date(),
9
+ endTime: s.date().optional(),
10
+ description: s.string().optional(),
11
+ isOnline: s.boolean()
12
+ }).modify(x => ({
13
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
14
+ })).compile();
@@ -0,0 +1,18 @@
1
+ import { s } from '@routier/core';
2
+
3
+ const isNullOrEmpty = (value: unknown) => {
4
+ return value == null || value == "";
5
+ }
6
+
7
+ export const inventoryItemsSchema = s.define("inventoryItems", {
8
+ sku: s.string().key().identity(),
9
+ name: s.string(),
10
+ quantity: s.number(),
11
+ warehouseLocation: s.string().optional(),
12
+ restockDate: s.date().optional(),
13
+ discontinued: s.boolean()
14
+ }).modify(w => ({
15
+ hasCollectionName: w.computed((_, collectionName, injected) => !injected.isNullOrEmpty(collectionName), { isNullOrEmpty }).tracked(),
16
+ wasRestocked: w.function((x, _collectioNName, injected) => !injected.isNullOrEmpty(x.restockDate != null), { isNullOrEmpty }),
17
+ documentType: w.computed((_, collectionName) => collectionName).tracked()
18
+ })).compile();
@@ -0,0 +1,9 @@
1
+ import { s } from '@routier/core';
2
+
3
+ export const playerSchema = s.define("player", {
4
+ _id: s.string().key().identity(),
5
+ _rev: s.string().identity(),
6
+ name: s.string()
7
+ }).modify(x => ({
8
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
9
+ })).compile();
@@ -0,0 +1,11 @@
1
+ import { s } from '@routier/core';
2
+
3
+ export const playerMatchSchema = s.define("playerMatch", {
4
+ _id: s.string().key().identity(),
5
+ _rev: s.string().identity(),
6
+ matchId: s.string(),
7
+ playerId: s.string(),
8
+ seasonId: s.string()
9
+ }).modify(x => ({
10
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
11
+ })).compile();
@@ -0,0 +1,14 @@
1
+ import { s } from "@routier/core/schema";
2
+
3
+ export const productsSchema = s.define("products", {
4
+ _id: s.string().key().identity(),
5
+ _rev: s.string().identity(),
6
+ name: s.string(),
7
+ price: s.number(),
8
+ category: s.string(),
9
+ inStock: s.boolean(),
10
+ tags: s.string("computer", "accessory").array(),
11
+ createdDate: s.date().default(() => new Date()).deserialize(x => (typeof x === "object" && (x as unknown) instanceof Date) ? x : new Date(x))
12
+ }).modify(x => ({
13
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
14
+ })).compile();
@@ -0,0 +1,17 @@
1
+ import { s, uuidv4 } from '@routier/core';
2
+
3
+ export const usersSchema = s.define("users", {
4
+ id: s.string().key().default(x => x.uuid(), { uuid: uuidv4 }),
5
+ firstName: s.string(),
6
+ lastName: s.string(),
7
+ age: s.number(),
8
+ createdDate: s.date().default(() => new Date("01/01/1900 8:00 AM")),
9
+ address: s.object({
10
+ street: s.string(),
11
+ city: s.string(),
12
+ state: s.string(),
13
+ zip: s.string()
14
+ })
15
+ }).modify(x => ({
16
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
17
+ })).compile();
@@ -0,0 +1,69 @@
1
+ import { s } from '@routier/core';
2
+
3
+ // A more practical example showing computed and function modifiers
4
+ export const userProfileSchema = s.define("userProfiles", {
5
+ _id: s.string().key().identity(),
6
+ _rev: s.string().identity(),
7
+ firstName: s.string(),
8
+ lastName: s.string(),
9
+ email: s.string(),
10
+ dateOfBirth: s.date(),
11
+ address: s.object({
12
+ street: s.string(),
13
+ city: s.string(),
14
+ state: s.string(),
15
+ zipCode: s.string(),
16
+ country: s.string()
17
+ }),
18
+ preferences: s.object({
19
+ theme: s.string("light", "dark"),
20
+ notifications: s.boolean(),
21
+ language: s.string()
22
+ }),
23
+ lastLoginAt: s.date().optional(),
24
+ createdAt: s.date().default(() => new Date())
25
+ }).modify(w => ({
26
+ // Computed: Full name derived from first and last name
27
+ fullName: w.computed(w => `${w.firstName} ${w.lastName}`),
28
+
29
+ // Computed: Age calculated from date of birth
30
+ age: w.computed(w => {
31
+ const today = new Date();
32
+ const birthDate = new Date(w.dateOfBirth);
33
+ let age = today.getFullYear() - birthDate.getFullYear();
34
+ const monthDiff = today.getMonth() - birthDate.getMonth();
35
+ if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
36
+ age--;
37
+ }
38
+ return age;
39
+ }),
40
+
41
+ // Computed: Formatted address string
42
+ formattedAddress: w.computed(w =>
43
+ `${w.address.street}, ${w.address.city}, ${w.address.state} ${w.address.zipCode}, ${w.address.country}`
44
+ ),
45
+
46
+ // Computed: User status based on login activity
47
+ isActive: w.computed(w => {
48
+ if (!w.lastLoginAt) return false;
49
+ const daysSinceLogin = (Date.now() - w.lastLoginAt.getTime()) / (1000 * 60 * 60 * 24);
50
+ return daysSinceLogin <= 30;
51
+ }),
52
+
53
+ // Function: Generate a display name with custom formatting
54
+ getDisplayName: w.function(w => (format: 'short' | 'full') => {
55
+ switch (format) {
56
+ case 'short':
57
+ return w.firstName;
58
+ case 'full':
59
+ return `${w.lastName}, ${w.firstName}`;
60
+ default:
61
+ return `${w.lastName}, ${w.firstName}`;
62
+ }
63
+ }),
64
+
65
+ // Computed: Collection metadata (tracked so it saves to the underlying datastore)
66
+ documentType: w.computed((_, collectionName) => collectionName).tracked()
67
+ })).modify(x => ({
68
+ documentType: x.computed((_, collectionName) => collectionName).tracked()
69
+ })).compile();
@@ -0,0 +1,63 @@
1
+ import { generateData } from '../../../../test-utils/dist';
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("User Profiles Tests", () => {
19
+
20
+ afterAll(async () => {
21
+ await Promise.all(stores.map(x => x.destroyAsync()));
22
+ });
23
+
24
+ describe('Add Operations', () => {
25
+ it("Can add item and access functions", async () => {
26
+ const dataStore = factory();
27
+ // Arrange
28
+ const [item] = generateData(dataStore.userProfiles.schema, 1);
29
+
30
+ // Act
31
+ const [added] = await dataStore.userProfiles.addAsync(item);
32
+ await dataStore.saveChangesAsync();
33
+
34
+ expect(added.age).toBeTypeOf("number");
35
+ });
36
+ });
37
+
38
+ describe('Select Operations', () => {
39
+
40
+ it("Can query on computed untracked property", async () => {
41
+ const dataStore = factory();
42
+ // Arrange
43
+ const items = generateData(dataStore.userProfiles.schema, 1000);
44
+
45
+ // Act
46
+ await dataStore.userProfiles.addAsync(...items);
47
+ await dataStore.saveChangesAsync();
48
+
49
+ const found = await dataStore.userProfiles
50
+ .where(x => x.firstName.startsWith("A"))
51
+ .where(x => x.age === 0).
52
+ firstOrUndefinedAsync();
53
+
54
+ // Enricher is not setting functions properly, needs to be fixed
55
+ expect(found?.fullName).toBeDefined();
56
+ expect(found?.age).toBeDefined();
57
+ expect(found?.formattedAddress).toBeDefined();
58
+ expect(found?.isActive).toBeDefined();
59
+ expect(found?.documentType).toBeDefined();
60
+ expect(typeof found?.getDisplayName).toBe("function");
61
+ });
62
+ });
63
+ });
@@ -0,0 +1,12 @@
1
+ import PouchDB from 'pouchdb';
2
+
3
+ export function assertIsResponse<T extends {}>(value: unknown): asserts value is PouchDB.Find.FindResponse<T> {
4
+ if (isResponse<T>(value) === true) {
5
+ return;
6
+ }
7
+
8
+ throw new Error("value is not typeof FindResponse")
9
+ }
10
+ export function isResponse<T extends {}>(value: unknown): value is PouchDB.Find.FindResponse<T> {
11
+ return value != null && typeof value === "object" && "docs" in value && Array.isArray(value.docs);
12
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "allowSyntheticDefaultImports": true,
5
+ "module": "commonjs",
6
+ "lib": [
7
+ "ESNext",
8
+ "ESNext.disposable"
9
+ ],
10
+ "target": "ESNext",
11
+ "declaration": true,
12
+ "noImplicitAny": true,
13
+ "sourceMap": true,
14
+ "outDir": "./dist",
15
+ "moduleResolution": "node",
16
+ "esModuleInterop": true,
17
+ "skipLibCheck": true,
18
+ "baseUrl": "dist",
19
+ "resolveJsonModule": true
20
+ },
21
+ "include": [
22
+ "./src/index.ts"
23
+ ],
24
+ "exclude": [
25
+ "node_modules",
26
+ "dist",
27
+ "./src/__tests__/*"
28
+ ]
29
+ }
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ coverage: {
8
+ reporter: ['text', 'html'],
9
+ },
10
+ },
11
+ });