@@ -49,15 +49,32 @@ export interface SimilarChunk extends Omit<MemoryChunk, 'embedding'> {
49
49
// Create a new database
50
50
// basePath. The path to
51
51
export async function createDb ( memoryName : string ) : Promise < Low < Schema > > {
52
- const dbFilePath = path . join (
53
- process . cwd ( ) ,
54
- '.baseai' ,
55
- 'db' ,
56
- `${ memoryName } .json`
57
- ) ;
52
+ const baseDir = path . join ( process . cwd ( ) , '.baseai' , 'db' ) ;
53
+ const dbFilePath = path . join ( baseDir , `${ memoryName } .json` ) ;
54
+
55
+ // Ensure the directory exists
56
+ await fs . mkdir ( baseDir , { recursive : true } ) ;
57
+
58
+ // Check if the file exists, if not, create it with default data
59
+ try {
60
+ await fs . access ( dbFilePath ) ;
61
+ } catch ( error ) {
62
+ // File doesn't exist, create it with default data
63
+ await fs . writeFile ( dbFilePath , JSON . stringify ( defaultData , null , 2 ) ) ;
64
+ }
65
+
58
66
const adapter = new JSONFile < Schema > ( dbFilePath ) ;
59
67
const db = new Low ( adapter , defaultData ) ;
60
- await db . write ( ) ;
68
+
69
+ // Read the existing data or initialize with default
70
+ await db . read ( ) ;
71
+
72
+ // If the file was empty or invalid JSON, write the default data
73
+ if ( db . data === null ) {
74
+ db . data = defaultData ;
75
+ await db . write ( ) ;
76
+ }
77
+
61
78
return db ;
62
79
}
63
80
@@ -90,6 +107,9 @@ export async function loadDb(memoryName: string) {
90
107
await fs . access ( memoryDbPath ) ;
91
108
return await readDb ( memoryDbPath ) ;
92
109
} catch ( error ) {
110
+ if ( ( error as NodeJS . ErrnoException ) . code === 'ENOENT' ) {
111
+ return await createDb ( memoryName ) ;
112
+ }
93
113
throw error ;
94
114
}
95
115
}
0 commit comments