diff --git a/.gitignore b/.gitignore index e7b9e65..709e02d 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ Thumbs.db .idea/ *.ipr +# +.swagger-codegen \ No newline at end of file diff --git a/example/clients/go/.gitignore b/example/clients/go/.gitignore new file mode 100644 index 0000000..daf913b --- /dev/null +++ b/example/clients/go/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/example/clients/go/.swagger-codegen-ignore b/example/clients/go/.swagger-codegen-ignore new file mode 100644 index 0000000..c5fa491 --- /dev/null +++ b/example/clients/go/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/example/clients/go/.travis.yml b/example/clients/go/.travis.yml new file mode 100644 index 0000000..f5cb2ce --- /dev/null +++ b/example/clients/go/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/example/clients/go/README.md b/example/clients/go/README.md new file mode 100644 index 0000000..e96509c --- /dev/null +++ b/example/clients/go/README.md @@ -0,0 +1,58 @@ +# Go API client for swagger + +No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: +- Package version: 1.0.0 +- Build package: io.swagger.codegen.languages.GoClientCodegen + +## Installation +Put the package under your project folder and add the following in import: +```golang +import "./swagger" +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*GreetApi* | [**Ping**](docs/GreetApi.md#ping) | **Get** /user/ping | +*UserApiApi* | [**GetUserInfo**](docs/UserApiApi.md#getuserinfo) | **Get** /api/user/{id} | 获取用户信息 +*UserApiApi* | [**Login**](docs/UserApiApi.md#login) | **Post** /api/user/login | 登录 +*UserApiApi* | [**Register**](docs/UserApiApi.md#register) | **Post** /api/user/register | 注册 +*UserApiApi* | [**SearchUser**](docs/UserApiApi.md#searchuser) | **Get** /api/user/search | 用户搜索 + + +## Documentation For Models + + - [LoginReq](docs/LoginReq.md) + - [RegisterReq](docs/RegisterReq.md) + - [UserInfoReply](docs/UserInfoReply.md) + - [UserInfoReq](docs/UserInfoReq.md) + - [UserSearchReply](docs/UserSearchReply.md) + - [UserSearchReq](docs/UserSearchReq.md) + + +## Documentation For Authorization + +## apiKey +- **Type**: API key + +Example +```golang +auth := context.WithValue(context.Background(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. +}) +r, err := client.Service.Operation(auth, args) +``` + +## Author + + + diff --git a/example/clients/go/api/swagger.yaml b/example/clients/go/api/swagger.yaml new file mode 100644 index 0000000..b57e408 --- /dev/null +++ b/example/clients/go/api/swagger.yaml @@ -0,0 +1,196 @@ +--- +swagger: "2.0" +info: + version: "" + title: "" +schemes: +- "http" +- "https" +consumes: +- "application/json" +produces: +- "application/json" +paths: + /api/user/login: + post: + tags: + - "user-api" + summary: "登录" + operationId: "login" + parameters: + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/LoginReq" + x-exportParamName: "Body" + responses: + "200": + description: "A successful response." + schema: {} + /api/user/register: + post: + tags: + - "user-api" + summary: "注册" + description: "注册一个用户" + operationId: "register" + parameters: + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/RegisterReq" + x-exportParamName: "Body" + responses: + "200": + description: "A successful response." + schema: {} + /api/user/search: + get: + tags: + - "user-api" + summary: "用户搜索" + operationId: "searchUser" + parameters: + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/UserSearchReq" + x-exportParamName: "Body" + responses: + "200": + description: "A successful response." + schema: + $ref: "#/definitions/UserSearchReply" + /api/user/{id}: + get: + tags: + - "user-api" + summary: "获取用户信息" + operationId: "getUserInfo" + parameters: + - name: "id" + in: "path" + required: true + type: "string" + x-exportParamName: "Id" + - in: "body" + name: "body" + required: true + schema: + $ref: "#/definitions/UserInfoReq" + x-exportParamName: "Body" + responses: + "200": + description: "A successful response." + schema: + $ref: "#/definitions/UserInfoReply" + /user/ping: + get: + tags: + - "greet" + operationId: "ping" + parameters: [] + responses: + "200": + description: "A successful response." + schema: {} +securityDefinitions: + apiKey: + description: "Enter JWT Bearer token **_only_**" + type: "apiKey" + name: "Authorization" + in: "header" +definitions: + LoginReq: + type: "object" + properties: + username: + type: "string" + password: + type: "string" + title: "LoginReq" + example: + password: "password" + username: "username" + RegisterReq: + type: "object" + properties: + username: + type: "string" + password: + type: "string" + mobile: + type: "string" + title: "RegisterReq" + example: + password: "password" + mobile: "mobile" + username: "username" + UserInfoReply: + type: "object" + properties: + name: + type: "string" + age: + type: "integer" + format: "int32" + birthday: + type: "string" + description: + type: "string" + tag: + type: "array" + items: + type: "string" + title: "UserInfoReply" + example: + birthday: "birthday" + name: "name" + description: "description" + tag: + - "tag" + - "tag" + age: 0 + UserInfoReq: + type: "object" + properties: + id: + type: "string" + title: "UserInfoReq" + example: + id: "id" + UserSearchReply: + type: "object" + properties: + KeyWord: + type: "array" + items: + $ref: "#/definitions/UserInfoReply" + title: "UserSearchReply" + example: + KeyWord: + - birthday: "birthday" + name: "name" + description: "description" + tag: + - "tag" + - "tag" + age: 0 + - birthday: "birthday" + name: "name" + description: "description" + tag: + - "tag" + - "tag" + age: 0 + UserSearchReq: + type: "object" + properties: + keyWord: + type: "string" + title: "UserSearchReq" + example: + keyWord: "keyWord" diff --git a/example/clients/go/api_greet.go b/example/clients/go/api_greet.go new file mode 100644 index 0000000..63f91ca --- /dev/null +++ b/example/clients/go/api_greet.go @@ -0,0 +1,109 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +import ( + "context" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// Linger please +var ( + _ context.Context +) + +type GreetApiService service + +/* +GreetApiService + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + +@return interface{} +*/ +func (a *GreetApiService) Ping(ctx context.Context) (interface{}, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue interface{} + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/user/ping" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v interface{} + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} diff --git a/example/clients/go/api_user_api.go b/example/clients/go/api_user_api.go new file mode 100644 index 0000000..e053b71 --- /dev/null +++ b/example/clients/go/api_user_api.go @@ -0,0 +1,377 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +import ( + "context" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +// Linger please +var ( + _ context.Context +) + +type UserApiApiService service + +/* +UserApiApiService 获取用户信息 + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param id + * @param body + +@return UserInfoReply +*/ +func (a *UserApiApiService) GetUserInfo(ctx context.Context, id string, body UserInfoReq) (UserInfoReply, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue UserInfoReply + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/api/user/{id}" + localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v UserInfoReply + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +UserApiApiService 登录 + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param body + +@return interface{} +*/ +func (a *UserApiApiService) Login(ctx context.Context, body LoginReq) (interface{}, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue interface{} + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/api/user/login" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v interface{} + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +UserApiApiService 注册 +注册一个用户 + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param body + +@return interface{} +*/ +func (a *UserApiApiService) Register(ctx context.Context, body RegisterReq) (interface{}, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Post") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue interface{} + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/api/user/register" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v interface{} + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} + +/* +UserApiApiService 用户搜索 + * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + * @param body + +@return UserSearchReply +*/ +func (a *UserApiApiService) SearchUser(ctx context.Context, body UserSearchReq) (UserSearchReply, *http.Response, error) { + var ( + localVarHttpMethod = strings.ToUpper("Get") + localVarPostBody interface{} + localVarFileName string + localVarFileBytes []byte + localVarReturnValue UserSearchReply + ) + + // create path and map variables + localVarPath := a.client.cfg.BasePath + "/api/user/search" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + + // to determine the Accept header + localVarHttpHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHttpResponse, err := a.client.callAPI(r) + if err != nil || localVarHttpResponse == nil { + return localVarReturnValue, localVarHttpResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) + localVarHttpResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode < 300 { + // If we succeed, return the data, otherwise pass on to decode error. + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + return localVarReturnValue, localVarHttpResponse, err + } + + if localVarHttpResponse.StatusCode >= 300 { + newErr := GenericSwaggerError{ + body: localVarBody, + error: localVarHttpResponse.Status, + } + + if localVarHttpResponse.StatusCode == 200 { + var v UserSearchReply + err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) + if err != nil { + newErr.error = err.Error() + return localVarReturnValue, localVarHttpResponse, newErr + } + newErr.model = v + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, newErr + } + + return localVarReturnValue, localVarHttpResponse, nil +} diff --git a/example/clients/go/client.go b/example/clients/go/client.go new file mode 100644 index 0000000..3e7ddbb --- /dev/null +++ b/example/clients/go/client.go @@ -0,0 +1,477 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:(?:application|text)/json)") + xmlCheck = regexp.MustCompile("(?i:(?:application|text)/xml)") +) + +// APIClient manages communication with the API v +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + GreetApi *GreetApiService + + UserApiApi *UserApiApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.GreetApi = (*GreetApiService)(&c.common) + c.UserApiApi = (*UserApiApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } + + return fmt.Sprintf("%v", obj) +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} + +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath(path string) { + c.cfg.BasePath = path +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Override request host, if applicable + if c.cfg.Host != "" { + localVarRequest.Host = c.cfg.Host + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if strings.Contains(contentType, "application/xml") { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } else if strings.Contains(contentType, "application/json") { + if err = json.Unmarshal(b, v); err != nil { + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericSwaggerError Provides access to the body, error and model on returned errors. +type GenericSwaggerError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericSwaggerError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericSwaggerError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericSwaggerError) Model() interface{} { + return e.model +} diff --git a/example/clients/go/configuration.go b/example/clients/go/configuration.go new file mode 100644 index 0000000..524634c --- /dev/null +++ b/example/clients/go/configuration.go @@ -0,0 +1,72 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +import ( + "net/http" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextBasicAuth takes BasicAuth as authentication for the request. + ContextBasicAuth = contextKey("basic") + + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + + // ContextAPIKey takes an APIKey as authentication for the request + ContextAPIKey = contextKey("apikey") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +type Configuration struct { + BasePath string `json:"basePath,omitempty"` + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + HTTPClient *http.Client +} + +func NewConfiguration() *Configuration { + cfg := &Configuration{ + BasePath: "http://localhost", + DefaultHeader: make(map[string]string), + UserAgent: "Swagger-Codegen/1.0.0/go", + } + return cfg +} + +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} diff --git a/example/clients/go/docs/GreetApi.md b/example/clients/go/docs/GreetApi.md new file mode 100644 index 0000000..8ec5c03 --- /dev/null +++ b/example/clients/go/docs/GreetApi.md @@ -0,0 +1,31 @@ +# \GreetApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Ping**](GreetApi.md#Ping) | **Get** /user/ping | + + +# **Ping** +> interface{} Ping(ctx, ) + + +### Required Parameters +This endpoint does not need any parameter. + +### Return type + +[**interface{}**](interface{}.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/example/clients/go/docs/LoginReq.md b/example/clients/go/docs/LoginReq.md new file mode 100644 index 0000000..ba1b7a3 --- /dev/null +++ b/example/clients/go/docs/LoginReq.md @@ -0,0 +1,11 @@ +# LoginReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Username** | **string** | | [optional] [default to null] +**Password** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/go/docs/RegisterReq.md b/example/clients/go/docs/RegisterReq.md new file mode 100644 index 0000000..4699374 --- /dev/null +++ b/example/clients/go/docs/RegisterReq.md @@ -0,0 +1,12 @@ +# RegisterReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Username** | **string** | | [optional] [default to null] +**Password** | **string** | | [optional] [default to null] +**Mobile** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/go/docs/UserApiApi.md b/example/clients/go/docs/UserApiApi.md new file mode 100644 index 0000000..a3c5db6 --- /dev/null +++ b/example/clients/go/docs/UserApiApi.md @@ -0,0 +1,119 @@ +# \UserApiApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**GetUserInfo**](UserApiApi.md#GetUserInfo) | **Get** /api/user/{id} | 获取用户信息 +[**Login**](UserApiApi.md#Login) | **Post** /api/user/login | 登录 +[**Register**](UserApiApi.md#Register) | **Post** /api/user/register | 注册 +[**SearchUser**](UserApiApi.md#SearchUser) | **Get** /api/user/search | 用户搜索 + + +# **GetUserInfo** +> UserInfoReply GetUserInfo(ctx, id, body) +获取用户信息 + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **id** | **string**| | + **body** | [**UserInfoReq**](UserInfoReq.md)| | + +### Return type + +[**UserInfoReply**](UserInfoReply.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **Login** +> interface{} Login(ctx, body) +登录 + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **body** | [**LoginReq**](LoginReq.md)| | + +### Return type + +[**interface{}**](interface{}.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **Register** +> interface{} Register(ctx, body) +注册 + +注册一个用户 + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **body** | [**RegisterReq**](RegisterReq.md)| | + +### Return type + +[**interface{}**](interface{}.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **SearchUser** +> UserSearchReply SearchUser(ctx, body) +用户搜索 + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc. + **body** | [**UserSearchReq**](UserSearchReq.md)| | + +### Return type + +[**UserSearchReply**](UserSearchReply.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/example/clients/go/docs/UserInfoReply.md b/example/clients/go/docs/UserInfoReply.md new file mode 100644 index 0000000..7623cae --- /dev/null +++ b/example/clients/go/docs/UserInfoReply.md @@ -0,0 +1,14 @@ +# UserInfoReply + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Name** | **string** | | [optional] [default to null] +**Age** | **int32** | | [optional] [default to null] +**Birthday** | **string** | | [optional] [default to null] +**Description** | **string** | | [optional] [default to null] +**Tag** | **[]string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/go/docs/UserInfoReq.md b/example/clients/go/docs/UserInfoReq.md new file mode 100644 index 0000000..1c055ee --- /dev/null +++ b/example/clients/go/docs/UserInfoReq.md @@ -0,0 +1,10 @@ +# UserInfoReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/go/docs/UserSearchReply.md b/example/clients/go/docs/UserSearchReply.md new file mode 100644 index 0000000..6ac5fb9 --- /dev/null +++ b/example/clients/go/docs/UserSearchReply.md @@ -0,0 +1,10 @@ +# UserSearchReply + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**KeyWord** | [**[]UserInfoReply**](UserInfoReply.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/go/docs/UserSearchReq.md b/example/clients/go/docs/UserSearchReq.md new file mode 100644 index 0000000..571fe72 --- /dev/null +++ b/example/clients/go/docs/UserSearchReq.md @@ -0,0 +1,10 @@ +# UserSearchReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**KeyWord** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/go/git_push.sh b/example/clients/go/git_push.sh new file mode 100644 index 0000000..ae01b18 --- /dev/null +++ b/example/clients/go/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/example/clients/go/model_login_req.go b/example/clients/go/model_login_req.go new file mode 100644 index 0000000..a54339d --- /dev/null +++ b/example/clients/go/model_login_req.go @@ -0,0 +1,15 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +type LoginReq struct { + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` +} diff --git a/example/clients/go/model_register_req.go b/example/clients/go/model_register_req.go new file mode 100644 index 0000000..62df97e --- /dev/null +++ b/example/clients/go/model_register_req.go @@ -0,0 +1,16 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +type RegisterReq struct { + Username string `json:"username,omitempty"` + Password string `json:"password,omitempty"` + Mobile string `json:"mobile,omitempty"` +} diff --git a/example/clients/go/model_user_info_reply.go b/example/clients/go/model_user_info_reply.go new file mode 100644 index 0000000..289b156 --- /dev/null +++ b/example/clients/go/model_user_info_reply.go @@ -0,0 +1,18 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +type UserInfoReply struct { + Name string `json:"name,omitempty"` + Age int32 `json:"age,omitempty"` + Birthday string `json:"birthday,omitempty"` + Description string `json:"description,omitempty"` + Tag []string `json:"tag,omitempty"` +} diff --git a/example/clients/go/model_user_info_req.go b/example/clients/go/model_user_info_req.go new file mode 100644 index 0000000..3e848df --- /dev/null +++ b/example/clients/go/model_user_info_req.go @@ -0,0 +1,14 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +type UserInfoReq struct { + Id string `json:"id,omitempty"` +} diff --git a/example/clients/go/model_user_search_reply.go b/example/clients/go/model_user_search_reply.go new file mode 100644 index 0000000..a76af6a --- /dev/null +++ b/example/clients/go/model_user_search_reply.go @@ -0,0 +1,14 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +type UserSearchReply struct { + KeyWord []UserInfoReply `json:"KeyWord,omitempty"` +} diff --git a/example/clients/go/model_user_search_req.go b/example/clients/go/model_user_search_req.go new file mode 100644 index 0000000..49ad24a --- /dev/null +++ b/example/clients/go/model_user_search_req.go @@ -0,0 +1,14 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +type UserSearchReq struct { + KeyWord string `json:"keyWord,omitempty"` +} diff --git a/example/clients/go/response.go b/example/clients/go/response.go new file mode 100644 index 0000000..1be42e6 --- /dev/null +++ b/example/clients/go/response.go @@ -0,0 +1,43 @@ +/* + * + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * API version: + * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) + */ + +package swagger + +import ( + "net/http" +) + +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the swagger operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/example/clients/javascript/.swagger-codegen-ignore b/example/clients/javascript/.swagger-codegen-ignore new file mode 100644 index 0000000..c5fa491 --- /dev/null +++ b/example/clients/javascript/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/example/clients/javascript/.travis.yml b/example/clients/javascript/.travis.yml new file mode 100644 index 0000000..e49f469 --- /dev/null +++ b/example/clients/javascript/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "6" + - "6.1" + - "5" + - "5.11" + diff --git a/example/clients/javascript/README.md b/example/clients/javascript/README.md new file mode 100644 index 0000000..bea4cb7 --- /dev/null +++ b/example/clients/javascript/README.md @@ -0,0 +1,142 @@ +# swagger-js-client + +SwaggerJsClient - JavaScript client for swagger-js-client +No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) +This SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: +- Package version: 1.0.0 +- Build package: io.swagger.codegen.languages.JavascriptClientCodegen + +## Installation + +### For [Node.js](https://nodejs.org/) + +#### npm + +To publish the library as a [npm](https://www.npmjs.com/), +please follow the procedure in ["Publishing npm packages"](https://docs.npmjs.com/getting-started/publishing-npm-packages). + +Then install it via: + +```shell +npm install swagger-js-client --save +``` + +##### Local development + +To use the library locally without publishing to a remote npm registry, first install the dependencies by changing +into the directory containing `package.json` (and this README). Let's call this `JAVASCRIPT_CLIENT_DIR`. Then run: + +```shell +npm install +``` + +Next, [link](https://docs.npmjs.com/cli/link) it globally in npm with the following, also from `JAVASCRIPT_CLIENT_DIR`: + +```shell +npm link +``` + +Finally, switch to the directory you want to use your swagger-js-client from, and run: + +```shell +npm link /path/to/ +``` + +You should now be able to `require('swagger-js-client')` in javascript files from the directory you ran the last +command above from. + +#### git +# +If the library is hosted at a git repository, e.g. +https://github.com/GIT_USER_ID/GIT_REPO_ID +then install it via: + +```shell + npm install GIT_USER_ID/GIT_REPO_ID --save +``` + +### For browser + +The library also works in the browser environment via npm and [browserify](http://browserify.org/). After following +the above steps with Node.js and installing browserify with `npm install -g browserify`, +perform the following (assuming *main.js* is your entry file, that's to say your javascript file where you actually +use this library): + +```shell +browserify main.js > bundle.js +``` + +Then include *bundle.js* in the HTML pages. + +### Webpack Configuration + +Using Webpack you may encounter the following error: "Module not found: Error: +Cannot resolve module", most certainly you should disable AMD loader. Add/merge +the following section to your webpack config: + +```javascript +module: { + rules: [ + { + parser: { + amd: false + } + } + ] +} +``` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following JS code: + +```javascript +var SwaggerJsClient = require('swagger-js-client'); + +var api = new SwaggerJsClient.GreetApi() + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +api.ping(callback); + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*SwaggerJsClient.GreetApi* | [**ping**](docs/GreetApi.md#ping) | **GET** /user/ping | +*SwaggerJsClient.UserApiApi* | [**getUserInfo**](docs/UserApiApi.md#getUserInfo) | **GET** /api/user/{id} | 获取用户信息 +*SwaggerJsClient.UserApiApi* | [**login**](docs/UserApiApi.md#login) | **POST** /api/user/login | 登录 +*SwaggerJsClient.UserApiApi* | [**register**](docs/UserApiApi.md#register) | **POST** /api/user/register | 注册 +*SwaggerJsClient.UserApiApi* | [**searchUser**](docs/UserApiApi.md#searchUser) | **GET** /api/user/search | 用户搜索 + + +## Documentation for Models + + - [SwaggerJsClient.LoginReq](docs/LoginReq.md) + - [SwaggerJsClient.RegisterReq](docs/RegisterReq.md) + - [SwaggerJsClient.UserInfoReply](docs/UserInfoReply.md) + - [SwaggerJsClient.UserInfoReq](docs/UserInfoReq.md) + - [SwaggerJsClient.UserSearchReply](docs/UserSearchReply.md) + - [SwaggerJsClient.UserSearchReq](docs/UserSearchReq.md) + + +## Documentation for Authorization + + +### apiKey + +- **Type**: API key +- **API key parameter name**: Authorization +- **Location**: HTTP header + diff --git a/example/clients/javascript/docs/GreetApi.md b/example/clients/javascript/docs/GreetApi.md new file mode 100644 index 0000000..342ff15 --- /dev/null +++ b/example/clients/javascript/docs/GreetApi.md @@ -0,0 +1,47 @@ +# SwaggerJsClient.GreetApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**ping**](GreetApi.md#ping) | **GET** /user/ping | + + + +# **ping** +> Object ping() + + + +### Example +```javascript +var SwaggerJsClient = require('swagger-js-client'); + +var apiInstance = new SwaggerJsClient.GreetApi(); + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.ping(callback); +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/example/clients/javascript/docs/LoginReq.md b/example/clients/javascript/docs/LoginReq.md new file mode 100644 index 0000000..0ed5a79 --- /dev/null +++ b/example/clients/javascript/docs/LoginReq.md @@ -0,0 +1,9 @@ +# SwaggerJsClient.LoginReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**username** | **String** | | [optional] +**password** | **String** | | [optional] + + diff --git a/example/clients/javascript/docs/RegisterReq.md b/example/clients/javascript/docs/RegisterReq.md new file mode 100644 index 0000000..f051e38 --- /dev/null +++ b/example/clients/javascript/docs/RegisterReq.md @@ -0,0 +1,10 @@ +# SwaggerJsClient.RegisterReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**username** | **String** | | [optional] +**password** | **String** | | [optional] +**mobile** | **String** | | [optional] + + diff --git a/example/clients/javascript/docs/UserApiApi.md b/example/clients/javascript/docs/UserApiApi.md new file mode 100644 index 0000000..ce07da5 --- /dev/null +++ b/example/clients/javascript/docs/UserApiApi.md @@ -0,0 +1,193 @@ +# SwaggerJsClient.UserApiApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**getUserInfo**](UserApiApi.md#getUserInfo) | **GET** /api/user/{id} | 获取用户信息 +[**login**](UserApiApi.md#login) | **POST** /api/user/login | 登录 +[**register**](UserApiApi.md#register) | **POST** /api/user/register | 注册 +[**searchUser**](UserApiApi.md#searchUser) | **GET** /api/user/search | 用户搜索 + + + +# **getUserInfo** +> UserInfoReply getUserInfo(id, body) + +获取用户信息 + +### Example +```javascript +var SwaggerJsClient = require('swagger-js-client'); + +var apiInstance = new SwaggerJsClient.UserApiApi(); + +var id = "id_example"; // String | + +var body = new SwaggerJsClient.UserInfoReq(); // UserInfoReq | + + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.getUserInfo(id, body, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **id** | **String**| | + **body** | [**UserInfoReq**](UserInfoReq.md)| | + +### Return type + +[**UserInfoReply**](UserInfoReply.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **login** +> Object login(body) + +登录 + +### Example +```javascript +var SwaggerJsClient = require('swagger-js-client'); + +var apiInstance = new SwaggerJsClient.UserApiApi(); + +var body = new SwaggerJsClient.LoginReq(); // LoginReq | + + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.login(body, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**LoginReq**](LoginReq.md)| | + +### Return type + +**Object** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **register** +> Object register(body) + +注册 + +注册一个用户 + +### Example +```javascript +var SwaggerJsClient = require('swagger-js-client'); + +var apiInstance = new SwaggerJsClient.UserApiApi(); + +var body = new SwaggerJsClient.RegisterReq(); // RegisterReq | + + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.register(body, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**RegisterReq**](RegisterReq.md)| | + +### Return type + +**Object** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **searchUser** +> UserSearchReply searchUser(body) + +用户搜索 + +### Example +```javascript +var SwaggerJsClient = require('swagger-js-client'); + +var apiInstance = new SwaggerJsClient.UserApiApi(); + +var body = new SwaggerJsClient.UserSearchReq(); // UserSearchReq | + + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.searchUser(body, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**UserSearchReq**](UserSearchReq.md)| | + +### Return type + +[**UserSearchReply**](UserSearchReply.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + diff --git a/example/clients/javascript/docs/UserInfoReply.md b/example/clients/javascript/docs/UserInfoReply.md new file mode 100644 index 0000000..0f56925 --- /dev/null +++ b/example/clients/javascript/docs/UserInfoReply.md @@ -0,0 +1,12 @@ +# SwaggerJsClient.UserInfoReply + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] +**age** | **Number** | | [optional] +**birthday** | **String** | | [optional] +**description** | **String** | | [optional] +**tag** | **[String]** | | [optional] + + diff --git a/example/clients/javascript/docs/UserInfoReq.md b/example/clients/javascript/docs/UserInfoReq.md new file mode 100644 index 0000000..9917b54 --- /dev/null +++ b/example/clients/javascript/docs/UserInfoReq.md @@ -0,0 +1,8 @@ +# SwaggerJsClient.UserInfoReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **String** | | [optional] + + diff --git a/example/clients/javascript/docs/UserSearchReply.md b/example/clients/javascript/docs/UserSearchReply.md new file mode 100644 index 0000000..9a75990 --- /dev/null +++ b/example/clients/javascript/docs/UserSearchReply.md @@ -0,0 +1,8 @@ +# SwaggerJsClient.UserSearchReply + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**keyWord** | [**[UserInfoReply]**](UserInfoReply.md) | | [optional] + + diff --git a/example/clients/javascript/docs/UserSearchReq.md b/example/clients/javascript/docs/UserSearchReq.md new file mode 100644 index 0000000..915b961 --- /dev/null +++ b/example/clients/javascript/docs/UserSearchReq.md @@ -0,0 +1,8 @@ +# SwaggerJsClient.UserSearchReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**keyWord** | **String** | | [optional] + + diff --git a/example/clients/javascript/git_push.sh b/example/clients/javascript/git_push.sh new file mode 100644 index 0000000..0d041ad --- /dev/null +++ b/example/clients/javascript/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the Git credential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/example/clients/javascript/mocha.opts b/example/clients/javascript/mocha.opts new file mode 100644 index 0000000..9070118 --- /dev/null +++ b/example/clients/javascript/mocha.opts @@ -0,0 +1 @@ +--timeout 10000 diff --git a/example/clients/javascript/package.json b/example/clients/javascript/package.json new file mode 100644 index 0000000..22be8c8 --- /dev/null +++ b/example/clients/javascript/package.json @@ -0,0 +1,22 @@ +{ + "name": "swagger-js-client", + "version": "1.0.0", + "description": "ERROR_UNKNOWN", + "license": "Unlicense", + "main": "src/index.js", + "scripts": { + "test": "mocha --recursive" + }, + "browser": { + "fs": false + }, + "dependencies": { + "superagent": "3.7.0", + "querystring": "0.2.0" + }, + "devDependencies": { + "mocha": "~2.3.4", + "sinon": "1.17.3", + "expect.js": "~0.3.1" + } +} diff --git a/example/clients/javascript/src/ApiClient.js b/example/clients/javascript/src/ApiClient.js new file mode 100644 index 0000000..c8e497d --- /dev/null +++ b/example/clients/javascript/src/ApiClient.js @@ -0,0 +1,600 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['superagent', 'querystring'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('superagent'), require('querystring')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.ApiClient = factory(root.superagent, root.querystring); + } +}(this, function(superagent, querystring) { + 'use strict'; + + /** + * @module ApiClient + * @version 1.0.0 + */ + + /** + * Manages low level client-server communications, parameter marshalling, etc. There should not be any need for an + * application to use this class directly - the *Api and model classes provide the public API for the service. The + * contents of this file should be regarded as internal but are documented for completeness. + * @alias module:ApiClient + * @class + */ + var exports = function() { + /** + * The base URL against which to resolve every API call's (relative) path. + * @type {String} + * @default http://localhost + */ + this.basePath = 'http://localhost'.replace(/\/+$/, ''); + + /** + * The authentication methods to be included for all API calls. + * @type {Array.} + */ + this.authentications = { + 'apiKey': {type: 'apiKey', 'in': 'header', name: 'Authorization'} + }; + /** + * The default HTTP headers to be included for all API calls. + * @type {Array.} + * @default {} + */ + this.defaultHeaders = {}; + + /** + * The default HTTP timeout for all API calls. + * @type {Number} + * @default 60000 + */ + this.timeout = 60000; + + /** + * If set to false an additional timestamp parameter is added to all API GET calls to + * prevent browser caching + * @type {Boolean} + * @default true + */ + this.cache = true; + + /** + * If set to true, the client will save the cookies from each server + * response, and return them in the next request. + * @default false + */ + this.enableCookies = false; + + /* + * Used to save and return cookies in a node.js (non-browser) setting, + * if this.enableCookies is set to true. + */ + if (typeof window === 'undefined') { + this.agent = new superagent.agent(); + } + + /* + * Allow user to override superagent agent + */ + this.requestAgent = null; + }; + + /** + * Returns a string representation for an actual parameter. + * @param param The actual parameter. + * @returns {String} The string representation of param. + */ + exports.prototype.paramToString = function(param) { + if (param == undefined || param == null) { + return ''; + } + if (param instanceof Date) { + return param.toISOString(); + } + return param.toString(); + }; + + /** + * Builds full URL by appending the given path to the base URL and replacing path parameter place-holders with parameter values. + * NOTE: query parameters are not handled here. + * @param {String} path The path to append to the base URL. + * @param {Object} pathParams The parameter values to append. + * @returns {String} The encoded path with parameter values substituted. + */ + exports.prototype.buildUrl = function(path, pathParams) { + if (!path.match(/^\//)) { + path = '/' + path; + } + var url = this.basePath + path; + var _this = this; + url = url.replace(/\{([\w-]+)\}/g, function(fullMatch, key) { + var value; + if (pathParams.hasOwnProperty(key)) { + value = _this.paramToString(pathParams[key]); + } else { + value = fullMatch; + } + return encodeURIComponent(value); + }); + return url; + }; + + /** + * Checks whether the given content type represents JSON.
+ * JSON content type examples:
+ *
    + *
  • application/json
  • + *
  • application/json; charset=UTF8
  • + *
  • APPLICATION/JSON
  • + *
