launchpad 0.3.0
launchpad: ^0.3.0 copied to clipboard
The missing dependency injection for Serverpod. Request-scoped and server-wide get_it containers for endpoints, streaming methods and future calls.
Launchpad example #
A Serverpod 4 project using launchpad:
example_server: the server. Seeserver.dart,hello_endpoint.dartandvisitor_report_future_call.dart.example_client: the generated client.example_flutter: a Flutter app calling the server.
Server setup #
import 'package:launchpad/launchpad.dart';
import 'package:serverpod/serverpod.dart';
void run(List<String> args) async {
final pod = Serverpod(args, Protocol(), Endpoints());
// Server-wide dependencies, shared across all requests on this pod.
Launchpad.initServerContext(pod, (getIt) {
getIt.registerSingleton(ServerState());
});
await pod.start();
// Schedule a future call. Its method is wrapped with `Launchpad.launch`, so
// it can use the same server context as the endpoints.
await pod.futureCalls
.callWithDelay(const Duration(seconds: 10))
.visitorReport
.report('startup');
}
Request-scoped dependencies are registered with Launchpad.launchpadInit, see the
package README.
Endpoint with a streaming method #
class HelloEndpoint extends Endpoint {
Future<String> hello(Session session) => Launchpad.launch(
session,
(context) async {
final serverState = context.serverContext.get<ServerState>();
serverState.counter += 1;
return 'Hello from Serverpod! You are visitor number ${serverState.counter}.';
},
);
Stream<String> countdown(Session session, int from) => Launchpad.launchStream(
session,
(context) async* {
final serverState = context.serverContext.get<ServerState>();
for (var i = from; i > 0; i--) {
yield '$i... (visitors so far: ${serverState.counter})';
await Future.delayed(const Duration(seconds: 1));
}
yield 'Liftoff!';
},
);
}
Future call #
class VisitorReportFutureCall extends FutureCall {
Future<void> report(Session session, String reason) => Launchpad.launch(
session,
(context) async {
final serverState = context.serverContext.get<ServerState>();
session.log('[$reason] Visitors so far: ${serverState.counter}');
},
);
}
Running it #
cd example_server
docker compose up --build --detach
dart bin/main.dart