Spaces:
Running
Running
feat: Implement Munger Engine API with v1 routes, data storage, core logic, and Docker deployment configuration.
ce3c7ff | import fs from 'fs'; | |
| import path from 'path'; | |
| import { MungerStock, EngineStatus } from './types'; | |
| const DATA_DIR = path.resolve(process.cwd(), 'data'); | |
| const STOCKS_FILE = path.join(DATA_DIR, 'stocks.json'); | |
| const STATUS_FILE = path.join(DATA_DIR, 'status.json'); | |
| // Ensure data dir exists | |
| if (!fs.existsSync(DATA_DIR)) { | |
| fs.mkdirSync(DATA_DIR, { recursive: true }); | |
| } | |
| export class JsonStore { | |
| private static readJson<T>(filePath: string, defaultValue: T): T { | |
| try { | |
| if (!fs.existsSync(filePath)) { | |
| return defaultValue; | |
| } | |
| const data = fs.readFileSync(filePath, 'utf-8'); | |
| return JSON.parse(data); | |
| } catch (error) { | |
| console.error(`Error reading ${filePath}:`, error); | |
| return defaultValue; | |
| } | |
| } | |
| private static writeJson<T>(filePath: string, data: T): void { | |
| try { | |
| fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8'); | |
| } catch (error) { | |
| console.error(`Error writing ${filePath}:`, error); | |
| } | |
| } | |
| static getStocks(): MungerStock[] { | |
| return this.readJson<MungerStock[]>(STOCKS_FILE, []); | |
| } | |
| static saveStocks(stocks: MungerStock[]): void { | |
| this.writeJson(STOCKS_FILE, stocks); | |
| } | |
| static getStatus(): EngineStatus { | |
| return this.readJson<EngineStatus>(STATUS_FILE, { | |
| status: 'IDLE', | |
| lastSyncTimestamp: new Date().toISOString(), | |
| apiLatencyMs: 0, | |
| totalAssets: 0, | |
| assetsAnalyzed: 0, | |
| buyTriggers: 0, | |
| errors: [] | |
| }); | |
| } | |
| static updateStatus(partialStatus: Partial<EngineStatus>): void { | |
| const current = this.getStatus(); | |
| this.writeJson(STATUS_FILE, { ...current, ...partialStatus }); | |
| } | |
| static getStock(symbol: string): MungerStock | undefined { | |
| const stocks = this.getStocks(); | |
| return stocks.find(s => s.symbol === symbol); | |
| } | |
| } | |