Dart服务器端 shelf_rest包

介绍

提供Shelf组件,能够轻松建立统一的,分层的REST资源,而且只需极少的样板。java

shelf_restshelf_route的一个替代品。 它支持shelf_route的全部功能,增长了不少功能以减小样板。json

基本用法

而不是导入shelf_routeapi

import 'package:shelf_route/shelf_route.dart';

你导入shelf_rest框架

import 'package:shelf_rest/shelf_rest.dart';

注意:不要同时导入二者。函数

若是您愿意,能够继续使用它与shelf_route彻底相同,例如。fetch

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_rest/shelf_rest.dart';

void main() {
  var myRouter = router()
    ..get('/accounts/{accountId}', (Request request) {
      var account =
          new Account.build(accountId: getPathParameter(request, 'accountId'));
      return new Response.ok(JSON.encode(account));
    });

  printRoutes(myRouter);
  
  io.serve(myRouter.handler, 'localhost', 8081);
}

class Account {
  final String accountId;

  Account.build({this.accountId});

  Account.fromJson(Map json) : this.accountId = json['accountId'];

  Map toJson() => {'accountId': accountId};
}

使用普通的Dart函数做为处理程序ui

因为shelf_rest自动捆绑shelf_bind,您如今能够移除大部分锅炉板。this

var myRouter = router()
    ..get('accounts/{accountId}',
        (String accountId) => new Account.build(accountId: accountId));

这里,accountId路径参数自动从请求中提取,并做为变量传递给处理函数。 此外,返回的account会自动转换为JSONspa

有关与处理程序一块儿使用的功能的更多详细信息,请参阅shelf_bind的文档。rest

将路由分组到类

您可使用addAll方法将路由分组到类中并将它们安装在给定的子路由中。

class AccountResource {
  void createRoutes(Router r) {
    r..get('{accountId}', (String accountId) => new Account.build(accountId: accountId));
  }
}

void main() {
  var myRouter = router()..addAll(new AccountResource(), path: 'accounts');

  printRoutes(myRouter);

  io.serve(myRouter.handler, 'localhost', 8081);
}

因为UserResource中的createRoutes方法采用类型为Router的单个参数,所以将自动调用此方法。

使用路由注解

您可使用Get注解,而不是实现采用路由的方法(如上面的createRoutes)。

class AccountResource {
  @Get('{accountId}')
  Account find(String accountId) => new Account.build(accountId: accountId);
}

对于Router上的全部方法都存在注解,例如@ Get,@ Post,@ Put,@ Delete@AddAll,这些注解支持与相应方法彻底相同的参数。

@AddAll注解用于添加嵌套路由(子资源)。 例如

class AccountResource {
  @AddAll(path: 'deposits')
  DepositResource deposits() => new DepositResource();
}

注意:@AddAll目前仅支持方法。 可能在将来版本中支持getter

使用RestResource注解

大多数REST资源每每包含许多标准CRUD操做。

为了进一步减小样板并帮助实现一致性,shelf_rest对实现这些CRUD操做提供了特殊支持。

例如,银行账户的RESTful资源可能具备如下类型的操做

搜索账户

GET /accounts?name='Freddy'

获取一个账户

GET /accounts/1234

建立一个账户

POST /accounts

更新账户

PUT /accounts/1234

删除账户

DELETE /accounts/1234

这是shelf_rest中的标准模式,能够按以下方式实现

@RestResource('accountId')
class AccountResource {
  List<Account> search(String name) => .....;

  Account create(Account account) => .....;

  Account update(Account account) => .....;

  Account find(String accountId) => ...;

  void delete(String accountId) => ...;
}

@RestResource('accountId')注解用于表示支持标准CRUD操做的类,并告诉shelf_rest使用accountId做为路径变量。 DELETE的路由看起来像

DELETE /accounts/{accountId}

shelf_rest遵循标准命名约定以最小化配置。 这也有助于提升您对方法命名方式的一致性。

可是,您可使用ResourceMethod注解覆盖默认命名

@ResourceMethod(operation: RestOperation.FIND)
Account fetchAccount(String accountId) => ...;

分层资源

建立分层REST资源很常见。

