11import { Request , Response , Router } from 'express' ;
2+ import fsSync from 'fs' ;
23import fs from 'fs/promises' ;
34import StatusCodes from 'http-status-codes' ;
45import path from 'path' ;
@@ -7,12 +8,20 @@ export const layoutRoute = Router();
78
89const CONFIG_FILE = path . join ( __dirname , '../config/config.json' ) ;
910
11+ const loadConfig = ( ) => {
12+ if ( fsSync . existsSync ( CONFIG_FILE ) ) {
13+ return JSON . parse ( fsSync . readFileSync ( CONFIG_FILE , 'utf-8' ) ) ;
14+ }
15+ return { layout : { desktop : [ ] , mobile : [ ] } } ;
16+ } ;
17+
1018// GET - Retrieve the saved layout JSON from disk
1119layoutRoute . get ( '/' , async ( _req : Request , res : Response ) : Promise < void > => {
1220 try {
13- const data = await fs . readFile ( CONFIG_FILE , 'utf-8' ) ;
14- const layout = JSON . parse ( data ) ;
15- res . status ( StatusCodes . OK ) . json ( layout . layout ) ;
21+ const config = loadConfig ( ) ;
22+ console . log ( 'loading layout' , config ) ;
23+
24+ res . status ( StatusCodes . OK ) . json ( config . layout ) ;
1625 } catch ( error ) {
1726 res . status ( StatusCodes . INTERNAL_SERVER_ERROR ) . json ( {
1827 message : 'Error reading layout file' ,
@@ -24,14 +33,18 @@ layoutRoute.get('/', async (_req: Request, res: Response): Promise<void> => {
2433// POST - Save the incoming JSON layout to disk
2534layoutRoute . post ( '/' , async ( req : Request , res : Response ) : Promise < void > => {
2635 try {
27- const layout = req . body ;
28-
29- if ( ! layout || typeof layout !== 'object' ) {
30- res . status ( StatusCodes . BAD_REQUEST ) . json ( { message : 'Invalid layout data' } ) ;
31- return ;
32- }
33- // TODO: write only layout section
34- await fs . writeFile ( CONFIG_FILE , JSON . stringify ( { layout : layout } , null , 2 ) , 'utf-8' ) ;
36+ console . log ( 'saving layout body' , req . body ) ;
37+
38+ const { desktop, mobile } = req . body ;
39+ const config = loadConfig ( ) ;
40+
41+ console . log ( 'config' , config ) ;
42+ config . layout . desktop = desktop && desktop . length > 0 ? desktop : config . layout . desktop ;
43+ config . layout . mobile = mobile && mobile . length > 0 ? mobile : desktop ;
44+ console . log ( 'config2' , config ) ;
45+
46+
47+ await fs . writeFile ( CONFIG_FILE , JSON . stringify ( config , null , 2 ) , 'utf-8' ) ;
3548 res . status ( StatusCodes . OK ) . json ( { message : 'Layout saved successfully' } ) ;
3649 } catch ( error ) {
3750 res . status ( StatusCodes . INTERNAL_SERVER_ERROR ) . json ( {
0 commit comments