Merge branch 'typescript-fetch-basic-unit-test' of https://github.com/leonyu/swagger-codegen into leonyu-typescript-fetch-basic-unit-test

This commit is contained in:
wing328 2016-05-13 18:02:38 +08:00
commit 1e00bbfb8d
57 changed files with 13374 additions and 3868 deletions

12
.gitignore vendored
View File

@ -41,6 +41,7 @@ samples/server-generator/scalatra/target
samples/server-generator/scalatra/output/.history
# nodejs
**/node_modules/
samples/server-generator/node/output/node_modules
samples/server/petstore/nodejs/node_modules
samples/server/petstore/nodejs-server/node_modules
@ -116,13 +117,6 @@ samples/client/petstore/python/.venv/
# ts
samples/client/petstore/typescript-node/npm/node_modules
samples/client/petstore/typescript-fetch/with-package-metadata/node_modules
samples/client/petstore/typescript-fetch/with-package-metadata/dist
samples/client/petstore/typescript-fetch/with-package-metadata/typings
samples/client/petstore/typescript-fetch/default/node_modules
samples/client/petstore/typescript-fetch/default/dist
samples/client/petstore/typescript-fetch/default/typings
samples/client/petstore/typescript-fetch/default-es6/node_modules
samples/client/petstore/typescript-fetch/default-es6/dist
samples/client/petstore/typescript-fetch/default-es6/typings
samples/client/petstore/typescript-fetch/**/dist/
samples/client/petstore/typescript-fetch/**/typings

View File

@ -1,5 +1,5 @@
#!/bin/sh
./bin/typescript-fetch-petstore-target-es6.sh
./bin/typescript-fetch-petstore-target-with-package-metadata.sh
./bin/typescript-fetch-petstore-with-npm-version.sh
./bin/typescript-fetch-petstore.sh

View File

@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/default-es6"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/builds/es6-target"
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-with-package-metadata.json -o samples/client/petstore/typescript-fetch/with-package-metadata"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-with-npm-version.json -o samples/client/petstore/typescript-fetch/builds/with-npm-version"
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/default"
ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/builds/default"
java $JAVA_OPTS -jar $executable $ags

View File

