@@ -49,15 +49,32 @@ export interface SimilarChunk extends Omit<MemoryChunk, 'embedding'> {
4949// Create a new database
5050// basePath. The path to
5151export 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+
5866 const adapter = new JSONFile < Schema > ( dbFilePath ) ;
5967 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+
6178 return db ;
6279}
6380
@@ -90,6 +107,9 @@ export async function loadDb(memoryName: string) {
90107 await fs . access ( memoryDbPath ) ;
91108 return await readDb ( memoryDbPath ) ;
92109 } catch ( error ) {
110+ if ( ( error as NodeJS . ErrnoException ) . code === 'ENOENT' ) {
111+ return await createDb ( memoryName ) ;
112+ }
93113 throw error ;
94114 }
95115}
0 commit comments