2016-08-03 126 views
1

我想让我的API支持同一名称的多个参数:例如:多个不能使用Perl Mojolicious Swagger2

/myAPI/search?myfield=1&myfield=2&myfield=3 

我使用Perl和CPAN模块Mojolicious和Swagger2

我招摇文件(YAML)有这个定义(验证):

/search: 
    get: 
     x-mojo-controller: "Search" 
     operationId: search 
     description: Search 
     parameters: 
     - name: myfield 
      description: Array of types 
      in: query 
      type: array 
      collectionFormat: multi 
      uniqueItems: true 
      items: 
      type: string 
      required: false 

我的控制器看起来是这样的:

package myAPI::Controller::Search; 
use Mojo::Base 'Mojolicious::Controller'; 
sub search { 
    my($self, $args, $cb) = @_; 
    $self->render(text => Dumper $args); 
} 

当args被转储到浏览器时,'myfield'字段看起来像是一个数组,但它仍然你永远有最后的价值。

$VAR1 = { 'myfield' => [ '3' ] }; 

Swagger2版本是:

our $VERSION = '0.83'; 

我在做什么错?

回答

1

我认为你正在开发你的例子,或者你可能会有一些钩子混淆输入。下面的测试运行成功:

use Mojo::Base -strict; 
use Test::Mojo; 
use Test::More; 

package MyApp::Example; 
use Mojo::Base 'Mojolicious::Controller'; 

sub search { 
    my ($self, $args, $cb) = @_; 
    $self->$cb($args, 200); 
} 

package main; 
use Mojolicious::Lite; 
plugin Swagger2 => {url => 'data://main/multi-param.json'}; 

my $t = Test::Mojo->new; 
$t->get_ok('/search?myfield=1&myfield=2&myfield=3')->status_is(200)->json_is('/myfield', [1, 2, 3]); 

done_testing; 

__DATA__ 
@@ multi-param.json 
{ 
    "swagger": "2.0", 
    "info": {"version": "1.0", "title": "Test multi"}, 
    "paths": { 
    "/search": { 
     "get": { 
     "x-mojo-controller": "MyApp::Example", 
     "operationId": "search", 
     "parameters": [ 
      { 
      "name": "myfield", 
      "in": "query", 
      "type": "array", 
      "collectionFormat": "multi", 
      "uniqueItems": true, 
      "items": { "type": "string" }, 
      "required": false 
      } 
     ], 
     "responses": { 
      "200": {"description": "whatever", "schema": {"type": "object"}} 
     } 
     } 
    } 
    } 
} 

有已经为这个测试:https://github.com/jhthorsen/swagger2/blob/master/t/multi-param.t

+0

你是对的!我发现了一个操纵参数的'钩子'。谢谢你的指导! – GreensterRox

0

你可能想尝试这个插件来代替:https://metacpan.org/release/Mojolicious-Plugin-OpenAPI

这是与“mojolicious规则”更加一起玩,这意味着你会提取像这样的参数:

sub search { 
    my $c = shift->openapi->valid_input or return; 
    my $values = $c->every_param("myfield"); 
    $c->reply->openapi(200 => $values); 
} 
相关问题