+ * @param {String} contentType The MIME content type to check. + * @returns {Boolean} true if contentType represents JSON, otherwise false. + */ + exports.prototype.isJsonMime = function(contentType) { + return Boolean(contentType != null && contentType.match(/^application\/json(;.*)?$/i)); + }; + + /** + * Chooses a content type from the given array, with JSON preferred; i.e. return JSON if included, otherwise return the first. + * @param {Array.} contentTypes + * @returns {String} The chosen content type, preferring JSON. + */ + exports.prototype.jsonPreferredMime = function(contentTypes) { + for (var i = 0; i < contentTypes.length; i++) { + if (this.isJsonMime(contentTypes[i])) { + return contentTypes[i]; + } + } + return contentTypes[0]; + }; + + /** + * Checks whether the given parameter value represents file-like content. + * @param param The parameter to check. + * @returns {Boolean} true if param represents a file. + */ + exports.prototype.isFileParam = function(param) { + // fs.ReadStream in Node.js and Electron (but not in runtime like browserify) + if (typeof require === 'function') { + var fs; + try { + fs = require('fs'); + } catch (err) {} + if (fs && fs.ReadStream && param instanceof fs.ReadStream) { + return true; + } + } + // Buffer in Node.js + if (typeof Buffer === 'function' && param instanceof Buffer) { + return true; + } + // Blob in browser + if (typeof Blob === 'function' && param instanceof Blob) { + return true; + } + // File in browser (it seems File object is also instance of Blob, but keep this for safe) + if (typeof File === 'function' && param instanceof File) { + return true; + } + return false; + }; + + /** + * Normalizes parameter values: + *
    + *
  • remove nils
  • + *
  • keep files and arrays
  • + *
  • format to string with `paramToString` for other cases
  • + *
+ * @param {Object.} params The parameters as object properties. + * @returns {Object.} normalized parameters. + */ + exports.prototype.normalizeParams = function(params) { + var newParams = {}; + for (var key in params) { + if (params.hasOwnProperty(key) && params[key] != undefined && params[key] != null) { + var value = params[key]; + if (this.isFileParam(value) || Array.isArray(value)) { + newParams[key] = value; + } else { + newParams[key] = this.paramToString(value); + } + } + } + return newParams; + }; + + /** + * Enumeration of collection format separator strategies. + * @enum {String} + * @readonly + */ + exports.CollectionFormatEnum = { + /** + * Comma-separated values. Value: csv + * @const + */ + CSV: ',', + /** + * Space-separated values. Value: ssv + * @const + */ + SSV: ' ', + /** + * Tab-separated values. Value: tsv + * @const + */ + TSV: '\t', + /** + * Pipe(|)-separated values. Value: pipes + * @const + */ + PIPES: '|', + /** + * Native array. Value: multi + * @const + */ + MULTI: 'multi' + }; + + /** + * Builds a string representation of an array-type actual parameter, according to the given collection format. + * @param {Array} param An array parameter. + * @param {module:ApiClient.CollectionFormatEnum} collectionFormat The array element separator strategy. + * @returns {String|Array} A string representation of the supplied collection, using the specified delimiter. Returns + * param as is if collectionFormat is multi. + */ + exports.prototype.buildCollectionParam = function buildCollectionParam(param, collectionFormat) { + if (param == null) { + return null; + } + switch (collectionFormat) { + case 'csv': + return param.map(this.paramToString).join(','); + case 'ssv': + return param.map(this.paramToString).join(' '); + case 'tsv': + return param.map(this.paramToString).join('\t'); + case 'pipes': + return param.map(this.paramToString).join('|'); + case 'multi': + // return the array directly as SuperAgent will handle it as expected + return param.map(this.paramToString); + default: + throw new Error('Unknown collection format: ' + collectionFormat); + } + }; + + /** + * Applies authentication headers to the request. + * @param {Object} request The request object created by a superagent() call. + * @param {Array.} authNames An array of authentication method names. + */ + exports.prototype.applyAuthToRequest = function(request, authNames) { + var _this = this; + authNames.forEach(function(authName) { + var auth = _this.authentications[authName]; + switch (auth.type) { + case 'basic': + if (auth.username || auth.password) { + request.auth(auth.username || '', auth.password || ''); + } + break; + case 'apiKey': + if (auth.apiKey) { + var data = {}; + if (auth.apiKeyPrefix) { + data[auth.name] = auth.apiKeyPrefix + ' ' + auth.apiKey; + } else { + data[auth.name] = auth.apiKey; + } + if (auth['in'] === 'header') { + request.set(data); + } else { + request.query(data); + } + } + break; + case 'oauth2': + if (auth.accessToken) { + request.set({'Authorization': 'Bearer ' + auth.accessToken}); + } + break; + default: + throw new Error('Unknown authentication type: ' + auth.type); + } + }); + }; + + /** + * Deserializes an HTTP response body into a value of the specified type. + * @param {Object} response A SuperAgent response object. + * @param {(String|Array.|Object.|Function)} returnType The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns A value of the specified type. + */ + exports.prototype.deserialize = function deserialize(response, returnType) { + if (response == null || returnType == null || response.status == 204) { + return null; + } + // Rely on SuperAgent for parsing response body. + // See http://visionmedia.github.io/superagent/#parsing-response-bodies + var data = response.body; + if (data == null || (typeof data === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length)) { + // SuperAgent does not always produce a body; use the unparsed response as a fallback + data = response.text; + } + return exports.convertToType(data, returnType); + }; + + /** + * Callback function to receive the result of the operation. + * @callback module:ApiClient~callApiCallback + * @param {String} error Error message, if any. + * @param data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Invokes the REST service using the supplied settings and parameters. + * @param {String} path The base URL to invoke. + * @param {String} httpMethod The HTTP method to use. + * @param {Object.} pathParams A map of path parameters and their values. + * @param {Object.} queryParams A map of query parameters and their values. + * @param {Object.} collectionQueryParams A map of collection query parameters and their values. + * @param {Object.} headerParams A map of header parameters and their values. + * @param {Object.} formParams A map of form parameters and their values. + * @param {Object} bodyParam The value to pass as the request body. + * @param {Array.} authNames An array of authentication type names. + * @param {Array.} contentTypes An array of request MIME types. + * @param {Array.} accepts An array of acceptable response MIME types. + * @param {(String|Array|ObjectFunction)} returnType The required type to return; can be a string for simple types or the + * constructor for a complex type. + * @param {module:ApiClient~callApiCallback} callback The callback function. + * @returns {Object} The SuperAgent request object. + */ + exports.prototype.callApi = function callApi(path, httpMethod, pathParams, + queryParams, collectionQueryParams, headerParams, formParams, bodyParam, authNames, contentTypes, accepts, + returnType, callback) { + + var _this = this; + var url = this.buildUrl(path, pathParams); + var request = superagent(httpMethod, url); + + // apply authentications + this.applyAuthToRequest(request, authNames); + + // set collection query parameters + for (var key in collectionQueryParams) { + if (collectionQueryParams.hasOwnProperty(key)) { + var param = collectionQueryParams[key]; + if (param.collectionFormat === 'csv') { + // SuperAgent normally percent-encodes all reserved characters in a query parameter. However, + // commas are used as delimiters for the 'csv' collectionFormat so they must not be encoded. We + // must therefore construct and encode 'csv' collection query parameters manually. + if (param.value != null) { + var value = param.value.map(this.paramToString).map(encodeURIComponent).join(','); + request.query(encodeURIComponent(key) + "=" + value); + } + } else { + // All other collection query parameters should be treated as ordinary query parameters. + queryParams[key] = this.buildCollectionParam(param.value, param.collectionFormat); + } + } + } + + // set query parameters + if (httpMethod.toUpperCase() === 'GET' && this.cache === false) { + queryParams['_'] = new Date().getTime(); + } + request.query(this.normalizeParams(queryParams)); + + // set header parameters + request.set(this.defaultHeaders).set(this.normalizeParams(headerParams)); + + + // set requestAgent if it is set by user + if (this.requestAgent) { + request.agent(this.requestAgent); + } + + // set request timeout + request.timeout(this.timeout); + + var contentType = this.jsonPreferredMime(contentTypes); + if (contentType) { + // Issue with superagent and multipart/form-data (https://github.com/visionmedia/superagent/issues/746) + if(contentType != 'multipart/form-data') { + request.type(contentType); + } + } else if (!request.header['Content-Type']) { + request.type('application/json'); + } + + if (contentType === 'application/x-www-form-urlencoded') { + request.send(querystring.stringify(this.normalizeParams(formParams))); + } else if (contentType == 'multipart/form-data') { + var _formParams = this.normalizeParams(formParams); + for (var key in _formParams) { + if (_formParams.hasOwnProperty(key)) { + if (this.isFileParam(_formParams[key])) { + // file field + request.attach(key, _formParams[key]); + } else { + request.field(key, _formParams[key]); + } + } + } + } else if (bodyParam) { + request.send(bodyParam); + } + + var accept = this.jsonPreferredMime(accepts); + if (accept) { + request.accept(accept); + } + + if (returnType === 'Blob') { + request.responseType('blob'); + } else if (returnType === 'String') { + request.responseType('string'); + } + + // Attach previously saved cookies, if enabled + if (this.enableCookies){ + if (typeof window === 'undefined') { + this.agent.attachCookies(request); + } + else { + request.withCredentials(); + } + } + + + request.end(function(error, response) { + if (callback) { + var data = null; + if (!error) { + try { + data = _this.deserialize(response, returnType); + if (_this.enableCookies && typeof window === 'undefined'){ + _this.agent.saveCookies(response); + } + } catch (err) { + error = err; + } + } + callback(error, data, response); + } + }); + + return request; + }; + + /** + * Parses a string representation of a date value. + * @param {String} str The date value as an ISO-8601 full-date or date-time string. + * @returns {Date} The parsed date object. + */ + exports.parseDate = function(str) { + // OpenAPI 2.0 & 3.0 specs state that: + // - date values are serialized as ISO-8601 full-date strings. + // - date-time values are serialized as ISO-8601 date-time strings, in which the timezone offset is mandatory. + return new Date(str); + }; + + /** + * Converts a value to the specified type. + * @param {(String|Object)} data The data to convert, as a string or object. + * @param {(String|Array.|Object.|Function)} type The type to return. Pass a string for simple types + * or the constructor function for a complex type. Pass an array containing the type name to return an array of that type. To + * return an object, pass an object with one property whose name is the key type and whose value is the corresponding value type: + * all properties on data will be converted to this type. + * @returns An instance of the specified type or null or undefined if data is null or undefined. + */ + exports.convertToType = function(data, type) { + if (data === null || data === undefined) + return data + + switch (type) { + case 'Boolean': + return Boolean(data); + case 'Integer': + return parseInt(data, 10); + case 'Number': + return parseFloat(data); + case 'String': + return String(data); + case 'Date': + return this.parseDate(String(data)); + case 'Blob': + return data; + default: + if (type === Object) { + // generic object, return directly + return data; + } else if (typeof type === 'function') { + // for model type like: User + return type.constructFromObject(data); + } else if (Array.isArray(type)) { + // for array type like: ['String'] + var itemType = type[0]; + return data.map(function(item) { + return exports.convertToType(item, itemType); + }); + } else if (typeof type === 'object') { + // for plain object type like: {'String': 'Integer'} + var keyType, valueType; + for (var k in type) { + if (type.hasOwnProperty(k)) { + keyType = k; + valueType = type[k]; + break; + } + } + var result = {}; + for (var k in data) { + if (data.hasOwnProperty(k)) { + var key = exports.convertToType(k, keyType); + var value = exports.convertToType(data[k], valueType); + result[key] = value; + } + } + return result; + } else { + // for unknown type, return the data directly + return data; + } + } + }; + + /** + * Constructs a new map or array model from REST data. + * @param data {Object|Array} The REST data. + * @param obj {Object|Array} The target object or array. + */ + exports.constructFromObject = function(data, obj, itemType) { + if (Array.isArray(data)) { + for (var i = 0; i < data.length; i++) { + if (data.hasOwnProperty(i)) + obj[i] = exports.convertToType(data[i], itemType); + } + } else { + for (var k in data) { + if (data.hasOwnProperty(k)) + obj[k] = exports.convertToType(data[k], itemType); + } + } + }; + + /** + * The default API client implementation. + * @type {module:ApiClient} + */ + exports.instance = new exports(); + + return exports; +})); diff --git a/example/clients/javascript/src/api/GreetApi.js b/example/clients/javascript/src/api/GreetApi.js new file mode 100644 index 0000000..0a8bced --- /dev/null +++ b/example/clients/javascript/src/api/GreetApi.js @@ -0,0 +1,91 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.GreetApi = factory(root.SwaggerJsClient.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * Greet service. + * @module api/GreetApi + * @version 1.0.0 + */ + + /** + * Constructs a new GreetApi. + * @alias module:api/GreetApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instance} if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + + + /** + * Callback function to receive the result of the ping operation. + * @callback module:api/GreetApi~pingCallback + * @param {String} error Error message, if any. + * @param {Object} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * @param {module:api/GreetApi~pingCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link Object} + */ + this.ping = function(callback) { + var postBody = null; + + + var pathParams = { + }; + var queryParams = { + }; + var collectionQueryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = ['application/json']; + var accepts = ['application/json']; + var returnType = Object; + + return this.apiClient.callApi( + '/user/ping', 'GET', + pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + }; + + return exports; +})); diff --git a/example/clients/javascript/src/api/UserApiApi.js b/example/clients/javascript/src/api/UserApiApi.js new file mode 100644 index 0000000..817362c --- /dev/null +++ b/example/clients/javascript/src/api/UserApiApi.js @@ -0,0 +1,244 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/LoginReq', 'model/RegisterReq', 'model/UserInfoReply', 'model/UserInfoReq', 'model/UserSearchReply', 'model/UserSearchReq'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('../model/LoginReq'), require('../model/RegisterReq'), require('../model/UserInfoReply'), require('../model/UserInfoReq'), require('../model/UserSearchReply'), require('../model/UserSearchReq')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.UserApiApi = factory(root.SwaggerJsClient.ApiClient, root.SwaggerJsClient.LoginReq, root.SwaggerJsClient.RegisterReq, root.SwaggerJsClient.UserInfoReply, root.SwaggerJsClient.UserInfoReq, root.SwaggerJsClient.UserSearchReply, root.SwaggerJsClient.UserSearchReq); + } +}(this, function(ApiClient, LoginReq, RegisterReq, UserInfoReply, UserInfoReq, UserSearchReply, UserSearchReq) { + 'use strict'; + + /** + * UserApi service. + * @module api/UserApiApi + * @version 1.0.0 + */ + + /** + * Constructs a new UserApiApi. + * @alias module:api/UserApiApi + * @class + * @param {module:ApiClient} [apiClient] Optional API client implementation to use, + * default to {@link module:ApiClient#instance} if unspecified. + */ + var exports = function(apiClient) { + this.apiClient = apiClient || ApiClient.instance; + + + /** + * Callback function to receive the result of the getUserInfo operation. + * @callback module:api/UserApiApi~getUserInfoCallback + * @param {String} error Error message, if any. + * @param {module:model/UserInfoReply} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * 获取用户信息 + * @param {String} id + * @param {module:model/UserInfoReq} body + * @param {module:api/UserApiApi~getUserInfoCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/UserInfoReply} + */ + this.getUserInfo = function(id, body, callback) { + var postBody = body; + + // verify the required parameter 'id' is set + if (id === undefined || id === null) { + throw new Error("Missing the required parameter 'id' when calling getUserInfo"); + } + + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling getUserInfo"); + } + + + var pathParams = { + 'id': id + }; + var queryParams = { + }; + var collectionQueryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = ['application/json']; + var accepts = ['application/json']; + var returnType = UserInfoReply; + + return this.apiClient.callApi( + '/api/user/{id}', 'GET', + pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the login operation. + * @callback module:api/UserApiApi~loginCallback + * @param {String} error Error message, if any. + * @param {Object} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * 登录 + * @param {module:model/LoginReq} body + * @param {module:api/UserApiApi~loginCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link Object} + */ + this.login = function(body, callback) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling login"); + } + + + var pathParams = { + }; + var queryParams = { + }; + var collectionQueryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = ['application/json']; + var accepts = ['application/json']; + var returnType = Object; + + return this.apiClient.callApi( + '/api/user/login', 'POST', + pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the register operation. + * @callback module:api/UserApiApi~registerCallback + * @param {String} error Error message, if any. + * @param {Object} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * 注册 + * 注册一个用户 + * @param {module:model/RegisterReq} body + * @param {module:api/UserApiApi~registerCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link Object} + */ + this.register = function(body, callback) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling register"); + } + + + var pathParams = { + }; + var queryParams = { + }; + var collectionQueryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = ['application/json']; + var accepts = ['application/json']; + var returnType = Object; + + return this.apiClient.callApi( + '/api/user/register', 'POST', + pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + + /** + * Callback function to receive the result of the searchUser operation. + * @callback module:api/UserApiApi~searchUserCallback + * @param {String} error Error message, if any. + * @param {module:model/UserSearchReply} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * 用户搜索 + * @param {module:model/UserSearchReq} body + * @param {module:api/UserApiApi~searchUserCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/UserSearchReply} + */ + this.searchUser = function(body, callback) { + var postBody = body; + + // verify the required parameter 'body' is set + if (body === undefined || body === null) { + throw new Error("Missing the required parameter 'body' when calling searchUser"); + } + + + var pathParams = { + }; + var queryParams = { + }; + var collectionQueryParams = { + }; + var headerParams = { + }; + var formParams = { + }; + + var authNames = []; + var contentTypes = ['application/json']; + var accepts = ['application/json']; + var returnType = UserSearchReply; + + return this.apiClient.callApi( + '/api/user/search', 'GET', + pathParams, queryParams, collectionQueryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, callback + ); + } + }; + + return exports; +})); diff --git a/example/clients/javascript/src/index.js b/example/clients/javascript/src/index.js new file mode 100644 index 0000000..7e94c29 --- /dev/null +++ b/example/clients/javascript/src/index.js @@ -0,0 +1,107 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/LoginReq', 'model/RegisterReq', 'model/UserInfoReply', 'model/UserInfoReq', 'model/UserSearchReply', 'model/UserSearchReq', 'api/GreetApi', 'api/UserApiApi'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('./ApiClient'), require('./model/LoginReq'), require('./model/RegisterReq'), require('./model/UserInfoReply'), require('./model/UserInfoReq'), require('./model/UserSearchReply'), require('./model/UserSearchReq'), require('./api/GreetApi'), require('./api/UserApiApi')); + } +}(function(ApiClient, LoginReq, RegisterReq, UserInfoReply, UserInfoReq, UserSearchReply, UserSearchReq, GreetApi, UserApiApi) { + 'use strict'; + + /** + * ERROR_UNKNOWN.
+ * The index module provides access to constructors for all the classes which comprise the public API. + *

+ * An AMD (recommended!) or CommonJS application will generally do something equivalent to the following: + *

+   * var SwaggerJsClient = require('index'); // See note below*.
+   * var xxxSvc = new SwaggerJsClient.XxxApi(); // Allocate the API class we're going to use.
+   * var yyyModel = new SwaggerJsClient.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ * *NOTE: For a top-level AMD script, use require(['index'], function(){...}) + * and put the application logic within the callback function. + *

+ *

+ * A non-AMD browser application (discouraged) might do something like this: + *

+   * var xxxSvc = new SwaggerJsClient.XxxApi(); // Allocate the API class we're going to use.
+   * var yyy = new SwaggerJsClient.Yyy(); // Construct a model instance.
+   * yyyModel.someProperty = 'someValue';
+   * ...
+   * var zzz = xxxSvc.doSomething(yyyModel); // Invoke the service.
+   * ...
+   * 
+ *

+ * @module index + * @version 1.0.0 + */ + var exports = { + /** + * The ApiClient constructor. + * @property {module:ApiClient} + */ + ApiClient: ApiClient, + /** + * The LoginReq model constructor. + * @property {module:model/LoginReq} + */ + LoginReq: LoginReq, + /** + * The RegisterReq model constructor. + * @property {module:model/RegisterReq} + */ + RegisterReq: RegisterReq, + /** + * The UserInfoReply model constructor. + * @property {module:model/UserInfoReply} + */ + UserInfoReply: UserInfoReply, + /** + * The UserInfoReq model constructor. + * @property {module:model/UserInfoReq} + */ + UserInfoReq: UserInfoReq, + /** + * The UserSearchReply model constructor. + * @property {module:model/UserSearchReply} + */ + UserSearchReply: UserSearchReply, + /** + * The UserSearchReq model constructor. + * @property {module:model/UserSearchReq} + */ + UserSearchReq: UserSearchReq, + /** + * The GreetApi service constructor. + * @property {module:api/GreetApi} + */ + GreetApi: GreetApi, + /** + * The UserApiApi service constructor. + * @property {module:api/UserApiApi} + */ + UserApiApi: UserApiApi + }; + + return exports; +})); diff --git a/example/clients/javascript/src/model/LoginReq.js b/example/clients/javascript/src/model/LoginReq.js new file mode 100644 index 0000000..5161206 --- /dev/null +++ b/example/clients/javascript/src/model/LoginReq.js @@ -0,0 +1,78 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.LoginReq = factory(root.SwaggerJsClient.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The LoginReq model module. + * @module model/LoginReq + * @version 1.0.0 + */ + + /** + * Constructs a new LoginReq. + * @alias module:model/LoginReq + * @class + */ + var exports = function() { + }; + + /** + * Constructs a LoginReq from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/LoginReq} obj Optional instance to populate. + * @return {module:model/LoginReq} The populated LoginReq instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + if (data.hasOwnProperty('username')) + obj.username = ApiClient.convertToType(data['username'], 'String'); + if (data.hasOwnProperty('password')) + obj.password = ApiClient.convertToType(data['password'], 'String'); + } + return obj; + } + + /** + * @member {String} username + */ + exports.prototype.username = undefined; + + /** + * @member {String} password + */ + exports.prototype.password = undefined; + + + return exports; + +})); diff --git a/example/clients/javascript/src/model/RegisterReq.js b/example/clients/javascript/src/model/RegisterReq.js new file mode 100644 index 0000000..ba1bd1f --- /dev/null +++ b/example/clients/javascript/src/model/RegisterReq.js @@ -0,0 +1,85 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.RegisterReq = factory(root.SwaggerJsClient.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The RegisterReq model module. + * @module model/RegisterReq + * @version 1.0.0 + */ + + /** + * Constructs a new RegisterReq. + * @alias module:model/RegisterReq + * @class + */ + var exports = function() { + }; + + /** + * Constructs a RegisterReq from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/RegisterReq} obj Optional instance to populate. + * @return {module:model/RegisterReq} The populated RegisterReq instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + if (data.hasOwnProperty('username')) + obj.username = ApiClient.convertToType(data['username'], 'String'); + if (data.hasOwnProperty('password')) + obj.password = ApiClient.convertToType(data['password'], 'String'); + if (data.hasOwnProperty('mobile')) + obj.mobile = ApiClient.convertToType(data['mobile'], 'String'); + } + return obj; + } + + /** + * @member {String} username + */ + exports.prototype.username = undefined; + + /** + * @member {String} password + */ + exports.prototype.password = undefined; + + /** + * @member {String} mobile + */ + exports.prototype.mobile = undefined; + + + return exports; + +})); diff --git a/example/clients/javascript/src/model/UserInfoReply.js b/example/clients/javascript/src/model/UserInfoReply.js new file mode 100644 index 0000000..173a55a --- /dev/null +++ b/example/clients/javascript/src/model/UserInfoReply.js @@ -0,0 +1,99 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.UserInfoReply = factory(root.SwaggerJsClient.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The UserInfoReply model module. + * @module model/UserInfoReply + * @version 1.0.0 + */ + + /** + * Constructs a new UserInfoReply. + * @alias module:model/UserInfoReply + * @class + */ + var exports = function() { + }; + + /** + * Constructs a UserInfoReply from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/UserInfoReply} obj Optional instance to populate. + * @return {module:model/UserInfoReply} The populated UserInfoReply instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + if (data.hasOwnProperty('name')) + obj.name = ApiClient.convertToType(data['name'], 'String'); + if (data.hasOwnProperty('age')) + obj.age = ApiClient.convertToType(data['age'], 'Number'); + if (data.hasOwnProperty('birthday')) + obj.birthday = ApiClient.convertToType(data['birthday'], 'String'); + if (data.hasOwnProperty('description')) + obj.description = ApiClient.convertToType(data['description'], 'String'); + if (data.hasOwnProperty('tag')) + obj.tag = ApiClient.convertToType(data['tag'], ['String']); + } + return obj; + } + + /** + * @member {String} name + */ + exports.prototype.name = undefined; + + /** + * @member {Number} age + */ + exports.prototype.age = undefined; + + /** + * @member {String} birthday + */ + exports.prototype.birthday = undefined; + + /** + * @member {String} description + */ + exports.prototype.description = undefined; + + /** + * @member {Array.} tag + */ + exports.prototype.tag = undefined; + + + return exports; + +})); diff --git a/example/clients/javascript/src/model/UserInfoReq.js b/example/clients/javascript/src/model/UserInfoReq.js new file mode 100644 index 0000000..987ea6e --- /dev/null +++ b/example/clients/javascript/src/model/UserInfoReq.js @@ -0,0 +1,71 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.UserInfoReq = factory(root.SwaggerJsClient.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The UserInfoReq model module. + * @module model/UserInfoReq + * @version 1.0.0 + */ + + /** + * Constructs a new UserInfoReq. + * @alias module:model/UserInfoReq + * @class + */ + var exports = function() { + }; + + /** + * Constructs a UserInfoReq from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/UserInfoReq} obj Optional instance to populate. + * @return {module:model/UserInfoReq} The populated UserInfoReq instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + if (data.hasOwnProperty('id')) + obj.id = ApiClient.convertToType(data['id'], 'String'); + } + return obj; + } + + /** + * @member {String} id + */ + exports.prototype.id = undefined; + + + return exports; + +})); diff --git a/example/clients/javascript/src/model/UserSearchReply.js b/example/clients/javascript/src/model/UserSearchReply.js new file mode 100644 index 0000000..0b2e50e --- /dev/null +++ b/example/clients/javascript/src/model/UserSearchReply.js @@ -0,0 +1,71 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/UserInfoReply'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient'), require('./UserInfoReply')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.UserSearchReply = factory(root.SwaggerJsClient.ApiClient, root.SwaggerJsClient.UserInfoReply); + } +}(this, function(ApiClient, UserInfoReply) { + 'use strict'; + + /** + * The UserSearchReply model module. + * @module model/UserSearchReply + * @version 1.0.0 + */ + + /** + * Constructs a new UserSearchReply. + * @alias module:model/UserSearchReply + * @class + */ + var exports = function() { + }; + + /** + * Constructs a UserSearchReply from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/UserSearchReply} obj Optional instance to populate. + * @return {module:model/UserSearchReply} The populated UserSearchReply instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + if (data.hasOwnProperty('KeyWord')) + obj.keyWord = ApiClient.convertToType(data['KeyWord'], [UserInfoReply]); + } + return obj; + } + + /** + * @member {Array.} keyWord + */ + exports.prototype.keyWord = undefined; + + + return exports; + +})); diff --git a/example/clients/javascript/src/model/UserSearchReq.js b/example/clients/javascript/src/model/UserSearchReq.js new file mode 100644 index 0000000..510ab1d --- /dev/null +++ b/example/clients/javascript/src/model/UserSearchReq.js @@ -0,0 +1,71 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerJsClient) { + root.SwaggerJsClient = {}; + } + root.SwaggerJsClient.UserSearchReq = factory(root.SwaggerJsClient.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The UserSearchReq model module. + * @module model/UserSearchReq + * @version 1.0.0 + */ + + /** + * Constructs a new UserSearchReq. + * @alias module:model/UserSearchReq + * @class + */ + var exports = function() { + }; + + /** + * Constructs a UserSearchReq from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/UserSearchReq} obj Optional instance to populate. + * @return {module:model/UserSearchReq} The populated UserSearchReq instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + if (data.hasOwnProperty('keyWord')) + obj.keyWord = ApiClient.convertToType(data['keyWord'], 'String'); + } + return obj; + } + + /** + * @member {String} keyWord + */ + exports.prototype.keyWord = undefined; + + + return exports; + +})); diff --git a/example/clients/javascript/test/api/GreetApi.spec.js b/example/clients/javascript/test/api/GreetApi.spec.js new file mode 100644 index 0000000..6f84c39 --- /dev/null +++ b/example/clients/javascript/test/api/GreetApi.spec.js @@ -0,0 +1,62 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerJsClient.GreetApi(); + }); + + describe('(package)', function() { + describe('GreetApi', function() { + describe('ping', function() { + it('should call ping successfully', function(done) { + // TODO: uncomment ping call and complete the assertions + /* + + instance.ping(function(error, data, response) { + if (error) { + done(error); + return; + } + // TODO: update response assertions + expect(data).to.be.a(Object); + // expect(data).to.be(null); + + done(); + }); + */ + // TODO: uncomment and complete method invocation above, then delete this line and the next: + done(); + }); + }); + }); + }); + +})); diff --git a/example/clients/javascript/test/api/UserApiApi.spec.js b/example/clients/javascript/test/api/UserApiApi.spec.js new file mode 100644 index 0000000..460361e --- /dev/null +++ b/example/clients/javascript/test/api/UserApiApi.spec.js @@ -0,0 +1,181 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerJsClient.UserApiApi(); + }); + + describe('(package)', function() { + describe('UserApiApi', function() { + describe('getUserInfo', function() { + it('should call getUserInfo successfully', function(done) { + // TODO: uncomment, update parameter values for getUserInfo call and complete the assertions + /* + var id = "id_example"; + var body = new SwaggerJsClient.UserInfoReq(); + body.id = ""; + + instance.getUserInfo(id, body, function(error, data, response) { + if (error) { + done(error); + return; + } + // TODO: update response assertions + expect(data).to.be.a(SwaggerJsClient.UserInfoReply); + expect(data.name).to.be.a('string'); + expect(data.name).to.be(""); + expect(data.age).to.be.a('number'); + expect(data.age).to.be(0); + expect(data.birthday).to.be.a('string'); + expect(data.birthday).to.be(""); + expect(data.description).to.be.a('string'); + expect(data.description).to.be(""); + { + let dataCtr = data.tag; + expect(dataCtr).to.be.an(Array); + expect(dataCtr).to.not.be.empty(); + for (let p in dataCtr) { + let data = dataCtr[p]; + expect(data).to.be.a('string'); + expect(data).to.be(""); + } + } + + done(); + }); + */ + // TODO: uncomment and complete method invocation above, then delete this line and the next: + done(); + }); + }); + describe('login', function() { + it('should call login successfully', function(done) { + // TODO: uncomment, update parameter values for login call and complete the assertions + /* + var body = new SwaggerJsClient.LoginReq(); + body.username = ""; + body.password = ""; + + instance.login(body, function(error, data, response) { + if (error) { + done(error); + return; + } + // TODO: update response assertions + expect(data).to.be.a(Object); + // expect(data).to.be(null); + + done(); + }); + */ + // TODO: uncomment and complete method invocation above, then delete this line and the next: + done(); + }); + }); + describe('register', function() { + it('should call register successfully', function(done) { + // TODO: uncomment, update parameter values for register call and complete the assertions + /* + var body = new SwaggerJsClient.RegisterReq(); + body.username = ""; + body.password = ""; + body.mobile = ""; + + instance.register(body, function(error, data, response) { + if (error) { + done(error); + return; + } + // TODO: update response assertions + expect(data).to.be.a(Object); + // expect(data).to.be(null); + + done(); + }); + */ + // TODO: uncomment and complete method invocation above, then delete this line and the next: + done(); + }); + }); + describe('searchUser', function() { + it('should call searchUser successfully', function(done) { + // TODO: uncomment, update parameter values for searchUser call and complete the assertions + /* + var body = new SwaggerJsClient.UserSearchReq(); + body.keyWord = ""; + + instance.searchUser(body, function(error, data, response) { + if (error) { + done(error); + return; + } + // TODO: update response assertions + expect(data).to.be.a(SwaggerJsClient.UserSearchReply); + { + let dataCtr = data.keyWord; + expect(dataCtr).to.be.an(Array); + expect(dataCtr).to.not.be.empty(); + for (let p in dataCtr) { + let data = dataCtr[p]; + expect(data).to.be.a(SwaggerJsClient.UserInfoReply); + expect(data.name).to.be.a('string'); + expect(data.name).to.be(""); + expect(data.age).to.be.a('number'); + expect(data.age).to.be(0); + expect(data.birthday).to.be.a('string'); + expect(data.birthday).to.be(""); + expect(data.description).to.be.a('string'); + expect(data.description).to.be(""); + { + let dataCtr = data.tag; + expect(dataCtr).to.be.an(Array); + expect(dataCtr).to.not.be.empty(); + for (let p in dataCtr) { + let data = dataCtr[p]; + expect(data).to.be.a('string'); + expect(data).to.be(""); + } + } + + } + } + + done(); + }); + */ + // TODO: uncomment and complete method invocation above, then delete this line and the next: + done(); + }); + }); + }); + }); + +})); diff --git a/example/clients/javascript/test/assert-equals.js b/example/clients/javascript/test/assert-equals.js new file mode 100644 index 0000000..b95cd5f --- /dev/null +++ b/example/clients/javascript/test/assert-equals.js @@ -0,0 +1,81 @@ +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(); + } else { + // Browser globals (root is window) + root.assertEquals = factory(); + } +}(this, function() { + 'use strict'; + + var assertEquals = function(expected, actual, ptr) { + if (!ptr) + ptr = ""; + if (actual === expected) + return; + if (expected instanceof Date || actual instanceof Date) { + expected = toISODateString(expected); + actual = toISODateString(actual); + if (actual !== expected) + fail(expected, actual, ptr, "date value incorrect;"); + } + if (!expected || !actual || typeof expected != 'object' && typeof actual != 'object') { + if (typeof actual != typeof expected) + fail(typeof expected, typeof actual, ptr, "value type incorrect;"); + if (actual != expected) + fail(expected, actual, ptr, "value incorrect;"); + } + return checkObject(expected, actual, ptr); + } + + function toISODateString(value) { + if (value instanceof Date) { + // JavaScript's ISO string contains a milliseconds component that must be stripped out. + value = value.toISOString().replace('.000', ''); + } + return value; + } + + function checkObject(expected, actual, ptr) { + if (undefOrNull(expected) || undefOrNull(actual)) + fail(expected, actual, ptr, "missing value;"); + if (typeof expected !== typeof actual) + fail(typeof expected, typeof actual, ptr, "wrong type;"); + if (expected.prototype !== actual.prototype) + fail(expected.prototype, actual.prototype, ptr, "wrong prototype;"); + try { + var expectedKeys = Object.keys(expected); + var actualKeys = Object.keys(actual); + } catch (e) { + fail(expectedKeys, actualKeys, ptr, "wrong keys;"); + } + if (actualKeys.length != expectedKeys.length) + fail(expectedKeys.length, actualKeys.length, ptr, "key count incorrect;"); + expectedKeys.sort(); + actualKeys.sort(); + for (var i = 0; i < expectedKeys.length; i++) { + if (actualKeys[i] != expectedKeys[i]) + fail(expectedKeys, actualKeys, ptr, "wrong keys;"); + } + for (i = 0; i < expectedKeys.length; i++) { + var key = expectedKeys[i]; + assertEquals(expected[key], actual[key], ptr + '/' + key); + } + } + + function undefOrNull(v) { + return v === undefined || v === null; + } + + function fail(expected, actual, ptr, msg) { + var text = ptr + ' ' + msg + " expected: " + expected + ", actual: " + actual; + console.log(text); + throw new Error(text); + } + + return assertEquals; +})); diff --git a/example/clients/javascript/test/model/LoginReq.spec.js b/example/clients/javascript/test/model/LoginReq.spec.js new file mode 100644 index 0000000..b661e4c --- /dev/null +++ b/example/clients/javascript/test/model/LoginReq.spec.js @@ -0,0 +1,58 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + describe('(package)', function() { + describe('LoginReq', function() { + beforeEach(function() { + instance = new SwaggerJsClient.LoginReq(); + }); + + it('should create an instance of LoginReq', function() { + // TODO: update the code to test LoginReq + expect(instance).to.be.a(SwaggerJsClient.LoginReq); + }); + + it('should have the property username (base name: "username")', function() { + // TODO: update the code to test the property username + expect(instance).to.have.property('username'); + // expect(instance.username).to.be(expectedValueLiteral); + }); + + it('should have the property password (base name: "password")', function() { + // TODO: update the code to test the property password + expect(instance).to.have.property('password'); + // expect(instance.password).to.be(expectedValueLiteral); + }); + + }); + }); + +})); diff --git a/example/clients/javascript/test/model/RegisterReq.spec.js b/example/clients/javascript/test/model/RegisterReq.spec.js new file mode 100644 index 0000000..56a77e1 --- /dev/null +++ b/example/clients/javascript/test/model/RegisterReq.spec.js @@ -0,0 +1,64 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + describe('(package)', function() { + describe('RegisterReq', function() { + beforeEach(function() { + instance = new SwaggerJsClient.RegisterReq(); + }); + + it('should create an instance of RegisterReq', function() { + // TODO: update the code to test RegisterReq + expect(instance).to.be.a(SwaggerJsClient.RegisterReq); + }); + + it('should have the property username (base name: "username")', function() { + // TODO: update the code to test the property username + expect(instance).to.have.property('username'); + // expect(instance.username).to.be(expectedValueLiteral); + }); + + it('should have the property password (base name: "password")', function() { + // TODO: update the code to test the property password + expect(instance).to.have.property('password'); + // expect(instance.password).to.be(expectedValueLiteral); + }); + + it('should have the property mobile (base name: "mobile")', function() { + // TODO: update the code to test the property mobile + expect(instance).to.have.property('mobile'); + // expect(instance.mobile).to.be(expectedValueLiteral); + }); + + }); + }); + +})); diff --git a/example/clients/javascript/test/model/UserInfoReply.spec.js b/example/clients/javascript/test/model/UserInfoReply.spec.js new file mode 100644 index 0000000..f91401a --- /dev/null +++ b/example/clients/javascript/test/model/UserInfoReply.spec.js @@ -0,0 +1,76 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + describe('(package)', function() { + describe('UserInfoReply', function() { + beforeEach(function() { + instance = new SwaggerJsClient.UserInfoReply(); + }); + + it('should create an instance of UserInfoReply', function() { + // TODO: update the code to test UserInfoReply + expect(instance).to.be.a(SwaggerJsClient.UserInfoReply); + }); + + it('should have the property name (base name: "name")', function() { + // TODO: update the code to test the property name + expect(instance).to.have.property('name'); + // expect(instance.name).to.be(expectedValueLiteral); + }); + + it('should have the property age (base name: "age")', function() { + // TODO: update the code to test the property age + expect(instance).to.have.property('age'); + // expect(instance.age).to.be(expectedValueLiteral); + }); + + it('should have the property birthday (base name: "birthday")', function() { + // TODO: update the code to test the property birthday + expect(instance).to.have.property('birthday'); + // expect(instance.birthday).to.be(expectedValueLiteral); + }); + + it('should have the property description (base name: "description")', function() { + // TODO: update the code to test the property description + expect(instance).to.have.property('description'); + // expect(instance.description).to.be(expectedValueLiteral); + }); + + it('should have the property tag (base name: "tag")', function() { + // TODO: update the code to test the property tag + expect(instance).to.have.property('tag'); + // expect(instance.tag).to.be(expectedValueLiteral); + }); + + }); + }); + +})); diff --git a/example/clients/javascript/test/model/UserInfoReq.spec.js b/example/clients/javascript/test/model/UserInfoReq.spec.js new file mode 100644 index 0000000..f7328ae --- /dev/null +++ b/example/clients/javascript/test/model/UserInfoReq.spec.js @@ -0,0 +1,52 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + describe('(package)', function() { + describe('UserInfoReq', function() { + beforeEach(function() { + instance = new SwaggerJsClient.UserInfoReq(); + }); + + it('should create an instance of UserInfoReq', function() { + // TODO: update the code to test UserInfoReq + expect(instance).to.be.a(SwaggerJsClient.UserInfoReq); + }); + + it('should have the property id (base name: "id")', function() { + // TODO: update the code to test the property id + expect(instance).to.have.property('id'); + // expect(instance.id).to.be(expectedValueLiteral); + }); + + }); + }); + +})); diff --git a/example/clients/javascript/test/model/UserSearchReply.spec.js b/example/clients/javascript/test/model/UserSearchReply.spec.js new file mode 100644 index 0000000..2b7eca7 --- /dev/null +++ b/example/clients/javascript/test/model/UserSearchReply.spec.js @@ -0,0 +1,52 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + describe('(package)', function() { + describe('UserSearchReply', function() { + beforeEach(function() { + instance = new SwaggerJsClient.UserSearchReply(); + }); + + it('should create an instance of UserSearchReply', function() { + // TODO: update the code to test UserSearchReply + expect(instance).to.be.a(SwaggerJsClient.UserSearchReply); + }); + + it('should have the property keyWord (base name: "KeyWord")', function() { + // TODO: update the code to test the property keyWord + expect(instance).to.have.property('keyWord'); + // expect(instance.keyWord).to.be(expectedValueLiteral); + }); + + }); + }); + +})); diff --git a/example/clients/javascript/test/model/UserSearchReq.spec.js b/example/clients/javascript/test/model/UserSearchReq.spec.js new file mode 100644 index 0000000..1ae7ff1 --- /dev/null +++ b/example/clients/javascript/test/model/UserSearchReq.spec.js @@ -0,0 +1,52 @@ +/* + * + * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + * + * OpenAPI spec version: + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.18 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerJsClient); + } +}(this, function(expect, SwaggerJsClient) { + 'use strict'; + + var instance; + + describe('(package)', function() { + describe('UserSearchReq', function() { + beforeEach(function() { + instance = new SwaggerJsClient.UserSearchReq(); + }); + + it('should create an instance of UserSearchReq', function() { + // TODO: update the code to test UserSearchReq + expect(instance).to.be.a(SwaggerJsClient.UserSearchReq); + }); + + it('should have the property keyWord (base name: "keyWord")', function() { + // TODO: update the code to test the property keyWord + expect(instance).to.have.property('keyWord'); + // expect(instance.keyWord).to.be(expectedValueLiteral); + }); + + }); + }); + +})); diff --git a/example/clients/php/.swagger-codegen-ignore b/example/clients/php/.swagger-codegen-ignore new file mode 100644 index 0000000..c5fa491 --- /dev/null +++ b/example/clients/php/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/example/clients/php/SwaggerClient-php/.php_cs b/example/clients/php/SwaggerClient-php/.php_cs new file mode 100644 index 0000000..4fbe53e --- /dev/null +++ b/example/clients/php/SwaggerClient-php/.php_cs @@ -0,0 +1,23 @@ +setUsingCache(true) + ->setRules([ + '@PSR2' => true, + 'ordered_imports' => true, + 'phpdoc_order' => true, + 'array_syntax' => [ 'syntax' => 'short' ], + 'strict_comparison' => true, + 'strict_param' => true, + 'no_trailing_whitespace' => false, + 'no_trailing_whitespace_in_comment' => false, + 'braces' => false, + 'single_blank_line_at_eof' => false, + 'blank_line_after_namespace' => false, + ]) + ->setFinder( + PhpCsFixer\Finder::create() + ->exclude('test') + ->exclude('tests') + ->in(__DIR__) + ); diff --git a/example/clients/php/SwaggerClient-php/.travis.yml b/example/clients/php/SwaggerClient-php/.travis.yml new file mode 100644 index 0000000..d77f382 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/.travis.yml @@ -0,0 +1,10 @@ +language: php +sudo: false +php: + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - hhvm +before_install: "composer install" +script: "vendor/bin/phpunit" diff --git a/example/clients/php/SwaggerClient-php/README.md b/example/clients/php/SwaggerClient-php/README.md new file mode 100644 index 0000000..7d95604 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/README.md @@ -0,0 +1,112 @@ +# SwaggerClient-php +No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) + +This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: +- Build package: io.swagger.codegen.languages.PhpClientCodegen + +## Requirements + +PHP 5.5 and later + +## Installation & Usage +### Composer + +To install the bindings via [Composer](http://getcomposer.org/), add the following to `composer.json`: + +``` +{ + "repositories": [ + { + "type": "git", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + } + ], + "require": { + "GIT_USER_ID/GIT_REPO_ID": "*@dev" + } +} +``` + +Then run `composer install` + +### Manual Installation + +Download the files and include `autoload.php`: + +```php + require_once('/path/to/SwaggerClient-php/vendor/autoload.php'); +``` + +## Tests + +To run the unit tests: + +``` +composer install +./vendor/bin/phpunit +``` + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```php +ping(); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling GreetApi->ping: ', $e->getMessage(), PHP_EOL; +} + +?> +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*GreetApi* | [**ping**](docs/Api/GreetApi.md#ping) | **GET** /user/ping | +*UserApiApi* | [**getUserInfo**](docs/Api/UserApiApi.md#getuserinfo) | **GET** /api/user/{id} | 获取用户信息 +*UserApiApi* | [**login**](docs/Api/UserApiApi.md#login) | **POST** /api/user/login | 登录 +*UserApiApi* | [**register**](docs/Api/UserApiApi.md#register) | **POST** /api/user/register | 注册 +*UserApiApi* | [**searchUser**](docs/Api/UserApiApi.md#searchuser) | **GET** /api/user/search | 用户搜索 + + +## Documentation For Models + + - [LoginReq](docs/Model/LoginReq.md) + - [RegisterReq](docs/Model/RegisterReq.md) + - [UserInfoReply](docs/Model/UserInfoReply.md) + - [UserInfoReq](docs/Model/UserInfoReq.md) + - [UserSearchReply](docs/Model/UserSearchReply.md) + - [UserSearchReq](docs/Model/UserSearchReq.md) + + +## Documentation For Authorization + + +## apiKey + +- **Type**: API key +- **API key parameter name**: Authorization +- **Location**: HTTP header + + +## Author + + + + diff --git a/example/clients/php/SwaggerClient-php/composer.json b/example/clients/php/SwaggerClient-php/composer.json new file mode 100644 index 0000000..2d76f02 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/composer.json @@ -0,0 +1,36 @@ +{ + "name": "GIT_USER_ID/GIT_REPO_ID", + "description": "", + "keywords": [ + "swagger", + "php", + "sdk", + "api" + ], + "homepage": "http://swagger.io", + "license": "proprietary", + "authors": [ + { + "name": "Swagger and contributors", + "homepage": "https://github.com/swagger-api/swagger-codegen" + } + ], + "require": { + "php": ">=5.5", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^6.2" + }, + "require-dev": { + "phpunit/phpunit": "^4.8", + "squizlabs/php_codesniffer": "~2.6", + "friendsofphp/php-cs-fixer": "~2.12" + }, + "autoload": { + "psr-4": { "Swagger\\Client\\" : "lib/" } + }, + "autoload-dev": { + "psr-4": { "Swagger\\Client\\" : "test/" } + } +} diff --git a/example/clients/php/SwaggerClient-php/docs/Api/GreetApi.md b/example/clients/php/SwaggerClient-php/docs/Api/GreetApi.md new file mode 100644 index 0000000..59f9f08 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Api/GreetApi.md @@ -0,0 +1,52 @@ +# Swagger\Client\GreetApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**ping**](GreetApi.md#ping) | **GET** /user/ping | + + +# **ping** +> object ping() + + + +### Example +```php +ping(); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling GreetApi->ping: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**object** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/example/clients/php/SwaggerClient-php/docs/Api/UserApiApi.md b/example/clients/php/SwaggerClient-php/docs/Api/UserApiApi.md new file mode 100644 index 0000000..19eb311 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Api/UserApiApi.md @@ -0,0 +1,204 @@ +# Swagger\Client\UserApiApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**getUserInfo**](UserApiApi.md#getUserInfo) | **GET** /api/user/{id} | 获取用户信息 +[**login**](UserApiApi.md#login) | **POST** /api/user/login | 登录 +[**register**](UserApiApi.md#register) | **POST** /api/user/register | 注册 +[**searchUser**](UserApiApi.md#searchUser) | **GET** /api/user/search | 用户搜索 + + +# **getUserInfo** +> \Swagger\Client\Model\UserInfoReply getUserInfo($id, $body) + +获取用户信息 + +### Example +```php +getUserInfo($id, $body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApiApi->getUserInfo: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **id** | **string**| | + **body** | [**\Swagger\Client\Model\UserInfoReq**](../Model/UserInfoReq.md)| | + +### Return type + +[**\Swagger\Client\Model\UserInfoReply**](../Model/UserInfoReply.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **login** +> object login($body) + +登录 + +### Example +```php +login($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApiApi->login: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\LoginReq**](../Model/LoginReq.md)| | + +### Return type + +**object** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **register** +> object register($body) + +注册 + +注册一个用户 + +### Example +```php +register($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApiApi->register: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\RegisterReq**](../Model/RegisterReq.md)| | + +### Return type + +**object** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **searchUser** +> \Swagger\Client\Model\UserSearchReply searchUser($body) + +用户搜索 + +### Example +```php +searchUser($body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling UserApiApi->searchUser: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**\Swagger\Client\Model\UserSearchReq**](../Model/UserSearchReq.md)| | + +### Return type + +[**\Swagger\Client\Model\UserSearchReply**](../Model/UserSearchReply.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/example/clients/php/SwaggerClient-php/docs/Model/LoginReq.md b/example/clients/php/SwaggerClient-php/docs/Model/LoginReq.md new file mode 100644 index 0000000..723259d --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Model/LoginReq.md @@ -0,0 +1,11 @@ +# LoginReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**username** | **string** | | [optional] +**password** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/php/SwaggerClient-php/docs/Model/RegisterReq.md b/example/clients/php/SwaggerClient-php/docs/Model/RegisterReq.md new file mode 100644 index 0000000..9042e4a --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Model/RegisterReq.md @@ -0,0 +1,12 @@ +# RegisterReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**username** | **string** | | [optional] +**password** | **string** | | [optional] +**mobile** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/php/SwaggerClient-php/docs/Model/UserInfoReply.md b/example/clients/php/SwaggerClient-php/docs/Model/UserInfoReply.md new file mode 100644 index 0000000..553b34d --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Model/UserInfoReply.md @@ -0,0 +1,14 @@ +# UserInfoReply + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **string** | | [optional] +**age** | **int** | | [optional] +**birthday** | **string** | | [optional] +**description** | **string** | | [optional] +**tag** | **string[]** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/php/SwaggerClient-php/docs/Model/UserInfoReq.md b/example/clients/php/SwaggerClient-php/docs/Model/UserInfoReq.md new file mode 100644 index 0000000..209684f --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Model/UserInfoReq.md @@ -0,0 +1,10 @@ +# UserInfoReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/php/SwaggerClient-php/docs/Model/UserSearchReply.md b/example/clients/php/SwaggerClient-php/docs/Model/UserSearchReply.md new file mode 100644 index 0000000..b7b8b09 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Model/UserSearchReply.md @@ -0,0 +1,10 @@ +# UserSearchReply + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**key_word** | [**\Swagger\Client\Model\UserInfoReply[]**](UserInfoReply.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/php/SwaggerClient-php/docs/Model/UserSearchReq.md b/example/clients/php/SwaggerClient-php/docs/Model/UserSearchReq.md new file mode 100644 index 0000000..c883e21 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/docs/Model/UserSearchReq.md @@ -0,0 +1,10 @@ +# UserSearchReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**key_word** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/example/clients/php/SwaggerClient-php/git_push.sh b/example/clients/php/SwaggerClient-php/git_push.sh new file mode 100644 index 0000000..160f6f2 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/example/clients/php/SwaggerClient-php/lib/Api/GreetApi.php b/example/clients/php/SwaggerClient-php/lib/Api/GreetApi.php new file mode 100644 index 0000000..8bd5d54 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Api/GreetApi.php @@ -0,0 +1,354 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation ping + * + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return object + */ + public function ping() + { + list($response) = $this->pingWithHttpInfo(); + return $response; + } + + /** + * Operation pingWithHttpInfo + * + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of object, HTTP status code, HTTP response headers (array of strings) + */ + public function pingWithHttpInfo() + { + $returnType = 'object'; + $request = $this->pingRequest(); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'object', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation pingAsync + * + * + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function pingAsync() + { + return $this->pingAsyncWithHttpInfo() + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation pingAsyncWithHttpInfo + * + * + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function pingAsyncWithHttpInfo() + { + $returnType = 'object'; + $request = $this->pingRequest(); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'ping' + * + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function pingRequest() + { + + $resourcePath = '/user/ping'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + + if($headers['Content-Type'] === 'application/json') { + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass) { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + // array has no __toString(), so we should encode it manually + if(is_array($httpBody)) { + $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody)); + } + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/example/clients/php/SwaggerClient-php/lib/Api/UserApiApi.php b/example/clients/php/SwaggerClient-php/lib/Api/UserApiApi.php new file mode 100644 index 0000000..74edee9 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Api/UserApiApi.php @@ -0,0 +1,1183 @@ +client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Operation getUserInfo + * + * 获取用户信息 + * + * @param string $id id (required) + * @param \Swagger\Client\Model\UserInfoReq $body body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\UserInfoReply + */ + public function getUserInfo($id, $body) + { + list($response) = $this->getUserInfoWithHttpInfo($id, $body); + return $response; + } + + /** + * Operation getUserInfoWithHttpInfo + * + * 获取用户信息 + * + * @param string $id (required) + * @param \Swagger\Client\Model\UserInfoReq $body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\UserInfoReply, HTTP status code, HTTP response headers (array of strings) + */ + public function getUserInfoWithHttpInfo($id, $body) + { + $returnType = '\Swagger\Client\Model\UserInfoReply'; + $request = $this->getUserInfoRequest($id, $body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\UserInfoReply', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation getUserInfoAsync + * + * 获取用户信息 + * + * @param string $id (required) + * @param \Swagger\Client\Model\UserInfoReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserInfoAsync($id, $body) + { + return $this->getUserInfoAsyncWithHttpInfo($id, $body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation getUserInfoAsyncWithHttpInfo + * + * 获取用户信息 + * + * @param string $id (required) + * @param \Swagger\Client\Model\UserInfoReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function getUserInfoAsyncWithHttpInfo($id, $body) + { + $returnType = '\Swagger\Client\Model\UserInfoReply'; + $request = $this->getUserInfoRequest($id, $body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'getUserInfo' + * + * @param string $id (required) + * @param \Swagger\Client\Model\UserInfoReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function getUserInfoRequest($id, $body) + { + // verify the required parameter 'id' is set + if ($id === null || (is_array($id) && count($id) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $id when calling getUserInfo' + ); + } + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling getUserInfo' + ); + } + + $resourcePath = '/api/user/{id}'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + // path params + if ($id !== null) { + $resourcePath = str_replace( + '{' . 'id' . '}', + ObjectSerializer::toPathValue($id), + $resourcePath + ); + } + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + + if($headers['Content-Type'] === 'application/json') { + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass) { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + // array has no __toString(), so we should encode it manually + if(is_array($httpBody)) { + $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody)); + } + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation login + * + * 登录 + * + * @param \Swagger\Client\Model\LoginReq $body body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return object + */ + public function login($body) + { + list($response) = $this->loginWithHttpInfo($body); + return $response; + } + + /** + * Operation loginWithHttpInfo + * + * 登录 + * + * @param \Swagger\Client\Model\LoginReq $body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of object, HTTP status code, HTTP response headers (array of strings) + */ + public function loginWithHttpInfo($body) + { + $returnType = 'object'; + $request = $this->loginRequest($body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'object', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation loginAsync + * + * 登录 + * + * @param \Swagger\Client\Model\LoginReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function loginAsync($body) + { + return $this->loginAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation loginAsyncWithHttpInfo + * + * 登录 + * + * @param \Swagger\Client\Model\LoginReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function loginAsyncWithHttpInfo($body) + { + $returnType = 'object'; + $request = $this->loginRequest($body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'login' + * + * @param \Swagger\Client\Model\LoginReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function loginRequest($body) + { + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling login' + ); + } + + $resourcePath = '/api/user/login'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + + if($headers['Content-Type'] === 'application/json') { + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass) { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + // array has no __toString(), so we should encode it manually + if(is_array($httpBody)) { + $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody)); + } + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation register + * + * 注册 + * + * @param \Swagger\Client\Model\RegisterReq $body body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return object + */ + public function register($body) + { + list($response) = $this->registerWithHttpInfo($body); + return $response; + } + + /** + * Operation registerWithHttpInfo + * + * 注册 + * + * @param \Swagger\Client\Model\RegisterReq $body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of object, HTTP status code, HTTP response headers (array of strings) + */ + public function registerWithHttpInfo($body) + { + $returnType = 'object'; + $request = $this->registerRequest($body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'object', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation registerAsync + * + * 注册 + * + * @param \Swagger\Client\Model\RegisterReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function registerAsync($body) + { + return $this->registerAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation registerAsyncWithHttpInfo + * + * 注册 + * + * @param \Swagger\Client\Model\RegisterReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function registerAsyncWithHttpInfo($body) + { + $returnType = 'object'; + $request = $this->registerRequest($body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'register' + * + * @param \Swagger\Client\Model\RegisterReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function registerRequest($body) + { + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling register' + ); + } + + $resourcePath = '/api/user/register'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + + if($headers['Content-Type'] === 'application/json') { + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass) { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + // array has no __toString(), so we should encode it manually + if(is_array($httpBody)) { + $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody)); + } + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'POST', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation searchUser + * + * 用户搜索 + * + * @param \Swagger\Client\Model\UserSearchReq $body body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return \Swagger\Client\Model\UserSearchReply + */ + public function searchUser($body) + { + list($response) = $this->searchUserWithHttpInfo($body); + return $response; + } + + /** + * Operation searchUserWithHttpInfo + * + * 用户搜索 + * + * @param \Swagger\Client\Model\UserSearchReq $body (required) + * + * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of \Swagger\Client\Model\UserSearchReply, HTTP status code, HTTP response headers (array of strings) + */ + public function searchUserWithHttpInfo($body) + { + $returnType = '\Swagger\Client\Model\UserSearchReply'; + $request = $this->searchUserRequest($body); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? $e->getResponse()->getBody()->getContents() : null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\Swagger\Client\Model\UserSearchReply', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation searchUserAsync + * + * 用户搜索 + * + * @param \Swagger\Client\Model\UserSearchReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchUserAsync($body) + { + return $this->searchUserAsyncWithHttpInfo($body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation searchUserAsyncWithHttpInfo + * + * 用户搜索 + * + * @param \Swagger\Client\Model\UserSearchReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function searchUserAsyncWithHttpInfo($body) + { + $returnType = '\Swagger\Client\Model\UserSearchReply'; + $request = $this->searchUserRequest($body); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'searchUser' + * + * @param \Swagger\Client\Model\UserSearchReq $body (required) + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + protected function searchUserRequest($body) + { + // verify the required parameter 'body' is set + if ($body === null || (is_array($body) && count($body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $body when calling searchUser' + ); + } + + $resourcePath = '/api/user/search'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + // $_tempBody is the method argument, if present + $httpBody = $_tempBody; + + if($headers['Content-Type'] === 'application/json') { + // \stdClass has no __toString(), so we should encode it manually + if ($httpBody instanceof \stdClass) { + $httpBody = \GuzzleHttp\json_encode($httpBody); + } + // array has no __toString(), so we should encode it manually + if(is_array($httpBody)) { + $httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($httpBody)); + } + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = \GuzzleHttp\json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + return new Request( + 'GET', + $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Create http client option + * + * @throws \RuntimeException on file opening failure + * @return array of http client options + */ + protected function createHttpClientOption() + { + $options = []; + if ($this->config->getDebug()) { + $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); + if (!$options[RequestOptions::DEBUG]) { + throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); + } + } + + return $options; + } +} diff --git a/example/clients/php/SwaggerClient-php/lib/ApiException.php b/example/clients/php/SwaggerClient-php/lib/ApiException.php new file mode 100644 index 0000000..cfd7477 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/ApiException.php @@ -0,0 +1,121 @@ +responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; + } + + /** + * Gets the HTTP response header + * + * @return string[]|null HTTP response header + */ + public function getResponseHeaders() + { + return $this->responseHeaders; + } + + /** + * Gets the HTTP body of the server response either as Json or string + * + * @return mixed HTTP body of the server response either as \stdClass or string + */ + public function getResponseBody() + { + return $this->responseBody; + } + + /** + * Sets the deseralized response object (during deserialization) + * + * @param mixed $obj Deserialized response object + * + * @return void + */ + public function setResponseObject($obj) + { + $this->responseObject = $obj; + } + + /** + * Gets the deseralized response object (during deserialization) + * + * @return mixed the deserialized response object + */ + public function getResponseObject() + { + return $this->responseObject; + } +} diff --git a/example/clients/php/SwaggerClient-php/lib/Configuration.php b/example/clients/php/SwaggerClient-php/lib/Configuration.php new file mode 100644 index 0000000..caeebe3 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Configuration.php @@ -0,0 +1,429 @@ +tempFolderPath = sys_get_temp_dir(); + } + + /** + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * + * @return $this + */ + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the detault configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' OpenAPI Spec Version: ' . PHP_EOL; + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } +} diff --git a/example/clients/php/SwaggerClient-php/lib/HeaderSelector.php b/example/clients/php/SwaggerClient-php/lib/HeaderSelector.php new file mode 100644 index 0000000..e331308 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/HeaderSelector.php @@ -0,0 +1,109 @@ +selectAcceptHeader($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + $headers['Content-Type'] = $this->selectContentTypeHeader($contentTypes); + return $headers; + } + + /** + * @param string[] $accept + * @return array + */ + public function selectHeadersForMultipart($accept) + { + $headers = $this->selectHeaders($accept, []); + + unset($headers['Content-Type']); + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * + * @return string Accept (e.g. application/json) + */ + private function selectAcceptHeader($accept) + { + if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { + return null; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } + } + + /** + * Return the content type based on an array of content-type provided + * + * @param string[] $contentType Array fo content-type + * + * @return string Content-Type (e.g. application/json) + */ + private function selectContentTypeHeader($contentType) + { + if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $contentType)) { + return 'application/json'; + } else { + return implode(',', $contentType); + } + } +} diff --git a/example/clients/php/SwaggerClient-php/lib/Model/LoginReq.php b/example/clients/php/SwaggerClient-php/lib/Model/LoginReq.php new file mode 100644 index 0000000..2d6b27a --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Model/LoginReq.php @@ -0,0 +1,331 @@ + 'string', + 'password' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'username' => null, + 'password' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'username' => 'username', + 'password' => 'password' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'username' => 'setUsername', + 'password' => 'setPassword' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'username' => 'getUsername', + 'password' => 'getPassword' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['username'] = isset($data['username']) ? $data['username'] : null; + $this->container['password'] = isset($data['password']) ? $data['password'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets username + * + * @return string + */ + public function getUsername() + { + return $this->container['username']; + } + + /** + * Sets username + * + * @param string $username username + * + * @return $this + */ + public function setUsername($username) + { + $this->container['username'] = $username; + + return $this; + } + + /** + * Gets password + * + * @return string + */ + public function getPassword() + { + return $this->container['password']; + } + + /** + * Sets password + * + * @param string $password password + * + * @return $this + */ + public function setPassword($password) + { + $this->container['password'] = $password; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/example/clients/php/SwaggerClient-php/lib/Model/ModelInterface.php b/example/clients/php/SwaggerClient-php/lib/Model/ModelInterface.php new file mode 100644 index 0000000..f08f156 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Model/ModelInterface.php @@ -0,0 +1,96 @@ + 'string', + 'password' => 'string', + 'mobile' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'username' => null, + 'password' => null, + 'mobile' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'username' => 'username', + 'password' => 'password', + 'mobile' => 'mobile' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'username' => 'setUsername', + 'password' => 'setPassword', + 'mobile' => 'setMobile' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'username' => 'getUsername', + 'password' => 'getPassword', + 'mobile' => 'getMobile' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['username'] = isset($data['username']) ? $data['username'] : null; + $this->container['password'] = isset($data['password']) ? $data['password'] : null; + $this->container['mobile'] = isset($data['mobile']) ? $data['mobile'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets username + * + * @return string + */ + public function getUsername() + { + return $this->container['username']; + } + + /** + * Sets username + * + * @param string $username username + * + * @return $this + */ + public function setUsername($username) + { + $this->container['username'] = $username; + + return $this; + } + + /** + * Gets password + * + * @return string + */ + public function getPassword() + { + return $this->container['password']; + } + + /** + * Sets password + * + * @param string $password password + * + * @return $this + */ + public function setPassword($password) + { + $this->container['password'] = $password; + + return $this; + } + + /** + * Gets mobile + * + * @return string + */ + public function getMobile() + { + return $this->container['mobile']; + } + + /** + * Sets mobile + * + * @param string $mobile mobile + * + * @return $this + */ + public function setMobile($mobile) + { + $this->container['mobile'] = $mobile; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/example/clients/php/SwaggerClient-php/lib/Model/UserInfoReply.php b/example/clients/php/SwaggerClient-php/lib/Model/UserInfoReply.php new file mode 100644 index 0000000..8ee2855 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Model/UserInfoReply.php @@ -0,0 +1,421 @@ + 'string', + 'age' => 'int', + 'birthday' => 'string', + 'description' => 'string', + 'tag' => 'string[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'name' => null, + 'age' => 'int32', + 'birthday' => null, + 'description' => null, + 'tag' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'name' => 'name', + 'age' => 'age', + 'birthday' => 'birthday', + 'description' => 'description', + 'tag' => 'tag' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'name' => 'setName', + 'age' => 'setAge', + 'birthday' => 'setBirthday', + 'description' => 'setDescription', + 'tag' => 'setTag' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'name' => 'getName', + 'age' => 'getAge', + 'birthday' => 'getBirthday', + 'description' => 'getDescription', + 'tag' => 'getTag' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['name'] = isset($data['name']) ? $data['name'] : null; + $this->container['age'] = isset($data['age']) ? $data['age'] : null; + $this->container['birthday'] = isset($data['birthday']) ? $data['birthday'] : null; + $this->container['description'] = isset($data['description']) ? $data['description'] : null; + $this->container['tag'] = isset($data['tag']) ? $data['tag'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets name + * + * @return string + */ + public function getName() + { + return $this->container['name']; + } + + /** + * Sets name + * + * @param string $name name + * + * @return $this + */ + public function setName($name) + { + $this->container['name'] = $name; + + return $this; + } + + /** + * Gets age + * + * @return int + */ + public function getAge() + { + return $this->container['age']; + } + + /** + * Sets age + * + * @param int $age age + * + * @return $this + */ + public function setAge($age) + { + $this->container['age'] = $age; + + return $this; + } + + /** + * Gets birthday + * + * @return string + */ + public function getBirthday() + { + return $this->container['birthday']; + } + + /** + * Sets birthday + * + * @param string $birthday birthday + * + * @return $this + */ + public function setBirthday($birthday) + { + $this->container['birthday'] = $birthday; + + return $this; + } + + /** + * Gets description + * + * @return string + */ + public function getDescription() + { + return $this->container['description']; + } + + /** + * Sets description + * + * @param string $description description + * + * @return $this + */ + public function setDescription($description) + { + $this->container['description'] = $description; + + return $this; + } + + /** + * Gets tag + * + * @return string[] + */ + public function getTag() + { + return $this->container['tag']; + } + + /** + * Sets tag + * + * @param string[] $tag tag + * + * @return $this + */ + public function setTag($tag) + { + $this->container['tag'] = $tag; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/example/clients/php/SwaggerClient-php/lib/Model/UserInfoReq.php b/example/clients/php/SwaggerClient-php/lib/Model/UserInfoReq.php new file mode 100644 index 0000000..6a245d5 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Model/UserInfoReq.php @@ -0,0 +1,301 @@ + 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'id' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'id' => 'id' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'id' => 'setId' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'id' => 'getId' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['id'] = isset($data['id']) ? $data['id'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets id + * + * @return string + */ + public function getId() + { + return $this->container['id']; + } + + /** + * Sets id + * + * @param string $id id + * + * @return $this + */ + public function setId($id) + { + $this->container['id'] = $id; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/example/clients/php/SwaggerClient-php/lib/Model/UserSearchReply.php b/example/clients/php/SwaggerClient-php/lib/Model/UserSearchReply.php new file mode 100644 index 0000000..4f6b9ab --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Model/UserSearchReply.php @@ -0,0 +1,301 @@ + '\Swagger\Client\Model\UserInfoReply[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'key_word' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'key_word' => 'KeyWord' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'key_word' => 'setKeyWord' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'key_word' => 'getKeyWord' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['key_word'] = isset($data['key_word']) ? $data['key_word'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets key_word + * + * @return \Swagger\Client\Model\UserInfoReply[] + */ + public function getKeyWord() + { + return $this->container['key_word']; + } + + /** + * Sets key_word + * + * @param \Swagger\Client\Model\UserInfoReply[] $key_word key_word + * + * @return $this + */ + public function setKeyWord($key_word) + { + $this->container['key_word'] = $key_word; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/example/clients/php/SwaggerClient-php/lib/Model/UserSearchReq.php b/example/clients/php/SwaggerClient-php/lib/Model/UserSearchReq.php new file mode 100644 index 0000000..538901b --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/Model/UserSearchReq.php @@ -0,0 +1,301 @@ + 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $swaggerFormats = [ + 'key_word' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'key_word' => 'keyWord' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'key_word' => 'setKeyWord' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'key_word' => 'getKeyWord' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$swaggerModelName; + } + + + + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['key_word'] = isset($data['key_word']) ? $data['key_word'] : null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets key_word + * + * @return string + */ + public function getKeyWord() + { + return $this->container['key_word']; + } + + /** + * Sets key_word + * + * @param string $key_word key_word + * + * @return $this + */ + public function setKeyWord($key_word) + { + $this->container['key_word'] = $key_word; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * + * @param integer $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/example/clients/php/SwaggerClient-php/lib/ObjectSerializer.php b/example/clients/php/SwaggerClient-php/lib/ObjectSerializer.php new file mode 100644 index 0000000..28e0f0f --- /dev/null +++ b/example/clients/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -0,0 +1,322 @@ +format('Y-m-d') : $data->format(\DateTime::ATOM); + } elseif (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = self::sanitizeForSerialization($value); + } + return $data; + } elseif ($data instanceof \stdClass) { + foreach ($data as $property => $value) { + $data->$property = self::sanitizeForSerialization($value); + } + return $data; + } elseif (is_object($data)) { + $values = []; + $formats = $data::swaggerFormats(); + foreach ($data::swaggerTypes() as $property => $swaggerType) { + $getter = $data::getters()[$property]; + $value = $data->$getter(); + if ($value !== null + && !in_array($swaggerType, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true) + && method_exists($swaggerType, 'getAllowableEnumValues') + && !in_array($value, $swaggerType::getAllowableEnumValues(), true)) { + $imploded = implode("', '", $swaggerType::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$swaggerType', must be one of: '$imploded'"); + } + if ($value !== null) { + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $swaggerType, $formats[$property]); + } + } + return (object)$values; + } else { + return (string)$data; + } + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public static function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * + * @param string $value a string which will be part of the path + * + * @return string the serialized object + */ + public static function toPathValue($value) + { + return rawurlencode(self::toString($value)); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * + * @param string[]|string|\DateTime $object an object to be serialized to a string + * + * @return string the serialized object + */ + public static function toQueryValue($object) + { + if (is_array($object)) { + return implode(',', $object); + } else { + return self::toString($object); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string $value a string which will be part of the header + * + * @return string the header string + */ + public static function toHeaderValue($value) + { + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string|\SplFileObject $value the value of the form parameter + * + * @return string the form string + */ + public static function toFormValue($value) + { + if ($value instanceof \SplFileObject) { + return $value->getRealPath(); + } else { + return self::toString($value); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * + * @param string|\DateTime $value the value of the parameter + * + * @return string the header string + */ + public static function toString($value) + { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ATOM); + } else { + return $value; + } + } + + /** + * Serialize an array to a string. + * + * @param array $collection collection to serialize to a string + * @param string $collectionFormat the format use for serialization (csv, + * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array + * + * @return string + */ + public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) + { + if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { + // http_build_query() almost does the job for us. We just + // need to fix the result of multidimensional arrays. + return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&')); + } + switch ($collectionFormat) { + case 'pipes': + return implode('|', $collection); + + case 'tsv': + return implode("\t", $collection); + + case 'ssv': + return implode(' ', $collection); + + case 'csv': + // Deliberate fall through. CSV is default format. + default: + return implode(',', $collection); + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used + * + * @return object|array|null an single or an array of $class instances + */ + public static function deserialize($data, $class, $httpHeaders = null) + { + if (null === $data) { + return null; + } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = []; + if (strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = self::deserialize($value, $subClass, null); + } + } + return $deserialized; + } elseif (strcasecmp(substr($class, -2), '[]') === 0) { + $subClass = substr($class, 0, -2); + $values = []; + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass, null); + } + return $values; + } elseif ($class === 'object') { + settype($data, 'array'); + return $data; + } elseif ($class === '\DateTime') { + // Some API's return an invalid, empty string as a + // date-time property. DateTime::__construct() will return + // the current time for empty input which is probably not + // what is meant. The invalid empty string is probably to + // be interpreted as a missing field/value. Let's handle + // this graceful. + if (!empty($data)) { + return new \DateTime($data); + } else { + return null; + } + } elseif (in_array($class, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + settype($data, $class); + return $data; + } elseif ($class === '\SplFileObject') { + /** @var \Psr\Http\Message\StreamInterface $data */ + + // determine file name + if (array_key_exists('Content-Disposition', $httpHeaders) && + preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); + } else { + $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); + } + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + return new \SplFileObject($filename, 'r'); + } elseif (method_exists($class, 'getAllowableEnumValues')) { + if (!in_array($data, $class::getAllowableEnumValues(), true)) { + $imploded = implode("', '", $class::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); + } + return $data; + } else { + // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; + if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { + $subclass = '\Swagger\Client\Model\\' . $data->{$discriminator}; + if (is_subclass_of($subclass, $class)) { + $class = $subclass; + } + } + $instance = new $class(); + foreach ($instance::swaggerTypes() as $property => $type) { + $propertySetter = $instance::setters()[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::attributeMap()[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::attributeMap()[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); + } + } + return $instance; + } + } +} diff --git a/example/clients/php/SwaggerClient-php/phpunit.xml.dist b/example/clients/php/SwaggerClient-php/phpunit.xml.dist new file mode 100644 index 0000000..c12ee14 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/phpunit.xml.dist @@ -0,0 +1,21 @@ + + + + + ./test/Api + ./test/Model + + + + + + ./lib/Api + ./lib/Model + + + diff --git a/example/clients/php/SwaggerClient-php/test/Api/GreetApiTest.php b/example/clients/php/SwaggerClient-php/test/Api/GreetApiTest.php new file mode 100644 index 0000000..dc0daa4 --- /dev/null +++ b/example/clients/php/SwaggerClient-php/test/Api/GreetApiTest.php @@ -0,0 +1,83 @@ +