2016-08-03 128 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); 
} 
相關問題