Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pkgs/shelf_router_generator: README.md example update #472

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pkgs/shelf_router_generator/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 1.1.2

* Updated `README.md` with current example from `examples/main.dart`.

## 1.1.1

* Support the latest `package:analyzer` and `package:source_gen`
Expand Down
96 changes: 69 additions & 27 deletions pkgs/shelf_router_generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,43 +29,85 @@ generated part can be created with `pub run build_runner build`.
## Example

```dart
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import 'dart:async' show Future;

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';

part 'userservice.g.dart'; // generated with 'pub run build_runner build'
// Generated code will be written to 'main.g.dart'
part 'main.g.dart';

class Service {
// A handler is annotated with @Route.<verb>('<route>'), the '<route>' may
// embed URL-parameters, and these may be taken as parameters by the handler.
// But either all URL-parameters or none of the URL parameters must be taken
// as parameters by the handler.
@Route.get('/say-hi/<name>')
Response _hi(Request request, String name) => Response.ok('hi $name');

// Embedded URL parameters may also be associated with a regular-expression
// that the pattern must match.
@Route.get('/user/<userId|[0-9]+>')
Response _user(Request request, String userId) =>
Response.ok('User has the user-number: $userId');

// Handlers can be asynchronous (returning `FutureOr` is also allowed).
@Route.get('/wave')
Future<Response> _wave(Request request) async {
await Future<void>.delayed(const Duration(milliseconds: 100));
return Response.ok('_o/');
}

class UserService {
final DatabaseConnection connection;
UserService(this.connection);
// Other routers can be mounted...
@Route.mount('/api')
Router get _api => Api().router;

@Route.get('/users/')
Future<Response> listUsers(Request request) async {
return Response.ok('["user1"]');
}
// You can catch all verbs and use a URL-parameter with a regular expression
// that matches everything to catch app.
@Route.all('/<ignored|.*>')
Response _notFound(Request request) => Response.notFound('Page not found');

@Route.get('/users/<userId>')
Future<Response> fetchUser(Request request, String userId) async {
if (userId == 'user1') {
return Response.ok('user1');
}
return Response.notFound('no such user');
}
// The generated function _$ServiceRouter can be used to get a [Handler]
// for this object. This can be used with [shelf_io.serve].
Handler get handler => _$ServiceRouter(this).call;
}

class Api {
// A handler can have more that one route :)
@Route.get('/messages')
@Route.get('/messages/')
Future<Response> _messages(Request request) async => Response.ok('[]');

// This nested catch-all, will only catch /api/.* when mounted above.
// Notice that ordering if annotated handlers and mounts is significant.
@Route.all('/<ignored|.*>')
Response _notFound(Request request) => Response.notFound('null');

// Create router using the generate function defined in 'userservice.g.dart'.
Router get router => _$UserServiceRouter(this);
// The generated function _$ApiRouter can be used to expose a [Router] for
// this object.
Router get router => _$ApiRouter(this);
}

// Run shelf server and host a [Service] instance on port 8080.
void main() async {
// You can setup context, database connections, cache connections, email
// services, before you create an instance of your service.
var connection = await DatabaseConnection.connect('localhost:1234');

// Create an instance of your service, usine one of the constructors you've
// defined.
var service = UserService(connection);
// Service request using the router, note the router can also be mounted.
var router = service.router;
var server = await io.serve(router.handler, 'localhost', 8080);
final service = Service();
final server = await shelf_io.serve(service.handler, 'localhost', 8080);
print('Server running on localhost:${server.port}');
}
```

Expand Down
2 changes: 1 addition & 1 deletion pkgs/shelf_router_generator/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: shelf_router_generator
version: 1.1.1
version: 1.1.2
description: >
A package:build-compatible builder for generating request routers for the
shelf web-framework based on source annotations.
Expand Down