@ -26,7 +26,6 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege
super.processOpts();
supportingFiles.add(new SupportingFile("api.mustache", "", "api.ts"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("assign.ts", "", "assign.ts"));
supportingFiles.add(new SupportingFile("README.md", "", "README.md"));
supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json"));

View File

@ -1,44 +1,54 @@
# TypeScript-Fetch
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments:
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments:
* Node.JS
Environment
* Node.js
* Webpack
* Browserify
It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
Language level
* ES5 - you must have a Promises/A+ library installed
* ES6
Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Installation ###
`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`.
`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`.
#### NPM repository ###
If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module.
#### NPM ####
You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project.
#### NPM install local file ###
You should be able to directly install the module using `npm install file:///codegen_path`.
You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path.
NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute.
#### direct copy/symlink ###
You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below)
### Usage ###
With ES6 module syntax, the following syntaxes are supported:
Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
```
The CommonJS syntax is as follows:
```
import localName = require('npmName');
```
#### Direct copy/symlink ####
You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows:
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
With CommonJS, the following syntaxes are supported:
The CommonJS syntax is as follows:
```
import localName = require('npmName');
import localName = require('./symlinkDir')';
```

View File

@ -1,7 +1,23 @@
import * as querystring from 'querystring';
import * as fetch from 'isomorphic-fetch';
import {assign} from './assign';
import * as querystring from "querystring";
import * as url from "url";
import * as isomorphicFetch from "isomorphic-fetch";
{{^supportsES6}}
import * as assign from "core-js/library/fn/object/assign";
{{/supportsES6}}
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
export class BaseAPI {
basePath: string;
fetch: FetchAPI;
constructor(basePath: string = "{{basePath}}", fetch: FetchAPI = isomorphicFetch) {
this.basePath = basePath;
this.fetch = fetch;
}
}
{{#models}}
{{#model}}
@ -13,24 +29,20 @@ import {assign} from './assign';
export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{
{{#vars}}
{{#description}}
/**
* {{{description}}}
*/
{{/description}}
"{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}.{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
"{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{classname}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}};
{{/vars}}
}
{{#hasEnums}}
export namespace {{classname}} {
{{#vars}}
{{#isEnum}}
export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}};
export type {{classname}}{{datatypeWithEnum}} = {{#allowableValues}}{{#values}}"{{.}}"{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}};
{{/isEnum}}
{{/vars}}
}
{{/hasEnums}}
{{/model}}
{{/models}}
@ -38,96 +50,72 @@ export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-las
{{#apiInfo}}
{{#apis}}
{{#operations}}
//export namespace {{package}} {
'use strict';
{{#description}}
/**
* {{&description}}
*/
/**
* {{&description}}
*/
{{/description}}
export class {{classname}} {
protected basePath = '{{basePath}}';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
export class {{classname}} extends BaseAPI {
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}* @param {{paramName}} {{description}}
{{/allParams}}*/
public {{nickname}} (params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> {
const localVarPath = this.basePath + '{{path}}'{{#pathParams}}
.replace('{' + '{{baseName}}' + '}', String(params.{{paramName}})){{/pathParams}};
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
{{#hasFormParams}}
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
{{/hasFormParams}}
{{#hasBodyParam}}
headerParams['Content-Type'] = 'application/json';
{{/hasBodyParam}}
/** {{#summary}}
* {{summary}}{{/summary}}{{#notes}}
* {{notes}}{{/notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{/allParams}}
*/
{{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}): Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> {
{{#allParams}}
{{#required}}
// verify required parameter '{{paramName}}' is set
if (params.{{paramName}} == null) {
throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}');
}
// verify required parameter "{{paramName}}" is set
if (params["{{paramName}}"] == null) {
throw new Error("Missing required parameter {{paramName}} when calling {{nickname}}");
}
{{/required}}
{{/allParams}}
{{#queryParams}}
if (params.{{paramName}} !== undefined) {
queryParameters['{{baseName}}'] = params.{{paramName}};
}
const baseUrl = `${this.basePath}{{path}}`{{#pathParams}}
.replace(`{${"{{baseName}}"}}`, `${ params.{{paramName}} }`){{/pathParams}};
let urlObj = url.parse(baseUrl, true);
{{#hasQueryParams}}
urlObj.query = {{#supportsES6}}Object.{{/supportsES6}}assign({}, urlObj.query, { {{#queryParams}}
"{{baseName}}": params.{{paramName}},{{/queryParams}}
});
{{/hasQueryParams}}
let fetchOptions: RequestInit = { method: "{{httpMethod}}" };
{{/queryParams}}
{{#headerParams}}
headerParams['{{baseName}}'] = params.{{paramName}};
{{/headerParams}}
{{#formParams}}
formParams['{{baseName}}'] = params.{{paramName}};
{{/formParams}}
let fetchParams = {
method: '{{httpMethod}}',
headers: headerParams,
{{#bodyParam}}body: JSON.stringify(params.{{paramName}}),
{{/bodyParam}}
{{#hasFormParams}}body: querystring.stringify(formParams),
{{/hasFormParams}}
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
let contentTypeHeader: Dictionary<string>;
{{#hasFormParams}}
contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
fetchOptions.body = querystring.stringify({ {{#formParams}}
"{{baseName}}": params.{{paramName}},{{/formParams}}
});
{{/hasFormParams}}
{{#hasBodyParam}}
contentTypeHeader = { "Content-Type": "application/json" };{{#bodyParam}}
if (params["{{paramName}}"]) {
fetchOptions.body = JSON.stringify(params["{{paramName}}"] || {});
}{{/bodyParam}}
{{/hasBodyParam}}
{{#hasHeaderParam}}
fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ {{#headerParams}}
"{{baseName}}": params.{{paramName}},{{/headerParams}}
}, contentTypeHeader);
{{/hasHeaderParam}}
{{^hasHeaderParam}}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
{{/operation}}
{{/hasHeaderParam}}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response{{#returnType}}.json(){{/returnType}};
} else {
throw response;
}
});
}
//}
{{/operation}}
}
{{/operations}}
{{/apis}}
{{/apiInfo}}

View File

@ -1,18 +0,0 @@
export function assign (target: any, ...args: any[]) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (let source of args) {
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};

View File

@ -1,15 +1,15 @@
{
"name": "{{#npmName}}{{{npmName}}}{{/npmName}}{{^npmName}}typescript-fetch-api{{/npmName}}",
"version": "{{#npmVersion}}{{{npmVersion}}}{{/npmVersion}}{{^npmVersion}}0.0.0{{/npmVersion}}",
"private": true,
"main": "./dist/api.js",
"browser": "./dist/api.js",
"typings": "./dist/api.d.ts",
"dependencies": {
"isomorphic-fetch": "^2.2.1"
{{^supportsES6}}"core-js": "^2.4.0",
{{/supportsES6}}"isomorphic-fetch": "^2.2.1"
},
"scripts" : {
"install" : "typings install && tsc"
"prepublish" : "typings install && tsc"
},
"devDependencies": {
"typescript": "^1.8.10",

View File

@ -1,9 +1,9 @@
{
"version": false,
"dependencies": {},
"ambientDependencies": {
{{^supportsES6}} "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304",
{{/supportsES6}} "node": "registry:dt/node#4.0.0+20160423143914",
"ambientDependencies": { {{^supportsES6}}
"core-js": "registry:dt/core-js#0.0.0+20160317120654",{{/supportsES6}}
"node": "registry:dt/node#4.0.0+20160423143914",
"isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433"
}
}

View File

@ -1,859 +0,0 @@
import * as querystring from 'querystring';
import * as fetch from 'isomorphic-fetch';
import {assign} from './assign';
export interface Category {
"id"?: number;
"name"?: string;
}
export interface Order {
"id"?: number;
"petId"?: number;
"quantity"?: number;
"shipDate"?: Date;
/**
* Order Status
*/
"status"?: Order.StatusEnum;
"complete"?: boolean;
}
export enum StatusEnum {
placed = <any> 'placed',
approved = <any> 'approved',
delivered = <any> 'delivered'
}
export interface Pet {
"id"?: number;
"category"?: Category;
"name": string;
"photoUrls": Array<string>;
"tags"?: Array<Tag>;
/**
* pet status in the store
*/
"status"?: Pet.StatusEnum;
}
export enum StatusEnum {
available = <any> 'available',
pending = <any> 'pending',
sold = <any> 'sold'
}
export interface Tag {
"id"?: number;
"name"?: string;
}
export interface User {
"id"?: number;
"username"?: string;
"firstName"?: string;
"lastName"?: string;
"email"?: string;
"password"?: string;
"phone"?: string;
/**
* User Status
*/
"userStatus"?: number;
}
//export namespace {
'use strict';
export class PetApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling deletePet');
}
headerParams['api_key'] = params.apiKey;
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus (params: { status?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByStatus';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.status !== undefined) {
queryParameters['status'] = params.status;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
public findPetsByTags (params: { tags?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByTags';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.tags !== undefined) {
queryParameters['tags'] = params.tags;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Pet> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling getPetById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling updatePetWithForm');
}
formParams['name'] = params.name;
formParams['status'] = params.status;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling uploadFile');
}
formParams['additionalMetadata'] = params.additionalMetadata;
formParams['file'] = params.file;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class StoreApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling deleteOrder');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> {
const localVarPath = this.basePath + '/store/inventory';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling getOrderById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class UserApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithArrayInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithArray';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithListInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithList';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling deleteUser');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<User> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling getUserByName');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<string> {
const localVarPath = this.basePath + '/user/login';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.username !== undefined) {
queryParameters['username'] = params.username;
}
if (params.password !== undefined) {
queryParameters['password'] = params.password;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Logs out current logged in user session
*
*/
public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/logout';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling updateUser');
}
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
var error = new Error(response.statusText);
error['response'] = response;
throw error;
}
});
}
}
//}

View File

@ -1,18 +0,0 @@
export function assign (target, ...args) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (let source of args) {
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};

View File

@ -0,0 +1,54 @@
# TypeScript-Fetch
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments:
Environment
* Node.js
* Webpack
* Browserify
Language level
* ES5 - you must have a Promises/A+ library installed
* ES6
Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Installation ###
`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`.
#### NPM ####
You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project.
You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path.
Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
```
The CommonJS syntax is as follows:
```
import localName = require('npmName');
```
#### Direct copy/symlink ####
You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows:
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
The CommonJS syntax is as follows:
```
import localName = require('./symlinkDir')';
```

