rojects/source/server/routes/layout.ts

46 lines
1.5 KiB
TypeScript
Raw Normal View History

import { Router } from 'express';
import fs from 'fs';
import path from 'path';
import { requireAuth } from '../middleware/auth';
import { RJLog } from '../../library-ts/node/log/RJLog';
import { ROOT } from '../rootDir';
const router = Router();
router.use( requireAuth );
const LAYOUTS_DIR = path.join( ROOT, 'build', 'data', 'storage', 'layouts' );
function layoutFilePath( userId: string, deviceId: string ): string
{
RJLog.log( { userId, deviceId } );
const safe = ( s: string ) => s.replace( /[^a-zA-Z0-9_-]/g, '_' );
const dir = path.join( LAYOUTS_DIR, safe( userId ) );
if ( !fs.existsSync( dir ) ) fs.mkdirSync( dir, { recursive: true } );
return path.join( dir, safe( deviceId ) + '.json' );
}
router.get( '/', ( req, res ) =>
{
const deviceId = req.query.deviceId as string;
if ( !deviceId ) { res.json( null ); return; }
const fp = layoutFilePath( req.user!.userId, deviceId );
if ( !fs.existsSync( fp ) ) { res.json( null ); return; }
try { res.json( JSON.parse( fs.readFileSync( fp, 'utf8' ) ) ); }
catch { res.json( null ); }
} );
router.put( '/', ( req, res ) =>
{
const deviceId = req.query.deviceId as string;
if ( !deviceId ) { res.status( 400 ).json( { error: 'Missing deviceId' } ); return; }
const fp = layoutFilePath( req.user!.userId, deviceId );
try
{
fs.writeFileSync( fp, JSON.stringify( req.body ), 'utf8' );
res.json( { ok: true } );
}
catch ( e ) { res.status( 500 ).json( { error: String( e ) } ); }
} );
export default router;