@@ -4,7 +4,10 @@ import {
44 WorkerMessageTypes ,
55 type WorkerMessage ,
66 type TableExistsResponseData ,
7- type CreateTableRequestData
7+ type CreateTableRequestData ,
8+ type DataRow ,
9+ type FillStorageRequestData ,
10+ type FillStorageResponseData
811} from './types' ;
912
1013const storages = [ 'customers_v1' ] ;
@@ -15,6 +18,12 @@ async function getStructure(storage: string): Promise<TableStructure> {
1518 return data ;
1619}
1720
21+ async function getData ( storage : string , offset : number , limit : number ) {
22+ const res = await fetch ( `/api/data/${ storage } /data?offset=${ offset } &limit=${ limit } ` ) ;
23+ const data = ( await res . json ( ) ) as { data : DataRow [ ] ; moreRows : boolean } ;
24+ return data ;
25+ }
26+
1827async function createStorage ( storage : string , structure : TableStructure ) {
1928 const res = ( await sendMsgToWorker ( {
2029 storageId : storage ,
@@ -26,6 +35,32 @@ async function createStorage(storage: string, structure: TableStructure) {
2635 if ( res . data . errorMsg ) throw new Error ( res . data . errorMsg ) ;
2736}
2837
38+ async function fillStorage ( storage : string , structure : TableStructure ) {
39+ const PAGE_SIZE = 100 ;
40+ let currOffset = 0 ;
41+ let fetchMore = false ;
42+
43+ do {
44+ const { data, moreRows } = await getData ( storage , currOffset , PAGE_SIZE ) ;
45+ console . log ( `Fetched ${ data . length } rows from ${ storage } at offset ${ currOffset } ` , data ) ;
46+
47+ const res = ( await sendMsgToWorker ( {
48+ storageId : storage ,
49+ type : WorkerMessageTypes . FILL_STORAGE ,
50+ expectedType : WorkerMessageTypes . FILL_STORAGE_RESPONSE ,
51+ data : { rows : data , structure : structure } as FillStorageRequestData
52+ } ) ) as WorkerMessage < FillStorageResponseData > ;
53+
54+ if ( res . data . errorMsg ) {
55+ console . error ( `Error filling storage ${ storage } at offset ${ currOffset } ` , res . data . errorMsg ) ;
56+ throw new Error ( res . data . errorMsg ) ;
57+ }
58+
59+ currOffset += PAGE_SIZE ;
60+ fetchMore = moreRows ;
61+ } while ( fetchMore ) ;
62+ }
63+
2964export default async function initStorages ( ) {
3065 for ( const storageId of storages ) {
3166 const res = ( await sendMsgToWorker ( {
@@ -39,10 +74,16 @@ export default async function initStorages() {
3974
4075 if ( res . data . tableExists ) {
4176 console . log ( `Table ${ storageId } exists. Has data: ${ res . data . hasData } ` ) ;
77+
78+ if ( ! res . data . hasData ) {
79+ const structure = await getStructure ( storageId ) ;
80+ await fillStorage ( storageId , structure ) ;
81+ }
4282 } else {
4383 const structure = await getStructure ( storageId ) ;
4484 console . log ( `Table ${ storageId } does not exist. Creating...` , structure ) ;
4585 await createStorage ( storageId , structure ) ;
86+ await fillStorage ( storageId , structure ) ;
4687 }
4788 }
4889}
0 commit comments