2018-09-04 20:04:53 +00:00
|
|
|
import 'dart:async';
|
|
|
|
import 'dart:isolate';
|
|
|
|
import 'package:angel_framework/angel_framework.dart';
|
|
|
|
import 'package:angel_production/angel_production.dart';
|
2018-09-04 22:00:53 +00:00
|
|
|
import 'package:pub_sub/pub_sub.dart' as pub_sub;
|
2018-09-04 20:04:53 +00:00
|
|
|
|
2021-05-01 02:03:46 +00:00
|
|
|
void main(List<String> args) => Runner('example', configureServer).run(args);
|
2018-09-04 20:04:53 +00:00
|
|
|
|
|
|
|
Future configureServer(Angel app) async {
|
2018-09-04 22:00:53 +00:00
|
|
|
// Use the injected `pub_sub.Client` to send messages.
|
2021-05-01 02:03:46 +00:00
|
|
|
var client = app.container!.make<pub_sub.Client>()!;
|
|
|
|
String? greeting = 'Hello! This is the default greeting.';
|
2018-09-04 22:00:53 +00:00
|
|
|
|
|
|
|
// We can listen for an event to perform some behavior.
|
|
|
|
//
|
|
|
|
// Here, we use message passing to synchronize some common state.
|
|
|
|
var onGreetingChanged = await client.subscribe('greeting_changed');
|
|
|
|
onGreetingChanged
|
|
|
|
.cast<String>()
|
|
|
|
.listen((newGreeting) => greeting = newGreeting);
|
|
|
|
|
|
|
|
// Add some routes...
|
2018-09-04 20:04:53 +00:00
|
|
|
app.get('/', (req, res) => 'Hello, production world!');
|
|
|
|
|
2019-04-28 17:51:08 +00:00
|
|
|
app.get('/404', (req, res) {
|
|
|
|
res.statusCode = 404;
|
|
|
|
return res.close();
|
|
|
|
});
|
|
|
|
|
2018-09-04 22:00:53 +00:00
|
|
|
// Create some routes to demonstrate message passing.
|
|
|
|
app.get('/greeting', (req, res) => greeting);
|
|
|
|
|
|
|
|
// This route will push a new value for `greeting`.
|
|
|
|
app.get('/change_greeting/:newGreeting', (req, res) {
|
2021-05-01 02:03:46 +00:00
|
|
|
greeting = req.params['newGreeting'] as String?;
|
2018-09-04 22:00:53 +00:00
|
|
|
client.publish('greeting_changed', greeting);
|
|
|
|
return 'Changed greeting -> $greeting';
|
|
|
|
});
|
|
|
|
|
|
|
|
// The `Runner` helps with fault tolerance.
|
2018-09-04 20:04:53 +00:00
|
|
|
app.get('/crash', (req, res) {
|
|
|
|
// We'll crash this instance deliberately, but the Runner will auto-respawn for us.
|
2019-04-28 17:51:08 +00:00
|
|
|
Timer(const Duration(seconds: 3), Isolate.current.kill);
|
2018-09-04 20:04:53 +00:00
|
|
|
return 'Crashing in 3s...';
|
|
|
|
});
|
|
|
|
}
|