1+ using System . Text . Json ;
2+ using LinkRouter . App . Configuration ;
3+
4+ namespace LinkRouter . App . Services ;
5+
6+ public class ConfigWatcher : BackgroundService
7+ {
8+ private string ConfigPath => Path . Combine ( "data" , "config.json" ) ;
9+ private ILogger < ConfigWatcher > Logger ;
10+ private Config Config ;
11+ private FileSystemWatcher Watcher ;
12+
13+ public ConfigWatcher ( ILogger < ConfigWatcher > logger , Config config )
14+ {
15+ Logger = logger ;
16+ Config = config ;
17+ }
18+
19+ protected override Task ExecuteAsync ( CancellationToken stoppingToken )
20+ {
21+ if ( ! File . Exists ( ConfigPath ) )
22+ {
23+ Logger . LogWarning ( "Watched file does not exist: {FilePath}" , ConfigPath ) ;
24+ File . WriteAllText ( ConfigPath , "Initial content" ) ;
25+ }
26+
27+ Watcher = new FileSystemWatcher ( Path . GetDirectoryName ( ConfigPath ) ?? throw new InvalidOperationException ( ) )
28+ {
29+ Filter = Path . GetFileName ( ConfigPath ) ,
30+ NotifyFilter = NotifyFilters . LastWrite | NotifyFilters . Size | NotifyFilters . CreationTime
31+ } ;
32+
33+ Watcher . Changed += OnChanged ;
34+
35+ Watcher . EnableRaisingEvents = true ;
36+
37+ return Task . CompletedTask ;
38+ }
39+
40+ private void OnChanged ( object sender , FileSystemEventArgs e )
41+ {
42+ try
43+ {
44+ var content = File . ReadAllText ( ConfigPath ) ;
45+
46+ var config = JsonSerializer . Deserialize < Config > ( content ) ;
47+
48+ Config . Routes = config ? . Routes ?? [ ] ;
49+ Config . RootRoute = config ? . RootRoute ?? "https://example.com" ;
50+
51+ Logger . LogInformation ( "Config file changed." ) ;
52+ }
53+ catch ( IOException ex )
54+ {
55+ }
56+ }
57+ }
0 commit comments