View File

@ -0,0 +1,620 @@
import * as querystring from "querystring";
import * as url from "url";
import * as isomorphicFetch from "isomorphic-fetch";
import * as assign from "core-js/library/fn/object/assign";
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
export class BaseAPI {
basePath: string;
fetch: FetchAPI;
constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) {
this.basePath = basePath;
this.fetch = fetch;
}
}
export interface Category {
"id"?: number;
"name"?: string;
}
export interface Order {
"id"?: number;
"petId"?: number;
"quantity"?: number;
"shipDate"?: Date;
/**
* Order Status
*/
"status"?: OrderStatusEnum;
"complete"?: boolean;
}
export type OrderStatusEnum = "placed" | "approved" | "delivered";
export interface Pet {
"id"?: number;
"category"?: Category;
"name": string;
"photoUrls": Array<string>;
"tags"?: Array<Tag>;
/**
* pet status in the store
*/
"status"?: PetStatusEnum;
}
export type PetStatusEnum = "available" | "pending" | "sold";
export interface Tag {
"id"?: number;
"name"?: string;
}
export interface User {
"id"?: number;
"username"?: string;
"firstName"?: string;
"lastName"?: string;
"email"?: string;
"password"?: string;
"phone"?: string;
/**
* User Status
*/
"userStatus"?: number;
}
export class PetApi extends BaseAPI {
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
addPet(params: { body?: Pet; }): Promise<any> {
const baseUrl = `${this.basePath}/pet`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
deletePet(params: { petId: number; apiKey?: string; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling deletePet");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
*/
findPetsByStatus(params: { status?: Array<string>; }): Promise<Array<Pet>> {
const baseUrl = `${this.basePath}/pet/findByStatus`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = assign({}, urlObj.query, {
"status": params.status,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
findPetsByTags(params: { tags?: Array<string>; }): Promise<Array<Pet>> {
const baseUrl = `${this.basePath}/pet/findByTags`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = assign({}, urlObj.query, {
"tags": params.tags,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
getPetById(params: { petId: number; }): Promise<Pet> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling getPetById");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
updatePet(params: { body?: Pet; }): Promise<any> {
const baseUrl = `${this.basePath}/pet`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "PUT" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling updatePetWithForm");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
fetchOptions.body = querystring.stringify({
"name": params.name,
"status": params.status,
});
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling uploadFile");
}
const baseUrl = `${this.basePath}/pet/{petId}/uploadImage`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
fetchOptions.body = querystring.stringify({
"additionalMetadata": params.additionalMetadata,
"file": params.file,
});
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
}
export class StoreApi extends BaseAPI {
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
deleteOrder(params: { orderId: string; }): Promise<any> {
// verify required parameter "orderId" is set
if (params["orderId"] == null) {
throw new Error("Missing required parameter orderId when calling deleteOrder");
}
const baseUrl = `${this.basePath}/store/order/{orderId}`
.replace(`{${"orderId"}}`, `${ params.orderId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
getInventory(): Promise<{ [key: string]: number; }> {
const baseUrl = `${this.basePath}/store/inventory`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
getOrderById(params: { orderId: string; }): Promise<Order> {
// verify required parameter "orderId" is set
if (params["orderId"] == null) {
throw new Error("Missing required parameter orderId when calling getOrderById");
}
const baseUrl = `${this.basePath}/store/order/{orderId}`
.replace(`{${"orderId"}}`, `${ params.orderId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
placeOrder(params: { body?: Order; }): Promise<Order> {
const baseUrl = `${this.basePath}/store/order`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
}
export class UserApi extends BaseAPI {
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
createUser(params: { body?: User; }): Promise<any> {
const baseUrl = `${this.basePath}/user`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
createUsersWithArrayInput(params: { body?: Array<User>; }): Promise<any> {
const baseUrl = `${this.basePath}/user/createWithArray`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
createUsersWithListInput(params: { body?: Array<User>; }): Promise<any> {
const baseUrl = `${this.basePath}/user/createWithList`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
deleteUser(params: { username: string; }): Promise<any> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling deleteUser");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
getUserByName(params: { username: string; }): Promise<User> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling getUserByName");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
loginUser(params: { username?: string; password?: string; }): Promise<string> {
const baseUrl = `${this.basePath}/user/login`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = assign({}, urlObj.query, {
"username": params.username,
"password": params.password,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Logs out current logged in user session
*
*/
logoutUser(): Promise<any> {
const baseUrl = `${this.basePath}/user/logout`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
updateUser(params: { username: string; body?: User; }): Promise<any> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling updateUser");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "PUT" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
}

View File

@ -1,15 +1,15 @@
{
"name": "typescript-fetch-api",
"version": "0.0.0",
"private": true,
"main": "./dist/api.js",
"browser": "./dist/api.js",
"typings": "./dist/api.d.ts",
"dependencies": {
"core-js": "^2.4.0",
"isomorphic-fetch": "^2.2.1"
},
"scripts" : {
"install" : "typings install && tsc"
"prepublish" : "typings install && tsc"
},
"devDependencies": {
"typescript": "^1.8.10",

View File

@ -2,7 +2,7 @@
"version": false,
"dependencies": {},
"ambientDependencies": {
"es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304",
"core-js": "registry:dt/core-js#0.0.0+20160317120654",
"node": "registry:dt/node#4.0.0+20160423143914",
"isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433"
}

View File

@ -0,0 +1,54 @@
# TypeScript-Fetch
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments:
Environment
* Node.js
* Webpack
* Browserify
Language level
* ES5 - you must have a Promises/A+ library installed
* ES6
Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Installation ###
`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`.
#### NPM ####
You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project.
You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path.
Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
```
The CommonJS syntax is as follows:
```
import localName = require('npmName');
```
#### Direct copy/symlink ####
You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows:
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
The CommonJS syntax is as follows:
```
import localName = require('./symlinkDir')';
```

View File

@ -0,0 +1,619 @@
import * as querystring from "querystring";
import * as url from "url";
import * as isomorphicFetch from "isomorphic-fetch";
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
export class BaseAPI {
basePath: string;
fetch: FetchAPI;
constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) {
this.basePath = basePath;
this.fetch = fetch;
}
}
export interface Category {
"id"?: number;
"name"?: string;
}
export interface Order {
"id"?: number;
"petId"?: number;
"quantity"?: number;
"shipDate"?: Date;
/**
* Order Status
*/
"status"?: OrderStatusEnum;
"complete"?: boolean;
}
export type OrderStatusEnum = "placed" | "approved" | "delivered";
export interface Pet {
"id"?: number;
"category"?: Category;
"name": string;
"photoUrls": Array<string>;
"tags"?: Array<Tag>;
/**
* pet status in the store
*/
"status"?: PetStatusEnum;
}
export type PetStatusEnum = "available" | "pending" | "sold";
export interface Tag {
"id"?: number;
"name"?: string;
}
export interface User {
"id"?: number;
"username"?: string;
"firstName"?: string;
"lastName"?: string;
"email"?: string;
"password"?: string;
"phone"?: string;
/**
* User Status
*/
"userStatus"?: number;
}
export class PetApi extends BaseAPI {
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
addPet(params: { body?: Pet; }): Promise<any> {
const baseUrl = `${this.basePath}/pet`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
deletePet(params: { petId: number; apiKey?: string; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling deletePet");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
*/
findPetsByStatus(params: { status?: Array<string>; }): Promise<Array<Pet>> {
const baseUrl = `${this.basePath}/pet/findByStatus`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = Object.assign({}, urlObj.query, {
"status": params.status,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
findPetsByTags(params: { tags?: Array<string>; }): Promise<Array<Pet>> {
const baseUrl = `${this.basePath}/pet/findByTags`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = Object.assign({}, urlObj.query, {
"tags": params.tags,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
getPetById(params: { petId: number; }): Promise<Pet> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling getPetById");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
updatePet(params: { body?: Pet; }): Promise<any> {
const baseUrl = `${this.basePath}/pet`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "PUT" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling updatePetWithForm");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
fetchOptions.body = querystring.stringify({
"name": params.name,
"status": params.status,
});
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling uploadFile");
}
const baseUrl = `${this.basePath}/pet/{petId}/uploadImage`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
fetchOptions.body = querystring.stringify({
"additionalMetadata": params.additionalMetadata,
"file": params.file,
});
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
}
export class StoreApi extends BaseAPI {
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
deleteOrder(params: { orderId: string; }): Promise<any> {
// verify required parameter "orderId" is set
if (params["orderId"] == null) {
throw new Error("Missing required parameter orderId when calling deleteOrder");
}
const baseUrl = `${this.basePath}/store/order/{orderId}`
.replace(`{${"orderId"}}`, `${ params.orderId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
getInventory(): Promise<{ [key: string]: number; }> {
const baseUrl = `${this.basePath}/store/inventory`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
getOrderById(params: { orderId: string; }): Promise<Order> {
// verify required parameter "orderId" is set
if (params["orderId"] == null) {
throw new Error("Missing required parameter orderId when calling getOrderById");
}
const baseUrl = `${this.basePath}/store/order/{orderId}`
.replace(`{${"orderId"}}`, `${ params.orderId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
placeOrder(params: { body?: Order; }): Promise<Order> {
const baseUrl = `${this.basePath}/store/order`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
}
export class UserApi extends BaseAPI {
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
createUser(params: { body?: User; }): Promise<any> {
const baseUrl = `${this.basePath}/user`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
createUsersWithArrayInput(params: { body?: Array<User>; }): Promise<any> {
const baseUrl = `${this.basePath}/user/createWithArray`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
createUsersWithListInput(params: { body?: Array<User>; }): Promise<any> {
const baseUrl = `${this.basePath}/user/createWithList`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
deleteUser(params: { username: string; }): Promise<any> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling deleteUser");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
getUserByName(params: { username: string; }): Promise<User> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling getUserByName");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
loginUser(params: { username?: string; password?: string; }): Promise<string> {
const baseUrl = `${this.basePath}/user/login`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = Object.assign({}, urlObj.query, {
"username": params.username,
"password": params.password,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Logs out current logged in user session
*
*/
logoutUser(): Promise<any> {
const baseUrl = `${this.basePath}/user/logout`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
updateUser(params: { username: string; body?: User; }): Promise<any> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling updateUser");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "PUT" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
}

View File

@ -1,7 +1,6 @@
{
"name": "typescript-fetch-api",
"version": "0.0.0",
"private": true,
"main": "./dist/api.js",
"browser": "./dist/api.js",
"typings": "./dist/api.d.ts",
@ -9,7 +8,7 @@
"isomorphic-fetch": "^2.2.1"
},
"scripts" : {
"install" : "typings install && tsc"
"prepublish" : "typings install && tsc"
},
"devDependencies": {
"typescript": "^1.8.10",

View File

@ -0,0 +1,54 @@
# TypeScript-Fetch
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments:
Environment
* Node.js
* Webpack
* Browserify
Language level
* ES5 - you must have a Promises/A+ library installed
* ES6
Module system
* CommonJS
* ES6 module system
It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Installation ###
`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`.
#### NPM ####
You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project.
You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path.
Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
```
The CommonJS syntax is as follows:
```
import localName = require('npmName');
```
#### Direct copy/symlink ####
You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows:
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
The CommonJS syntax is as follows:
```
import localName = require('./symlinkDir')';
```

View File

@ -0,0 +1,620 @@
import * as querystring from "querystring";
import * as url from "url";
import * as isomorphicFetch from "isomorphic-fetch";
import * as assign from "core-js/library/fn/object/assign";
interface Dictionary<T> { [index: string]: T; }
export interface FetchAPI { (url: string, init?: any): Promise<any>; }
export class BaseAPI {
basePath: string;
fetch: FetchAPI;
constructor(basePath: string = "http://petstore.swagger.io/v2", fetch: FetchAPI = isomorphicFetch) {
this.basePath = basePath;
this.fetch = fetch;
}
}
export interface Category {
"id"?: number;
"name"?: string;
}
export interface Order {
"id"?: number;
"petId"?: number;
"quantity"?: number;
"shipDate"?: Date;
/**
* Order Status
*/
"status"?: OrderStatusEnum;
"complete"?: boolean;
}
export type OrderStatusEnum = "placed" | "approved" | "delivered";
export interface Pet {
"id"?: number;
"category"?: Category;
"name": string;
"photoUrls": Array<string>;
"tags"?: Array<Tag>;
/**
* pet status in the store
*/
"status"?: PetStatusEnum;
}
export type PetStatusEnum = "available" | "pending" | "sold";
export interface Tag {
"id"?: number;
"name"?: string;
}
export interface User {
"id"?: number;
"username"?: string;
"firstName"?: string;
"lastName"?: string;
"email"?: string;
"password"?: string;
"phone"?: string;
/**
* User Status
*/
"userStatus"?: number;
}
export class PetApi extends BaseAPI {
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
addPet(params: { body?: Pet; }): Promise<any> {
const baseUrl = `${this.basePath}/pet`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
deletePet(params: { petId: number; apiKey?: string; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling deletePet");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
*/
findPetsByStatus(params: { status?: Array<string>; }): Promise<Array<Pet>> {
const baseUrl = `${this.basePath}/pet/findByStatus`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = assign({}, urlObj.query, {
"status": params.status,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
findPetsByTags(params: { tags?: Array<string>; }): Promise<Array<Pet>> {
const baseUrl = `${this.basePath}/pet/findByTags`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = assign({}, urlObj.query, {
"tags": params.tags,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
getPetById(params: { petId: number; }): Promise<Pet> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling getPetById");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
updatePet(params: { body?: Pet; }): Promise<any> {
const baseUrl = `${this.basePath}/pet`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "PUT" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
updatePetWithForm(params: { petId: string; name?: string; status?: string; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling updatePetWithForm");
}
const baseUrl = `${this.basePath}/pet/{petId}`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
fetchOptions.body = querystring.stringify({
"name": params.name,
"status": params.status,
});
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): Promise<any> {
// verify required parameter "petId" is set
if (params["petId"] == null) {
throw new Error("Missing required parameter petId when calling uploadFile");
}
const baseUrl = `${this.basePath}/pet/{petId}/uploadImage`
.replace(`{${"petId"}}`, `${ params.petId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" };
fetchOptions.body = querystring.stringify({
"additionalMetadata": params.additionalMetadata,
"file": params.file,
});
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
}
export class StoreApi extends BaseAPI {
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
deleteOrder(params: { orderId: string; }): Promise<any> {
// verify required parameter "orderId" is set
if (params["orderId"] == null) {
throw new Error("Missing required parameter orderId when calling deleteOrder");
}
const baseUrl = `${this.basePath}/store/order/{orderId}`
.replace(`{${"orderId"}}`, `${ params.orderId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
getInventory(): Promise<{ [key: string]: number; }> {
const baseUrl = `${this.basePath}/store/inventory`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
getOrderById(params: { orderId: string; }): Promise<Order> {
// verify required parameter "orderId" is set
if (params["orderId"] == null) {
throw new Error("Missing required parameter orderId when calling getOrderById");
}
const baseUrl = `${this.basePath}/store/order/{orderId}`
.replace(`{${"orderId"}}`, `${ params.orderId }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
placeOrder(params: { body?: Order; }): Promise<Order> {
const baseUrl = `${this.basePath}/store/order`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
}
export class UserApi extends BaseAPI {
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
createUser(params: { body?: User; }): Promise<any> {
const baseUrl = `${this.basePath}/user`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
createUsersWithArrayInput(params: { body?: Array<User>; }): Promise<any> {
const baseUrl = `${this.basePath}/user/createWithArray`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
createUsersWithListInput(params: { body?: Array<User>; }): Promise<any> {
const baseUrl = `${this.basePath}/user/createWithList`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "POST" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
deleteUser(params: { username: string; }): Promise<any> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling deleteUser");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "DELETE" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
getUserByName(params: { username: string; }): Promise<User> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling getUserByName");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
loginUser(params: { username?: string; password?: string; }): Promise<string> {
const baseUrl = `${this.basePath}/user/login`;
let urlObj = url.parse(baseUrl, true);
urlObj.query = assign({}, urlObj.query, {
"username": params.username,
"password": params.password,
});
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
throw response;
}
});
}
/**
* Logs out current logged in user session
*
*/
logoutUser(): Promise<any> {
const baseUrl = `${this.basePath}/user/logout`;
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "GET" };
let contentTypeHeader: Dictionary<string>;
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
updateUser(params: { username: string; body?: User; }): Promise<any> {
// verify required parameter "username" is set
if (params["username"] == null) {
throw new Error("Missing required parameter username when calling updateUser");
}
const baseUrl = `${this.basePath}/user/{username}`
.replace(`{${"username"}}`, `${ params.username }`);
let urlObj = url.parse(baseUrl, true);
let fetchOptions: RequestInit = { method: "PUT" };
let contentTypeHeader: Dictionary<string>;
contentTypeHeader = { "Content-Type": "application/json" };
if (params["body"]) {
fetchOptions.body = JSON.stringify(params["body"] || {});
}
if (contentTypeHeader) {
fetchOptions.headers = contentTypeHeader;
}
return this.fetch(url.format(urlObj), fetchOptions).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
throw response;
}
});
}
}

View File

@ -1,15 +1,15 @@
{
"name": "@swagger/typescript-fetch-petstore",
"version": "0.0.1",
"private": true,
"main": "./dist/api.js",
"browser": "./dist/api.js",
"typings": "./dist/api.d.ts",
"dependencies": {
"core-js": "^2.4.0",
"isomorphic-fetch": "^2.2.1"
},
"scripts" : {
"install" : "typings install && tsc"
"prepublish" : "typings install && tsc"
},
"devDependencies": {
"typescript": "^1.8.10",

View File

@ -2,7 +2,7 @@
"version": false,
"dependencies": {},
"ambientDependencies": {
"es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304",
"core-js": "registry:dt/core-js#0.0.0+20160317120654",
"node": "registry:dt/node#4.0.0+20160423143914",
"isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433"
}

View File

@ -1,44 +0,0 @@
# TypeScript-Fetch
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments:
* Node.JS
* Webpack
* Browserify
It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Installation ###
`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case.
#### NPM repository ###
If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module.
It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
#### NPM install local file ###
You should be able to directly install the module using `npm install file:///codegen_path`.
NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute.
#### direct copy/symlink ###
You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below)
### Usage ###
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
With CommonJS, the following syntaxes are supported:
```
import localName = require('npmName');
import localName = require('./symlinkDir')';
```

View File

@ -1,855 +0,0 @@
import * as querystring from 'querystring';
import * as fetch from 'isomorphic-fetch';
import {assign} from './assign';
export interface Category {
"id"?: number;
"name"?: string;
}
export interface Order {
"id"?: number;
"petId"?: number;
"quantity"?: number;
"shipDate"?: Date;
/**
* Order Status
*/
"status"?: Order.StatusEnum;
"complete"?: boolean;
}
export namespace Order {
export type StatusEnum = 'placed' | 'approved' | 'delivered';
}
export interface Pet {
"id"?: number;
"category"?: Category;
"name": string;
"photoUrls": Array<string>;
"tags"?: Array<Tag>;
/**
* pet status in the store
*/
"status"?: Pet.StatusEnum;
}
export namespace Pet {
export type StatusEnum = 'available' | 'pending' | 'sold';
}
export interface Tag {
"id"?: number;
"name"?: string;
}
export interface User {
"id"?: number;
"username"?: string;
"firstName"?: string;
"lastName"?: string;
"email"?: string;
"password"?: string;
"phone"?: string;
/**
* User Status
*/
"userStatus"?: number;
}
//export namespace {
'use strict';
export class PetApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling deletePet');
}
headerParams['api_key'] = params.apiKey;
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus (params: { status?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByStatus';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.status !== undefined) {
queryParameters['status'] = params.status;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
public findPetsByTags (params: { tags?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByTags';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.tags !== undefined) {
queryParameters['tags'] = params.tags;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Pet> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling getPetById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling updatePetWithForm');
}
formParams['name'] = params.name;
formParams['status'] = params.status;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling uploadFile');
}
formParams['additionalMetadata'] = params.additionalMetadata;
formParams['file'] = params.file;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class StoreApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling deleteOrder');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> {
const localVarPath = this.basePath + '/store/inventory';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling getOrderById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class UserApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithArrayInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithArray';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithListInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithList';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling deleteUser');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<User> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling getUserByName');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<string> {
const localVarPath = this.basePath + '/user/login';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.username !== undefined) {
queryParameters['username'] = params.username;
}
if (params.password !== undefined) {
queryParameters['password'] = params.password;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Logs out current logged in user session
*
*/
public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/logout';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling updateUser');
}
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}

View File

@ -1,18 +0,0 @@
export function assign (target: any, ...args: any[]) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (let source of args) {
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};

View File

@ -1,44 +0,0 @@
# TypeScript-Fetch
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments:
* Node.JS
* Webpack
* Browserify
It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Installation ###
`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case.
#### NPM repository ###
If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module.
It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
#### NPM install local file ###
You should be able to directly install the module using `npm install file:///codegen_path`.
NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute.
#### direct copy/symlink ###
You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below)
### Usage ###
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
With CommonJS, the following syntaxes are supported:
```
import localName = require('npmName');
import localName = require('./symlinkDir')';
```

View File

@ -1,855 +0,0 @@
import * as querystring from 'querystring';
import * as fetch from 'isomorphic-fetch';
import {assign} from './assign';
export interface Category {
"id"?: number;
"name"?: string;
}
export interface Order {
"id"?: number;
"petId"?: number;
"quantity"?: number;
"shipDate"?: Date;
/**
* Order Status
*/
"status"?: Order.StatusEnum;
"complete"?: boolean;
}
export namespace Order {
export type StatusEnum = 'placed' | 'approved' | 'delivered';
}
export interface Pet {
"id"?: number;
"category"?: Category;
"name": string;
"photoUrls": Array<string>;
"tags"?: Array<Tag>;
/**
* pet status in the store
*/
"status"?: Pet.StatusEnum;
}
export namespace Pet {
export type StatusEnum = 'available' | 'pending' | 'sold';
}
export interface Tag {
"id"?: number;
"name"?: string;
}
export interface User {
"id"?: number;
"username"?: string;
"firstName"?: string;
"lastName"?: string;
"email"?: string;
"password"?: string;
"phone"?: string;
/**
* User Status
*/
"userStatus"?: number;
}
//export namespace {
'use strict';
export class PetApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling deletePet');
}
headerParams['api_key'] = params.apiKey;
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus (params: { status?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByStatus';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.status !== undefined) {
queryParameters['status'] = params.status;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
public findPetsByTags (params: { tags?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByTags';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.tags !== undefined) {
queryParameters['tags'] = params.tags;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Pet> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling getPetById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling updatePetWithForm');
}
formParams['name'] = params.name;
formParams['status'] = params.status;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling uploadFile');
}
formParams['additionalMetadata'] = params.additionalMetadata;
formParams['file'] = params.file;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class StoreApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling deleteOrder');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> {
const localVarPath = this.basePath + '/store/inventory';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling getOrderById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class UserApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithArrayInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithArray';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithListInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithList';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling deleteUser');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<User> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling getUserByName');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<string> {
const localVarPath = this.basePath + '/user/login';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.username !== undefined) {
queryParameters['username'] = params.username;
}
if (params.password !== undefined) {
queryParameters['password'] = params.password;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Logs out current logged in user session
*
*/
public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/logout';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling updateUser');
}
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}

View File

@ -1,18 +0,0 @@
export function assign (target: any, ...args: any[]) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (let source of args) {
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};

View File

@ -1,10 +0,0 @@
{
"private": true,
"dependencies": {
"isomorphic-fetch": "^2.2.1"
},
"devDependencies": {
"typescript": "^1.8.10",
"typings": "^0.8.1"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,26 @@
{
"private": true,
"dependencies": {
"chai": "^3.5.0"
},
"devDependencies": {
"browserify": "^13.0.1",
"ts-loader": "^0.8.2",
"tsify": "^0.15.5",
"typescript": "^1.8.10",
"typings": "^0.8.1",
"webpack": "^1.13.0"
},
"scripts": {
"prepublish": "./scripts/prepublish.sh",
"test": "mocha"
},
"name": "typescript-fetch-test",
"version": "1.0.0",
"directories": {
"test": "test"
},
"author": "",
"license": "ISC",
"description": ""
}

View File

@ -0,0 +1,26 @@
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script>
mocha.setup({
ui: 'bdd',
timeout: 10000
});
</script>
<script src="./dist/test.browserify-bundle.js"></script>
<script>
mocha.checkLeaks();
mocha.globals(['jQuery']);
mocha.run();
</script>
</body>
</html>

View File

@ -0,0 +1,27 @@
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet" />
</head>
<body>
<div id="mocha"></div>
<script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>
<script>
mocha.setup({
ui: 'bdd',
timeout: 10000
});
</script>
<script src="./dist/vendor.bundle.js"></script>
<script src="./dist/test.bundle.js"></script>
<script>
mocha.checkLeaks();
mocha.globals(['jQuery']);
mocha.run();
</script>
</body>
</html>

View File

@ -0,0 +1,13 @@
#!/bin/bash
npm install ../../builds/default
typings install
# Build Node.js
tsc
# Build Webpack
webpack
# Build browserify
browserify test -p [ tsify ] > ./dist/test.browserify-bundle.js

View File

@ -0,0 +1,65 @@
import {expect} from 'chai';
import * as Swagger from 'typescript-fetch-api';
describe('PetApi', () => {
let api: Swagger.PetApi;
let fixture: Swagger.Pet = createTestFixture();
beforeEach(() => {
api = new Swagger.PetApi();
});
it('should add and delete Pet', () => {
return api.addPet({ body: fixture }).then(() => {
});
});
it('should get Pet by ID', () => {
return api.getPetById({ petId: fixture.id }).then((result) => {
return expect(result).to.deep.equal(fixture);
});
});
it('should update Pet by ID', () => {
return api.getPetById({ petId: fixture.id }).then( (result) => {
result.name = 'newname';
return api.updatePet({ body: result }).then(() => {
return api.getPetById({ petId: fixture.id }).then( (result) => {
return expect(result.name).to.deep.equal('newname');
});
});
});
});
it('should delete Pet', () => {
return api.deletePet({ petId: fixture.id });
});
it('should not contain deleted Pet', () => {
return api.getPetById({ petId: fixture.id }).then((result) => {
return expect(result).to.not.exist;
}, (err) => {
console.log(err)
return expect(err).to.exist;
});
});
});
function createTestFixture(ts = Date.now()) {
const category: Swagger.Category = {
'id': ts,
'name': `category${ts}`,
};
const pet: Swagger.Pet = {
'id': ts,
'name': `pet${ts}`,
'category': category,
'photoUrls': ['http://foo.bar.com/1', 'http://foo.bar.com/2'],
'status': 'available',
'tags': []
};
return pet;
};

View File

@ -0,0 +1,18 @@
import {expect} from 'chai';
import * as Swagger from 'typescript-fetch-api';
describe('StoreApi', function() {
let api: Swagger.StoreApi;
beforeEach(function() {
api = new Swagger.StoreApi();
});
it('should get inventory', function() {
return api.getInventory().then((result) => {
expect(Object.keys(result)).to.not.be.empty;
});
});
});

View File

@ -0,0 +1,2 @@
import './PetApi';
import './StoreApi';

View File

@ -0,0 +1 @@
--timeout 10000 dist/test

View File

@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": true,
"sourceMap": false,
"outDir": "dist",
"rootDir": "."
},
"exclude": [
"node_modules",
"typings/browser",
"typings/main",
"typings/main.d.ts"
]
}

View File

@ -0,0 +1,9 @@
{
"name": "typescript-fetch-test",
"version": false,
"ambientDependencies": {
"chai": "registry:dt/chai#3.4.0+20160317120654",
"es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304",
"mocha": "registry:dt/mocha#2.2.5+20160317120654"
}
}

View File

@ -0,0 +1,30 @@
const webpack = require('webpack');
module.exports = {
entry: {
app: './test/index.ts',
vendor: [
// libraries
'typescript-fetch-api'
],
},
output: {
filename: './dist/test.webpack-bundle.js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */'vendor', /* filename= */'./dist/vendor.webpack-bundle.js')
],
resolve: {
// Add `.ts` and `.tsx` as a resolvable extension.
extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
},
module: {
loaders: [
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
{
test: /\.tsx?$/,
loader: 'ts-loader'
}
]
}
};

View File

@ -1,11 +0,0 @@
{
"compilerOptions": {
"target": "es5"
},
"exclude": [
"node_modules",
"typings/browser",
"typings/main",
"typings/main.d.ts"
]
}

View File

@ -1,9 +0,0 @@
{
"version": false,
"dependencies": {},
"ambientDependencies": {
"es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304",
"node": "registry:dt/node#4.0.0+20160423143914",
"isomorphic-fetch": "github:leonyu/DefinitelyTyped/isomorphic-fetch/isomorphic-fetch.d.ts#isomorphic-fetch-fix-module"
}
}

View File

@ -1,44 +0,0 @@
# TypeScript-Fetch
This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The codegen Node module can be used in the following environments:
* Node.JS
* Webpack
* Browserify
It is usable in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `typings` in `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html))
### Installation ###
`swagger-codegen` does not generate JavaScript directly. The codegen Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile. The self-compile is normally run automatically via the `npm` `postinstall` script of `npm install`.
CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` may skip `postinstall` script if the user is `root`. You would need to manually invoke `npm install` or `npm run postinstall` for the codegen module if that's the case.
#### NPM repository ###
If you remove `"private": true` from `package.json`, you may publish the module to NPM. In which case, you would be able to install the module as any other NPM module.
It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope).
#### NPM install local file ###
You should be able to directly install the module using `npm install file:///codegen_path`.
NOTES: If you do `npm install file:///codegen_path --save` NPM might convert your path to relative path, maybe have adverse affect. `npm install` and `npm shrinkwrap` may misbehave if the installation path is not absolute.
#### direct copy/symlink ###
You may also simply copy or symlink the codegen into a directly under your project. The syntax of the usage would differ if you take this route. (See below)
### Usage ###
With ES6 module syntax, the following syntaxes are supported:
```
import * as localName from 'npmName';
import {operationId} from 'npmName';
import * as localName from './symlinkDir';
import {operationId} from './symlinkDir';
```
With CommonJS, the following syntaxes are supported:
```
import localName = require('npmName');
import localName = require('./symlinkDir')';
```

View File

@ -1,855 +0,0 @@
import * as querystring from 'querystring';
import * as fetch from 'isomorphic-fetch';
import {assign} from './assign';
export interface Category {
"id"?: number;
"name"?: string;
}
export interface Order {
"id"?: number;
"petId"?: number;
"quantity"?: number;
"shipDate"?: Date;
/**
* Order Status
*/
"status"?: Order.StatusEnum;
"complete"?: boolean;
}
export namespace Order {
export type StatusEnum = 'placed' | 'approved' | 'delivered';
}
export interface Pet {
"id"?: number;
"category"?: Category;
"name": string;
"photoUrls": Array<string>;
"tags"?: Array<Tag>;
/**
* pet status in the store
*/
"status"?: Pet.StatusEnum;
}
export namespace Pet {
export type StatusEnum = 'available' | 'pending' | 'sold';
}
export interface Tag {
"id"?: number;
"name"?: string;
}
export interface User {
"id"?: number;
"username"?: string;
"firstName"?: string;
"lastName"?: string;
"email"?: string;
"password"?: string;
"phone"?: string;
/**
* User Status
*/
"userStatus"?: number;
}
//export namespace {
'use strict';
export class PetApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
*/
public addPet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
*/
public deletePet (params: { petId: number; apiKey?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling deletePet');
}
headerParams['api_key'] = params.apiKey;
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma seperated strings
* @param status Status values that need to be considered for filter
*/
public findPetsByStatus (params: { status?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByStatus';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.status !== undefined) {
queryParameters['status'] = params.status;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
*/
public findPetsByTags (params: { tags?: Array<string>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Array<Pet>> {
const localVarPath = this.basePath + '/pet/findByTags';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.tags !== undefined) {
queryParameters['tags'] = params.tags;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
* @param petId ID of pet that needs to be fetched
*/
public getPetById (params: { petId: number; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Pet> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling getPetById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
*/
public updatePet (params: { body?: Pet; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Updates a pet in the store with form data
*
* @param petId ID of pet that needs to be updated
* @param name Updated name of the pet
* @param status Updated status of the pet
*/
public updatePetWithForm (params: { petId: string; name?: string; status?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling updatePetWithForm');
}
formParams['name'] = params.name;
formParams['status'] = params.status;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
*/
public uploadFile (params: { petId: number; additionalMetadata?: string; file?: any; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/pet/{petId}/uploadImage'
.replace('{' + 'petId' + '}', String(params.petId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let formParams: any = {};
headerParams['Content-Type'] = 'application/x-www-form-urlencoded';
// verify required parameter 'petId' is set
if (params.petId == null) {
throw new Error('Missing required parameter petId when calling uploadFile');
}
formParams['additionalMetadata'] = params.additionalMetadata;
formParams['file'] = params.file;
let fetchParams = {
method: 'POST',
headers: headerParams,
body: querystring.stringify(formParams),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class StoreApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
* @param orderId ID of the order that needs to be deleted
*/
public deleteOrder (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling deleteOrder');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*/
public getInventory (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{ [key: string]: number; }> {
const localVarPath = this.basePath + '/store/inventory';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generated exceptions
* @param orderId ID of pet that needs to be fetched
*/
public getOrderById (params: { orderId: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order/{orderId}'
.replace('{' + 'orderId' + '}', String(params.orderId));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'orderId' is set
if (params.orderId == null) {
throw new Error('Missing required parameter orderId when calling getOrderById');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
*/
public placeOrder (params: { body?: Order; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<Order> {
const localVarPath = this.basePath + '/store/order';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}
//export namespace {
'use strict';
export class UserApi {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders : any = {};
constructor(basePath?: string) {
if (basePath) {
this.basePath = basePath;
}
}
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
*/
public createUser (params: { body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithArrayInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithArray';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Creates list of users with given input array
*
* @param body List of user object
*/
public createUsersWithListInput (params: { body?: Array<User>; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/createWithList';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
let fetchParams = {
method: 'POST',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
*/
public deleteUser (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling deleteUser');
}
let fetchParams = {
method: 'DELETE',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
*/
public getUserByName (params: { username: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<User> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling getUserByName');
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
*/
public loginUser (params: { username?: string; password?: string; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<string> {
const localVarPath = this.basePath + '/user/login';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
if (params.username !== undefined) {
queryParameters['username'] = params.username;
}
if (params.password !== undefined) {
queryParameters['password'] = params.password;
}
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Logs out current logged in user session
*
*/
public logoutUser (params: { }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/logout';
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
let fetchParams = {
method: 'GET',
headers: headerParams,
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param body Updated user object
*/
public updateUser (params: { username: string; body?: User; }, extraQueryParams?: any, extraFetchParams?: any ) : Promise<{}> {
const localVarPath = this.basePath + '/user/{username}'
.replace('{' + 'username' + '}', String(params.username));
let queryParameters: any = assign({}, extraQueryParams);
let headerParams: any = assign({}, this.defaultHeaders);
headerParams['Content-Type'] = 'application/json';
// verify required parameter 'username' is set
if (params.username == null) {
throw new Error('Missing required parameter username when calling updateUser');
}
let fetchParams = {
method: 'PUT',
headers: headerParams,
body: JSON.stringify(params.body),
};
if (extraFetchParams) {
fetchParams = assign(fetchParams, extraFetchParams);
}
let localVarPathWithQueryParameters = localVarPath + (localVarPath.indexOf('?') !== -1 ? '&' : '?') + querystring.stringify(queryParameters);
return fetch(localVarPathWithQueryParameters, fetchParams).then((response) => {
if (response.status >= 200 && response.status < 300) {
return response.json();
} else {
let error = new Error(response.statusText);
(error as any).response = response;
throw error;
}
});
}
}
//}

View File

@ -1,18 +0,0 @@
export function assign (target: any, ...args: any[]) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (let source of args) {
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};

View File

@ -1,52 +0,0 @@
#!/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 crediential 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'