File size: 2,133 Bytes
ae4ceef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { createRxDatabase, addRxPlugin, RxDatabase, RxCollection, RxJsonSchema } from 'rxdb';
import { getRxStorageDexie } from 'rxdb/plugins/storage-dexie';
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
import { RxDBUpdatePlugin } from 'rxdb/plugins/update';
import { RxDBQueryBuilderPlugin } from 'rxdb/plugins/query-builder';

// Add plugins
addRxPlugin(RxDBQueryBuilderPlugin);
addRxPlugin(RxDBUpdatePlugin);

if (import.meta.env.DEV) {
  addRxPlugin(RxDBDevModePlugin);
}

// Schema definitions
const chatSchema: RxJsonSchema<any> = {
  title: 'chat schema',
  version: 0,
  description: 'describes a chat message',
  primaryKey: 'id',
  type: 'object',
  properties: {
    id: { type: 'string', maxLength: 100 },
    sessionId: { type: 'string' },
    role: { type: 'string' },
    content: { type: 'string' },
    timestamp: { type: 'number' },
    status: { type: 'string' }, // sent, pending, error
    metadata: { type: 'object' }
  },
  required: ['id', 'sessionId', 'role', 'content', 'timestamp'],
  indexes: ['sessionId', 'timestamp']
};

const workflowSchema: RxJsonSchema<any> = {
  title: 'workflow schema',
  version: 0,
  primaryKey: 'id',
  type: 'object',
  properties: {
    id: { type: 'string', maxLength: 100 },
    name: { type: 'string' },
    nodes: { type: 'array' },
    edges: { type: 'array' },
    updatedAt: { type: 'number' }
  },
  required: ['id', 'name', 'nodes', 'edges', 'updatedAt'],
  indexes: ['updatedAt']
};

// Database type
export type MyDatabaseCollections = {
  chats: RxCollection<any>;
  workflows: RxCollection<any>;
};

export type MyDatabase = RxDatabase<MyDatabaseCollections>;

let dbPromise: Promise<MyDatabase> | null = null;

export const getDatabase = async (): Promise<MyDatabase> => {
  if (!dbPromise) {
    dbPromise = createRxDatabase<MyDatabaseCollections>({
      name: 'codex_db',
      storage: getRxStorageDexie(),
      ignoreDuplicate: true
    }).then(async (db) => {
      await db.addCollections({
        chats: { schema: chatSchema },
        workflows: { schema: workflowSchema }
      });
      return db;
    });
  }
  return dbPromise;
};