例如,咱们可能但愿容许存款到咱们的账户,以下所示

PUT ->  /accounts/1234/deposits/999

您可使用上述标准@AddAll注解添加子资源。

@RestResource('accountId')
class AccountResource {

  ....

  @AddAll(path: 'deposits')
  DepositResource deposits() => new DepositResource();
}

DepositResource可能看起来像

@RestResource('depositId')
class DepositResource {

  @ResourceMethod(method: 'PUT')
  Deposit create(Deposit deposit) => ...;
}

请注意,建立操做的默认HTTP方法是POST。 当咱们在调用create时知道资源的主键时常用PUT

shelf_rest中,咱们经过使用ResourceMethod注解覆盖HTTP方法来实现。

要查看此操做,咱们使用printRoutes函数

printRoutes(router);

您能够看到建立了如下路由

GET    ->  /accounts{?name}                            => bound to search method
POST   ->  /accounts                                   => bound to create method
GET    ->  /accounts/{accountId}                       => bound to find method
PUT    ->  /accounts/{accountId}                       => bound to update method
DELETE ->  /accounts/{accountId}                       => bound to delete method
PUT    ->  /accounts/{accountId}/deposits/{depositId}  => bound to create method of DepositResource

请注意,任何不是现有路径变量的参数都将添加到uri模板的查询中。 因此

List<Account> search(String name) => .....;

产生

GET    ->  /accounts{?name}

中间件

您可使用ResourceMethod注解添加将包含在为资源方法建立的路由中的中间件。

@ResourceMethod(middleware: logRequests)
Account find(String accountId) => ...;

一样,您能够将它们添加到GetAddAll等全部Route注解中。 例如

@AddAll(path: 'deposits', middleware: logRequests)
  DepositResource deposits() => new DepositResource();

验证

因为shelf_bind用于从资源方法建立Shelf处理程序,所以请求参数的验证是免费的(由约束提供)。

有关详细信息,请参阅shelf_bind并约束doco。

默认状况下,验证已关闭。 您能够针对特定资源方法启用验证

@ResourceMethod(validateParameters: true)
Account find(String accountId) => ...;

您还能够经过建立新的handlerAdapter来在路由器层次结构的任何级别打开它。 例如,您能够按以下方式为全部路由打开它

var router = router('/accounts', new AccountResource(),
    handlerAdapter: handlerAdapter(validateParameters: true,
        validateReturn: true);

HATEOAS支持

shelf_rest支持使用HATEOAS连接返回响应。 用于操做这些连接的模型位于hateoas_models包中,也能够在客户端上使用。

要使用,只需在ResourceLinksFactory类型的处理程序方法中添加一个参数。 例如

AccountResourceModel find(
  String accountId, ResourceLinksFactory linksFactory) =>
    new AccountResourceModel(
        new Account.build(accountId: accountId), linksFactory(accountId));

这里的AccountResourceModel只是一个包含AccountHATEOAS资源连接的简单类。

class AccountResourceModel extends ResourceModel<Account> {
  final Account account;

  AccountResourceModel(this.account, ResourceLinks links) : super(links);

  Map toJson() => super.toJson()..addAll({'account': account.toJson()});
}

查找操做的典型响应以下所示

{
    "account": {
        "accountId": "123",
        "name": 'fred'
    },
    "links": [
        {
            "href": "123",
            "rel": "self"
        },
        {
            "href": "123",
            "rel": "update"
        },
        {
            "href": "123/deposits/{?deposit}",
            "rel": "deposits.create"
        }
    ]
}

混合和匹配

指定路由的全部不一样形式能够一块儿使用。 一种常见的方法是将@RestResource方法与@Get,@ Post,@ Put,@ Delete注解一块儿用于标准CRUD操做以及不适合标准模型的操做。

使用将Router做为其惟一参数(称为RouteableFunctions)的方法提供了更流畅的替代方案。 特别适用于像mojito这样的框架,例如,使用流畅的api扩展路由器以建立oauth路由。

约定

shelf_rest默认使用如下约定。 每一个均可以用注解覆盖。

  • create ... POST

TODO:更多doco

相关文章
相关标签/搜索