first commit

This commit is contained in:
William Cheng
2023-01-23 01:12:10 +08:00
parent 828309d74a
commit eddca32366
75 changed files with 6013 additions and 2817 deletions

View File

@@ -1,5 +1,6 @@
generatorName: typescript-koa-server
outputDir: samples/server/petstore/typescript-koa-server
#outputDir: /Users/williamcheng/Code/typescript/PetStore
inputSpec: modules/openapi-generator/src/test/resources/3_0/typescript-koa-server/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/typescript-koa-server
additionalProperties:

View File

@@ -126,7 +126,6 @@ public class TypeScriptKoaServerCodegen extends AbstractTypeScriptClientCodegen
providedInOptions.put(PROVIDED_IN_LEVEL.any.toString(), "Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.");
providedInCliOpt.setEnum(providedInOptions);
this.cliOptions.add(providedInCliOpt);
this.cliOptions.add(new CliOption(NG_VERSION, "The version of Angular. (At least 9.0.0)").defaultValue(this.ngVersion));
this.cliOptions.add(new CliOption(API_MODULE_PREFIX, "The prefix of the generated ApiModule."));
this.cliOptions.add(new CliOption(CONFIGURATION_PREFIX, "The prefix of the generated Configuration."));
this.cliOptions.add(new CliOption(SERVICE_SUFFIX, "The suffix of the generated service.").defaultValue(this.serviceSuffix));
@@ -167,81 +166,46 @@ public class TypeScriptKoaServerCodegen extends AbstractTypeScriptClientCodegen
supportingFiles.add(new SupportingFile("package.mustache", "", "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json"));
supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts"));
supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts"));
supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts"));
supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts"));
supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts"));
supportingFiles.add(new SupportingFile("encoder.mustache", getIndexDirectory(), "encoder.ts"));
supportingFiles.add(new SupportingFile("param.mustache", getIndexDirectory(), "param.ts"));
// app/session folder
supportingFiles.add(new SupportingFile("sessions.service.ts.mustache", "app" + File.separator + "services", "sessions.service.ts"));
supportingFiles.add(new SupportingFile("sessions.index.ts.mustache", "app" + File.separator + "ervices", "index.ts"));
// app/helpers folder
supportingFiles.add(new SupportingFile("client.ts.mustache", "app" + File.separator + "helpers", "client.ts"));
// app/jobs folder
supportingFiles.add(new SupportingFile("jobs.README.mustache", "app" + File.separator + "jobs", "README.md"));
// app/controllers
supportingFiles.add(new SupportingFile("index.ts.mustache", "app" + File.separator + "controllers", "index.ts"));
supportingFiles.add(new SupportingFile("sessions.controller.ts.mustache", "app" + File.separator + "controllers", "sessions.controller.ts"));
// app/controllers/__tests__
supportingFiles.add(new SupportingFile("session.test.js.mustache", "app" + File.separator + "controllers" + File.separator + "__tests__", "session.test.js"));
// configs
supportingFiles.add(new SupportingFile("application.ts.mustache", "configs", "application.ts"));
supportingFiles.add(new SupportingFile("bootstrap.ts.mustache", "configs", "bootstrap.ts"));
supportingFiles.add(new SupportingFile("interceptors.ts.mustache", "configs", "interceptors.ts"));
supportingFiles.add(new SupportingFile("koa.middlewares.ts.mustache", "configs", "koa.middlewares.ts"));
supportingFiles.add(new SupportingFile("routing.middlewares.ts.mustache", "configs", "routing.middlewares.ts"));
supportingFiles.add(new SupportingFile("routing.options.ts.mustache", "configs", "routing.options.ts"));
supportingFiles.add(new SupportingFile("utils.ts.mustache", "configs", "utils.ts"));
// configs/constants
supportingFiles.add(new SupportingFile("development.ts.mustache", "configs" + File.separator + "constants", "development.ts"));
supportingFiles.add(new SupportingFile("envs.ts.mustache", "configs" + File.separator + "constants", "envs.ts"));
supportingFiles.add(new SupportingFile("configs.constants.index.ts.mustache", "configs" + File.separator + "constants", "index.ts"));
supportingFiles.add(new SupportingFile("production.ts.mustache", "configs" + File.separator + "constants", "production.ts"));
supportingFiles.add(new SupportingFile("staging.ts.mustache", "configs" + File.separator + "constants", "staging.ts"));
// prisma
supportingFiles.add(new SupportingFile("schema.prisma.mustache", "prisma", "schema.prisma"));
supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("README.mustache", getIndexDirectory(), "README.md"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("package.mustache", getIndexDirectory(), "package.json"));
supportingFiles.add(new SupportingFile("tsconfig.mustache", getIndexDirectory(), "tsconfig.json"));
// determine NG version
SemVer ngVersion;
if (additionalProperties.containsKey(NG_VERSION)) {
ngVersion = new SemVer(additionalProperties.get(NG_VERSION).toString());
} else {
ngVersion = new SemVer(this.ngVersion);
LOGGER.info("generating code for Angular {} ...", ngVersion);
LOGGER.info(" (you can select the angular version by setting the additionalProperties (--additional-properties in CLI) ngVersion)");
}
if (!ngVersion.atLeast("9.0.0")) {
throw new IllegalArgumentException("Invalid ngVersion: " + ngVersion + ". Only Angular v9+ is supported.");
}
if (additionalProperties.containsKey(STRING_ENUMS)) {
setStringEnums(Boolean.parseBoolean(additionalProperties.get(STRING_ENUMS).toString()));
additionalProperties.put("stringEnums", getStringEnums());
if (getStringEnums()) {
classEnumSeparator = "";
}
}
if (additionalProperties.containsKey(WITH_INTERFACES)) {
boolean withInterfaces = Boolean.parseBoolean(additionalProperties.get(WITH_INTERFACES).toString());
if (withInterfaces) {
apiTemplateFiles.put("apiInterface.mustache", "Interface.ts");
}
}
if (additionalProperties.containsKey(USE_SINGLE_REQUEST_PARAMETER)) {
this.setUseSingleRequestParameter(convertPropertyToBoolean(USE_SINGLE_REQUEST_PARAMETER));
}
writePropertyBack(USE_SINGLE_REQUEST_PARAMETER, getUseSingleRequestParameter());
if (additionalProperties.containsKey(TAGGED_UNIONS)) {
taggedUnions = Boolean.parseBoolean(additionalProperties.get(TAGGED_UNIONS).toString());
}
if (additionalProperties.containsKey(PROVIDED_IN)) {
setProvidedIn(additionalProperties.get(PROVIDED_IN).toString());
}
additionalProperties.put("providedIn", providedIn);
additionalProperties.put("isProvidedInNone", getIsProvidedInNone());
additionalProperties.put(ENFORCE_GENERIC_MODULE_WITH_PROVIDERS, true);
if (ngVersion.atLeast("12.0.0")) {
additionalProperties.put(HTTP_CONTEXT_IN_OPTIONS, true);
}
additionalProperties.put(NG_VERSION, ngVersion);
if (additionalProperties.containsKey(API_MODULE_PREFIX)) {
String apiModulePrefix = additionalProperties.get(API_MODULE_PREFIX).toString();
validateClassPrefixArgument("ApiModule", apiModulePrefix);
additionalProperties.put("apiModuleClassName", apiModulePrefix + "ApiModule");
} else {
additionalProperties.put("apiModuleClassName", "ApiModule");
}
if (additionalProperties.containsKey(CONFIGURATION_PREFIX)) {
String configurationPrefix = additionalProperties.get(CONFIGURATION_PREFIX).toString();
validateClassPrefixArgument("Configuration", configurationPrefix);
@@ -252,32 +216,6 @@ public class TypeScriptKoaServerCodegen extends AbstractTypeScriptClientCodegen
additionalProperties.put("configurationClassName", "Configuration");
additionalProperties.put("configurationParametersInterfaceName", "ConfigurationParameters");
}
if (additionalProperties.containsKey(SERVICE_SUFFIX)) {
serviceSuffix = additionalProperties.get(SERVICE_SUFFIX).toString();
validateClassSuffixArgument("Service", serviceSuffix);
}
if (additionalProperties.containsKey(SERVICE_FILE_SUFFIX)) {
serviceFileSuffix = additionalProperties.get(SERVICE_FILE_SUFFIX).toString();
validateFileSuffixArgument("Service", serviceFileSuffix);
}
if (additionalProperties.containsKey(MODEL_SUFFIX)) {
modelSuffix = additionalProperties.get(MODEL_SUFFIX).toString();
validateClassSuffixArgument("Model", modelSuffix);
}
if (additionalProperties.containsKey(MODEL_FILE_SUFFIX)) {
modelFileSuffix = additionalProperties.get(MODEL_FILE_SUFFIX).toString();
validateFileSuffixArgument("Model", modelFileSuffix);
}
if (additionalProperties.containsKey(FILE_NAMING)) {
this.setFileNaming(additionalProperties.get(FILE_NAMING).toString());
}
if (additionalProperties.containsKey(QUERY_PARAM_OBJECT_FORMAT)) {
setQueryParamObjectFormat((String) additionalProperties.get(QUERY_PARAM_OBJECT_FORMAT));
}
additionalProperties.put("isQueryParamObjectFormatDot", getQueryParamObjectFormatDot());
additionalProperties.put("isQueryParamObjectFormatJson", getQueryParamObjectFormatJson());
additionalProperties.put("isQueryParamObjectFormatKey", getQueryParamObjectFormatKey());
}

View File

@@ -1,226 +1,107 @@
## {{npmName}}@{{npmVersion}}
### koa-ts
### Building
The best practice of building Koa2 with TypeScript. [中文](/README_CN.md)
To install the required dependencies and to build the typescript sources run:
```
npm install
npm run build
```
---
### publishing
#### Usage
First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!)
1. Run `npm init koa-ts`
### consuming
2. Install dependencies: `yarn`
Navigate to the folder of your consuming project and run one of next commands.
3. Rename `.env.example` to `.env`, and run `prisma db push` to synchronize the data model
_published:_
4. Start the server: `yarn dev`. visit: http://127.0.0.1:3000/apis/sessions
> **(Optional)** the project has built-in a docker compose, run `yarn dev:db` to run database automatic.
---
#### Project Layout
```
npm install {{npmName}}@{{npmVersion}} --save
├── app
│   ├── controllers --- server controllers
│   ├── helpers --- helper func (interceptor / error handler / validator...)
│   ├── jobs --- task (periodic task / trigger task / email server...)
│   ├── entities --- database entities/models
│   └── services --- adhesive controller and model
├── config
│   ├── constants --- environment variable
│  ├── koa.middlewares --- middlewares for Koa
│  ├── routing.middlewares --- middlewares for Routing Controller
│  ├── routing.options --- configs for Routing Controller
│   ├── bootstrap --- lifecycle
│   └── interceptors --- global interceptor
│   └── utils --- pure functions for help
└── test --- utils for testcase
├── .env --- environment file
```
_without publishing (not recommended):_
---
```
npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save
```
#### Feature
_It's important to take the tgz file, otherwise you'll get trouble with links on windows_
- Separation configuration and business logic.
_using `npm link`:_
- Export scheme model and interface, follow style of TypeScript.
In PATH_TO_GENERATED_PACKAGE/dist:
```
npm link
```
- Test cases and lint configuration.
In your project:
```
npm link {{npmName}}
```
- The best practice for Dependency Injection in Koa project.
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages.
Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround.
Published packages are not effected by this issue.
- Get constraints on your data model with Prisma.
- TypeScript hotload.
#### General usage
---
In your Angular project:
#### Lifecycle
1. `app.ts` -> collect env vars `constants` -> collect env files `variables.env`
```
// without configuring providers
import { {{apiModuleClassName}} } from '{{npmName}}';
import { HttpClientModule } from '@angular/common/http';
2. envs ready, call `bootstrap.before()`
@NgModule({
imports: [
{{apiModuleClassName}},
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
3. lift `routing-controllers` -> lift Koa middlewares -> register `Container` for DI
```
// configuring providers
import { {{apiModuleClassName}}, {{configurationClassName}}, {{configurationParametersInterfaceName}} } from '{{npmName}}';
4. start Koa & invoke `bootstrap.after()` after startup
export function apiConfigFactory (): {{configurationClassName}} {
const params: {{configurationParametersInterfaceName}} = {
// set configuration parameters here.
}
return new {{configurationClassName}}(params);
}
---
@NgModule({
imports: [ {{apiModuleClassName}}.forRoot(apiConfigFactory) ],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### Databases
```
// configuring providers with an authentication service that manages your access tokens
import { {{apiModuleClassName}}, {{configurationClassName}} } from '{{npmName}}';
The project uses Prisma as the intelligent ORM tool by default. Supports `PostgreSQL`, `MySQL` and `SQLite`.
@NgModule({
imports: [ {{apiModuleClassName}} ],
declarations: [ AppComponent ],
providers: [
{
provide: {{configurationClassName}},
useFactory: (authService: AuthService) => new {{configurationClassName}}(
{
basePath: environment.apiUrl,
accessToken: authService.getAccessToken.bind(authService)
}
),
deps: [AuthService],
multi: false
}
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
- You can change the data type and connection method in the `.env` file
- After each modification to file `/prisma/schema.prisma`, you need to run `prisma migrate dev` to migrate the database.
- After each modification to file `/prisma/schema.prisma`, you need to run `prisma generate` to sync types.
```
import { DefaultApi } from '{{npmName}}';
---
export class AppComponent {
constructor(private apiGateway: DefaultApi) { }
}
```
#### About Environments
Note: The {{apiModuleClassName}} is restricted to being instantiated once app wide.
This is to ensure that all services are treated as singletons.
When nodejs is running, `ENV` does not mean `NODE_ENV`:
#### Using multiple OpenAPI files / APIs / {{apiModuleClassName}}s
In order to use multiple `{{apiModuleClassName}}s` generated from different OpenAPI files,
you can create an alias name when importing the modules
in order to avoid naming conflicts:
```
import { {{apiModuleClassName}} } from 'my-api-path';
import { {{apiModuleClassName}} as OtherApiModule } from 'my-other-api-path';
import { HttpClientModule } from '@angular/common/http';
- After NodeJS project is built, we always run it as `NODE_ENV=PRODUCTION`, which may affect some framework optimizations.
- `NODE_ENV` only identifies the NodeJS runtime, independent of the business.
- You should use `ENV` to identify the environment.
@NgModule({
imports: [
{{apiModuleClassName}},
OtherApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
]
})
export class AppModule {
For the data settings of each environment, you can refer to the following:
}
```
- **Development Mode** (`ENV=development`): read configurations from `configs/constants/development.ts` file, but it will still be overwritten by `.env` file.
- **Production Mode** (`ENV=production`): read configurations from `configs/constants/production.ts` file, but it will still be overwritten by `.env` file.
### Set service base path
If different than the generated base path, during app bootstrap, you can provide the base path to your service.
---
```
import { BASE_PATH } from '{{npmName}}';
#### Reference
bootstrap(AppComponent, [
{ provide: BASE_PATH, useValue: 'https://your-web-service.com' },
]);
```
or
- [routing-controllers](https://github.com/typestack/routing-controllers)
- [Prisma](https://www.prisma.io/docs/concepts)
```
import { BASE_PATH } from '{{npmName}}';
---
@NgModule({
imports: [],
declarations: [ AppComponent ],
providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### LICENSE
#### Using @angular/cli
First extend your `src/environments/*.ts` files by adding the corresponding base path:
```
export const environment = {
production: false,
API_BASE_PATH: 'http://127.0.0.1:8080'
};
```
In the src/app/app.module.ts:
```
import { BASE_PATH } from '{{npmName}}';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [ ],
providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],
bootstrap: [ AppComponent ]
})
export class AppModule { }
```
### Customizing path parameter encoding
Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple'
and Dates for format 'date-time' are encoded correctly.
Other styles (e.g. "matrix") are not that easy to encode
and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]).
To implement your own parameter encoding (or call another library),
pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object
(see [General Usage](#general-usage) above).
Example value for use in your Configuration-Provider:
```typescript
new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param),
})
```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values
[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander
This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more info.

View File

@@ -0,0 +1,20 @@
import 'reflect-metadata'
import Koa from 'koa'
import { Container } from 'typedi'
import { routingConfigs } from './routing.options'
import { useMiddlewares } from './koa.middlewares'
import { useKoaServer, useContainer } from 'routing-controllers'
const createServer = async (): Promise<Koa> => {
const koa: Koa = new Koa()
useMiddlewares(koa)
useContainer(Container)
const app: Koa = useKoaServer<Koa>(koa, routingConfigs)
return app
}
export default createServer

View File

@@ -0,0 +1,18 @@
import { join } from 'path'
import { print } from './utils'
import dotenv from 'dotenv'
// "before" will trigger before the app lift.
export const bootstrapBefore = (): object => {
// solve ncc path link.
const result = dotenv.config({ path: join(__dirname, '../.env') })
if (result.error) {
print.danger('Environment variable not loaded: not found ".env" file.')
return {}
}
print.log('.env loaded.')
return result.parsed
}
// "after" will trigger after the "container" mounted..
export const bootstrapAfter = (): any => {}

View File

@@ -0,0 +1,23 @@
import { PrismaClient } from '@prisma/client'
declare global {
namespace NodeJS {
interface Global {
prisma: PrismaClient
}
}
}
let prisma: PrismaClient
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient()
} else {
if (!global.prisma) {
global.prisma = new PrismaClient()
}
prisma = global.prisma
}
export default prisma

View File

@@ -0,0 +1,54 @@
import { bootstrapBefore } from '../bootstrap'
import development, { EevRecord } from './development'
import staging from './staging'
import production from './production'
import { ENVS } from './envs'
const parsedEnvs = bootstrapBefore()
const getCurrentEnv = (): ENVS => {
const env = process.env?.ENV
if (typeof env === 'undefined') {
console.warn(`/n> ENV is not set, fallback to ${ENVS.DEVELOPMENT}.`)
}
const upperCaseEnv = `${env}`.toUpperCase()
if (upperCaseEnv === ENVS.PRODUCTION) return ENVS.PRODUCTION
if (upperCaseEnv === ENVS.STAGING) return ENVS.STAGING
return ENVS.DEVELOPMENT
}
const getCurrentConstants = (ident: ENVS): EevRecord => {
let constants = development
const source =
ident === ENVS.PRODUCTION
? production
: ident === ENVS.STAGING
? staging
: development
Object.keys(development).forEach(key => {
const sourceValue = source[key]
const processValue = process.env[key]
const parsedValue = parsedEnvs[key]
if (typeof sourceValue !== 'undefined') {
constants[key] = sourceValue
}
if (typeof processValue !== 'undefined') {
constants[key] = processValue
}
if (typeof parsedValue !== 'undefined') {
constants[key] = parsedValue
}
})
constants.ENV_LABEL = source.ENV_LABEL
return constants
}
export const CURRENT_ENV = getCurrentEnv()
export const isProd = () => CURRENT_ENV === ENVS.PRODUCTION
const CONSTANTS = getCurrentConstants(CURRENT_ENV)
export default CONSTANTS

View File

@@ -0,0 +1,9 @@
const development = {
ENV_LABEL: 'DEVELOPMENT',
PORT: 3001,
}
export default development
export type EevRecord = typeof development

View File

@@ -0,0 +1,5 @@
export enum ENVS {
DEVELOPMENT = 'DEVELOPMENT',
STAGING = 'STAGING',
PRODUCTION = 'PRODUCTION',
}

View File

@@ -0,0 +1 @@
export * from './sessions.controller'

View File

@@ -0,0 +1,12 @@
import { InterceptorInterface, Action, Interceptor } from 'routing-controllers'
import { Service } from 'typedi'
@Interceptor()
@Service()
export class AutoAssignJSONInterceptor implements InterceptorInterface {
intercept(action: Action, content: any): any {
if (typeof content === 'object')
return JSON.stringify(Object.assign({ message: 'ok' }, content))
return JSON.stringify({ message: content })
}
}

View File

@@ -0,0 +1,3 @@
## Jobs
You can add scheduled tasks, email tasks, or any third-party work here.

View File

@@ -0,0 +1,14 @@
import Koa from 'koa'
import logger from 'koa-logger'
import bodyParser from 'koa-bodyparser'
import { isProd } from './constants'
export const useMiddlewares = <T extends Koa>(app: T): T => {
if (isProd()) {
app.use(logger())
}
app.use(bodyParser())
return app
}

View File

@@ -1,43 +1,3 @@
{
"name": "{{{npmName}}}",
"version": "{{{npmVersion}}}",
"description": "OpenAPI client for {{{npmName}}}",
"author": "OpenAPI-Generator Contributors",
"repository": {
"type": "git",
"url": "https://{{gitHost}}/{{gitUserId}}/{{gitRepoId}}.git"
},
"keywords": [
"openapi-client",
"openapi-generator"
],
"license": "Unlicense",
"scripts": {
"build": "ng-packagr -p ng-package.json"
},
"peerDependencies": {
"@angular/core": "^{{ngVersion}}",
"rxjs": "^{{rxjsVersion}}"
},
"devDependencies": {
"@angular/common": "^{{ngVersion}}",
"@angular/compiler": "^{{ngVersion}}",
"@angular/compiler-cli": "^{{ngVersion}}",
"@angular/core": "^{{ngVersion}}",
"@angular/platform-browser": "^{{ngVersion}}",
"ng-packagr": "^{{ngPackagrVersion}}",
"reflect-metadata": "^0.1.3",
"rxjs": "^{{rxjsVersion}}",{{#tsickleVersion}}
"tsickle": "^{{tsickleVersion}}",{{/tsickleVersion}}
"typescript": "{{{tsVersion}}}",
"zone.js": "^{{zonejsVersion}}"
}{{#npmRepository}},
"publishConfig": {
"registry": "{{{npmRepository}}}"
}
{{/npmRepository}}
}
{
"name": "{{{npmName}}}",
"version": "{{{npmVersion}}}",

View File

@@ -0,0 +1,7 @@
import { EevRecord } from './development'
const production: Partial<EevRecord> = {
ENV_LABEL: 'PRODUCTION',
}
export default production

View File

@@ -0,0 +1,18 @@
import { KoaMiddlewareInterface, Middleware } from 'routing-controllers'
import { Service } from 'typedi'
@Middleware({ type: 'before' })
@Service()
export class HeaderMiddleware implements KoaMiddlewareInterface {
async use(context: any, next: (err?: any) => any): Promise<any> {
context.set('Access-Control-Allow-Methods', 'GET,HEAD,PUT,POST,DELETE,PATCH')
context.set(
'Access-Control-Allow-Origin',
context.request.header.origin || context.request.origin,
)
context.set('Access-Control-Allow-Headers', ['content-type'])
context.set('Access-Control-Allow-Credentials', 'true')
context.set('Content-Type', 'application/json; charset=utf-8')
return next()
}
}

View File

@@ -0,0 +1,21 @@
import { RoutingControllersOptions } from 'routing-controllers'
import * as controllers from 'app/controllers'
import * as middlewares from './routing.middlewares'
import * as interceptors from './interceptors'
import { dictToArray } from './utils'
export const routingConfigs: RoutingControllersOptions = {
controllers: dictToArray(controllers),
middlewares: dictToArray(middlewares),
interceptors: dictToArray(interceptors),
// router prefix
// e.g. api => http://hostname:port/{routePrefix}/{controller.method}
routePrefix: '/apis',
// auto validate entity item
// learn more: https://github.com/typestack/class-validator
validation: true,
}

View File

@@ -0,0 +1,14 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Session {
id Int @id @default(autoincrement())
name String
createdAt DateTime @default(now())
}

View File

@@ -0,0 +1,19 @@
import server from 'server'
import request from 'supertest'
describe('routers: session', () => {
let app
beforeAll(async () => {
app = await server
})
it('should be return 200 status code', async () => {
const res = await request(app).get('/apis/sessions')
expect(res.status).toEqual(200)
})
afterAll(async done => {
app.close()
done()
})
})

View File

@@ -0,0 +1,31 @@
import {
BadRequestError,
Post,
JsonController,
BodyParam,
Get,
} from 'routing-controllers'
import { SessionsService } from '../services'
import { Prisma } from '@prisma/client'
import { Service } from 'typedi'
@JsonController()
@Service()
export class SessionsController {
constructor(private sessionsService: SessionsService) {}
@Get('/sessions')
async query() {
return []
}
@Post('/sessions')
async create(
@BodyParam('username') name: string,
): Promise<Prisma.SessionGetPayload<any>> {
if (!name) {
throw new BadRequestError('username is required')
}
return await this.sessionsService.create({ name })
}
}

View File

@@ -0,0 +1 @@
export * from './sessions.service'

View File

@@ -0,0 +1,21 @@
import { Service } from 'typedi'
import prisma from 'app/helpers/client'
import { Prisma } from '@prisma/client'
@Service()
export class SessionsService {
/**
* Type 'Prisma.SessionCreateInput' is automatically generated.
* Whenever you modify file 'prisma/schema.prisma' and then run command:
* prisma generate
* prisma migrate dev
* The types is automatically updated.
*
* About CRUD: https://www.prisma.io/docs/concepts/components/prisma-client/crud
*/
async create(session: Prisma.SessionCreateInput) {
return prisma.session.create({
data: session,
})
}
}

View File

@@ -0,0 +1,7 @@
import { EevRecord } from './development'
const staging: Partial<EevRecord> = {
ENV_LABEL: 'STAGING',
}
export default staging

View File

@@ -0,0 +1,8 @@
export const dictToArray = (dict: object): Array<any> =>
Object.keys(dict).map(name => dict[name])
export const print = {
log: (text: string) => console.log('\x1b[37m%s \x1b[2m%s\x1b[0m', '>', text),
danger: (text: string) => console.log('\x1b[31m%s \x1b[31m%s\x1b[0m', '>', text),
tip: (text: string) => console.log('\x1b[36m%s \x1b[36m%s\x1b[0m', '>', text),
}

View File

@@ -0,0 +1,6 @@
ENV=development
POSTGRES_USER=root
POSTGRES_PASSWORD=rootpassword
POSTGRES_DB=dev
POSTGRES_PORT=5432
DATABASE_URL='postgresql://root:rootpassword@localhost:5432/dev?schema=public'

View File

@@ -0,0 +1,18 @@
module.exports = {
verbose: true,
testEnvironment: 'node',
moduleFileExtensions: ['ts', 'js'],
testPathIgnorePatterns: ['/dist/'],
transform: {
'^.+\\.[t|j]s?$': ['ts-jest'],
},
transformIgnorePatterns: ['<rootDir>/node_modules/'],
testRegex: '.*\\.test\\.(j|t)s?$',
moduleNameMapper: {
'tests/(.*)$': '<rootDir>/tests/$1',
'configs/(.*)$': '<rootDir>/configs/$1',
'app/(.*)$': '<rootDir>/app/$1',
server: '<rootDir>/app.ts',
// app: '<rootDir>/app.ts',
},
}

View File

@@ -1,20 +1,40 @@
.env.example
.gitignore
.jest.config.js
README.md
api.module.ts
api/api.ts
api/pet.service.ts
api/store.service.ts
api/user.service.ts
configuration.ts
encoder.ts
app.ts
app/controllers/__tests__/session.test.js
app/controllers/index.ts
app/controllers/sessions.controller.ts
app/helpers/client.ts
app/jobs/README.md
app/services/sessions.service.ts
apps/ervices/index.ts
build.js
configs/application.ts
configs/bootstrap.ts
configs/constants/development.ts
configs/constants/envs.ts
configs/constants/index.ts
configs/constants/production.ts
configs/constants/staging.ts
configs/interceptors.ts
configs/koa.middlewares.ts
configs/routing.middlewares.ts
configs/routing.options.ts
configs/utils.ts
docker-compose.yml
git_push.sh
index.ts
model/apiResponse.ts
model/category.ts
model/models.ts
model/order.ts
model/pet.ts
model/tag.ts
model/user.ts
param.ts
variables.ts
nodemon.json
package.json
prisma/schema.prisma
tsconfig.json

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 - 2021 Witt(@unix)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,226 +1,107 @@
## @
### koa-ts
### Building
The best practice of building Koa2 with TypeScript. [中文](/README_CN.md)
To install the required dependencies and to build the typescript sources run:
```
npm install
npm run build
```
---
### publishing
#### Usage
First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!)
1. Run `npm init koa-ts`
### consuming
2. Install dependencies: `yarn`
Navigate to the folder of your consuming project and run one of next commands.
3. Rename `.env.example` to `.env`, and run `prisma db push` to synchronize the data model
_published:_
4. Start the server: `yarn dev`. visit: http://127.0.0.1:3000/apis/sessions
> **(Optional)** the project has built-in a docker compose, run `yarn dev:db` to run database automatic.
---
#### Project Layout
```
npm install @ --save
├── app
│   ├── controllers --- server controllers
│   ├── helpers --- helper func (interceptor / error handler / validator...)
│   ├── jobs --- task (periodic task / trigger task / email server...)
│   ├── entities --- database entities/models
│   └── services --- adhesive controller and model
├── config
│   ├── constants --- environment variable
│  ├── koa.middlewares --- middlewares for Koa
│  ├── routing.middlewares --- middlewares for Routing Controller
│  ├── routing.options --- configs for Routing Controller
│   ├── bootstrap --- lifecycle
│   └── interceptors --- global interceptor
│   └── utils --- pure functions for help
└── test --- utils for testcase
├── .env --- environment file
```
_without publishing (not recommended):_
---
```
npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save
```
#### Feature
_It's important to take the tgz file, otherwise you'll get trouble with links on windows_
- Separation configuration and business logic.
_using `npm link`:_
- Export scheme model and interface, follow style of TypeScript.
In PATH_TO_GENERATED_PACKAGE/dist:
```
npm link
```
- Test cases and lint configuration.
In your project:
```
npm link
```
- The best practice for Dependency Injection in Koa project.
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages.
Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround.
Published packages are not effected by this issue.
- Get constraints on your data model with Prisma.
- TypeScript hotload.
#### General usage
---
In your Angular project:
#### Lifecycle
1. `app.ts` -> collect env vars `constants` -> collect env files `variables.env`
```
// without configuring providers
import { ApiModule } from '';
import { HttpClientModule } from '@angular/common/http';
2. envs ready, call `bootstrap.before()`
@NgModule({
imports: [
ApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
3. lift `routing-controllers` -> lift Koa middlewares -> register `Container` for DI
```
// configuring providers
import { ApiModule, Configuration, ConfigurationParameters } from '';
4. start Koa &amp; invoke `bootstrap.after()` after startup
export function apiConfigFactory (): Configuration {
const params: ConfigurationParameters = {
// set configuration parameters here.
}
return new Configuration(params);
}
---
@NgModule({
imports: [ ApiModule.forRoot(apiConfigFactory) ],
declarations: [ AppComponent ],
providers: [],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### Databases
```
// configuring providers with an authentication service that manages your access tokens
import { ApiModule, Configuration } from '';
The project uses Prisma as the intelligent ORM tool by default. Supports `PostgreSQL`, `MySQL` and `SQLite`.
@NgModule({
imports: [ ApiModule ],
declarations: [ AppComponent ],
providers: [
{
provide: Configuration,
useFactory: (authService: AuthService) => new Configuration(
{
basePath: environment.apiUrl,
accessToken: authService.getAccessToken.bind(authService)
}
),
deps: [AuthService],
multi: false
}
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
- You can change the data type and connection method in the `.env` file
- After each modification to file `/prisma/schema.prisma`, you need to run `prisma migrate dev` to migrate the database.
- After each modification to file `/prisma/schema.prisma`, you need to run `prisma generate` to sync types.
```
import { DefaultApi } from '';
---
export class AppComponent {
constructor(private apiGateway: DefaultApi) { }
}
```
#### About Environments
Note: The ApiModule is restricted to being instantiated once app wide.
This is to ensure that all services are treated as singletons.
When nodejs is running, `ENV` does not mean `NODE_ENV`:
#### Using multiple OpenAPI files / APIs / ApiModules
In order to use multiple `ApiModules` generated from different OpenAPI files,
you can create an alias name when importing the modules
in order to avoid naming conflicts:
```
import { ApiModule } from 'my-api-path';
import { ApiModule as OtherApiModule } from 'my-other-api-path';
import { HttpClientModule } from '@angular/common/http';
- After NodeJS project is built, we always run it as `NODE_ENV=PRODUCTION`, which may affect some framework optimizations.
- `NODE_ENV` only identifies the NodeJS runtime, independent of the business.
- You should use `ENV` to identify the environment.
@NgModule({
imports: [
ApiModule,
OtherApiModule,
// make sure to import the HttpClientModule in the AppModule only,
// see https://github.com/angular/angular/issues/20575
HttpClientModule
]
})
export class AppModule {
For the data settings of each environment, you can refer to the following:
}
```
- **Development Mode** (`ENV=development`): read configurations from `configs/constants/development.ts` file, but it will still be overwritten by `.env` file.
- **Production Mode** (`ENV=production`): read configurations from `configs/constants/production.ts` file, but it will still be overwritten by `.env` file.
### Set service base path
If different than the generated base path, during app bootstrap, you can provide the base path to your service.
---
```
import { BASE_PATH } from '';
#### Reference
bootstrap(AppComponent, [
{ provide: BASE_PATH, useValue: 'https://your-web-service.com' },
]);
```
or
- [routing-controllers](https://github.com/typestack/routing-controllers)
- [Prisma](https://www.prisma.io/docs/concepts)
```
import { BASE_PATH } from '';
---
@NgModule({
imports: [],
declarations: [ AppComponent ],
providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
```
#### LICENSE
#### Using @angular/cli
First extend your `src/environments/*.ts` files by adding the corresponding base path:
```
export const environment = {
production: false,
API_BASE_PATH: 'http://127.0.0.1:8080'
};
```
In the src/app/app.module.ts:
```
import { BASE_PATH } from '';
import { environment } from '../environments/environment';
@NgModule({
declarations: [
AppComponent
],
imports: [ ],
providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }],
bootstrap: [ AppComponent ]
})
export class AppModule { }
```
### Customizing path parameter encoding
Without further customization, only [path-parameters][parameter-locations-url] of [style][style-values-url] 'simple'
and Dates for format 'date-time' are encoded correctly.
Other styles (e.g. "matrix") are not that easy to encode
and thus are best delegated to other libraries (e.g.: [@honoluluhenk/http-param-expander]).
To implement your own parameter encoding (or call another library),
pass an arrow-function or method-reference to the `encodeParam` property of the Configuration-object
(see [General Usage](#general-usage) above).
Example value for use in your Configuration-Provider:
```typescript
new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param),
})
```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
[style-values-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values
[@honoluluhenk/http-param-expander]: https://www.npmjs.com/package/@honoluluhenk/http-param-expander
This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more info.

View File

@@ -1,33 +0,0 @@
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
import { Configuration } from './configuration';
import { HttpClient } from '@angular/common/http';
import { PetService } from './api/pet.service';
import { StoreService } from './api/store.service';
import { UserService } from './api/user.service';
@NgModule({
imports: [],
declarations: [],
exports: [],
providers: []
})
export class ApiModule {
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
return {
ngModule: ApiModule,
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
};
}
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
@Optional() http: HttpClient) {
if (parentModule) {
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
}
if (!http) {
throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
'See also https://github.com/angular/angular/issues/20575');
}
}
}

View File

@@ -1,7 +0,0 @@
export * from './pet.service';
import { PetService } from './pet.service';
export * from './store.service';
import { StoreService } from './store.service';
export * from './user.service';
import { UserService } from './user.service';
export const APIS = [PetService, StoreService, UserService];

View File

@@ -1,734 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { ApiResponse } from '../model/apiResponse';
// @ts-ignore
import { Pet } from '../model/pet';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable({
providedIn: 'root'
})
export class PetService {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
if (Array.isArray(basePath) && basePath.length > 0) {
basePath = basePath[0];
}
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
/**
* @param consumes string[] mime-types
* @return true: consumes contains 'multipart/form-data', false: otherwise
*/
private canConsumeForm(consumes: string[]): boolean {
const form = 'multipart/form-data';
for (const consume of consumes) {
if (form === consume) {
return true;
}
}
return false;
}
// @ts-ignore
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
* Add a new pet to the store
*
* @param pet Pet object that needs to be added to the store
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public addPet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<Pet>;
public addPet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<Pet>>;
public addPet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<Pet>>;
public addPet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (pet === null || pet === undefined) {
throw new Error('Required parameter pet was null or undefined when calling addPet.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (petstore_auth) required
localVarCredential = this.configuration.lookupCredential('petstore_auth');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json',
'application/xml'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet`;
return this.httpClient.request<Pet>('post', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: pet,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Deletes a pet
*
* @param petId Pet id to delete
* @param apiKey
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (petId === null || petId === undefined) {
throw new Error('Required parameter petId was null or undefined when calling deletePet.');
}
let localVarHeaders = this.defaultHeaders;
if (apiKey !== undefined && apiKey !== null) {
localVarHeaders = localVarHeaders.set('api_key', String(apiKey));
}
let localVarCredential: string | undefined;
// authentication (petstore_auth) required
localVarCredential = this.configuration.lookupCredential('petstore_auth');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`;
return this.httpClient.request<any>('delete', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* @param status Status values that need to be considered for filter
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<Array<Pet>>;
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<Array<Pet>>>;
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<Array<Pet>>>;
public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (status === null || status === undefined) {
throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (status) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
[...status].join(COLLECTION_FORMATS['csv']), 'status');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (petstore_auth) required
localVarCredential = this.configuration.lookupCredential('petstore_auth');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet/findByStatus`;
return this.httpClient.request<Array<Pet>>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* @param tags Tags to filter by
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
* @deprecated
*/
public findPetsByTags(tags: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<Array<Pet>>;
public findPetsByTags(tags: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<Array<Pet>>>;
public findPetsByTags(tags: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<Array<Pet>>>;
public findPetsByTags(tags: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (tags === null || tags === undefined) {
throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (tags) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
[...tags].join(COLLECTION_FORMATS['csv']), 'tags');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (petstore_auth) required
localVarCredential = this.configuration.lookupCredential('petstore_auth');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet/findByTags`;
return this.httpClient.request<Array<Pet>>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Find pet by ID
* Returns a single pet
* @param petId ID of pet to return
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<Pet>;
public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<Pet>>;
public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<Pet>>;
public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (petId === null || petId === undefined) {
throw new Error('Required parameter petId was null or undefined when calling getPetById.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`;
return this.httpClient.request<Pet>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Update an existing pet
*
* @param pet Pet object that needs to be added to the store
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updatePet(pet: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<Pet>;
public updatePet(pet: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<Pet>>;
public updatePet(pet: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<Pet>>;
public updatePet(pet: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (pet === null || pet === undefined) {
throw new Error('Required parameter pet was null or undefined when calling updatePet.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (petstore_auth) required
localVarCredential = this.configuration.lookupCredential('petstore_auth');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json',
'application/xml'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet`;
return this.httpClient.request<Pet>('put', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: pet,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* 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
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (petId === null || petId === undefined) {
throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (petstore_auth) required
localVarCredential = this.configuration.lookupCredential('petstore_auth');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/x-www-form-urlencoded'
];
const canConsumeForm = this.canConsumeForm(consumes);
let localVarFormParams: { append(param: string, value: any): any; };
let localVarUseForm = false;
let localVarConvertFormParamsToString = false;
if (localVarUseForm) {
localVarFormParams = new FormData();
} else {
localVarFormParams = new HttpParams({encoder: this.encoder});
}
if (name !== undefined) {
localVarFormParams = localVarFormParams.append('name', <any>name) as any || localVarFormParams;
}
if (status !== undefined) {
localVarFormParams = localVarFormParams.append('status', <any>status) as any || localVarFormParams;
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`;
return this.httpClient.request<any>('post', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<ApiResponse>;
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpResponse<ApiResponse>>;
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpEvent<ApiResponse>>;
public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any> {
if (petId === null || petId === undefined) {
throw new Error('Required parameter petId was null or undefined when calling uploadFile.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (petstore_auth) required
localVarCredential = this.configuration.lookupCredential('petstore_auth');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'multipart/form-data'
];
const canConsumeForm = this.canConsumeForm(consumes);
let localVarFormParams: { append(param: string, value: any): any; };
let localVarUseForm = false;
let localVarConvertFormParamsToString = false;
// use FormData to transmit files using content-type "multipart/form-data"
// see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data
localVarUseForm = canConsumeForm;
if (localVarUseForm) {
localVarFormParams = new FormData();
} else {
localVarFormParams = new HttpParams({encoder: this.encoder});
}
if (additionalMetadata !== undefined) {
localVarFormParams = localVarFormParams.append('additionalMetadata', <any>additionalMetadata) as any || localVarFormParams;
}
if (file !== undefined) {
localVarFormParams = localVarFormParams.append('file', <any>file) as any || localVarFormParams;
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/pet/${this.configuration.encodeParam({name: "petId", value: petId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}/uploadImage`;
return this.httpClient.request<ApiResponse>('post', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
}

View File

@@ -1,344 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { Order } from '../model/order';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable({
providedIn: 'root'
})
export class StoreService {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
if (Array.isArray(basePath) && basePath.length > 0) {
basePath = basePath[0];
}
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
// @ts-ignore
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
* 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
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (orderId === null || orderId === undefined) {
throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
return this.httpClient.request<any>('delete', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>;
public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpResponse<{ [key: string]: number; }>>;
public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<HttpEvent<{ [key: string]: number; }>>;
public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/store/inventory`;
return this.httpClient.request<{ [key: string]: number; }>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions
* @param orderId ID of pet that needs to be fetched
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<Order>;
public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<Order>>;
public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<Order>>;
public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (orderId === null || orderId === undefined) {
throw new Error('Required parameter orderId was null or undefined when calling getOrderById.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/store/order/${this.configuration.encodeParam({name: "orderId", value: orderId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int64"})}`;
return this.httpClient.request<Order>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Place an order for a pet
*
* @param order order placed for purchasing the pet
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public placeOrder(order: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<Order>;
public placeOrder(order: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<Order>>;
public placeOrder(order: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<Order>>;
public placeOrder(order: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (order === null || order === undefined) {
throw new Error('Required parameter order was null or undefined when calling placeOrder.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/store/order`;
return this.httpClient.request<Order>('post', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: order,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
}

View File

@@ -1,659 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { User } from '../model/user';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable({
providedIn: 'root'
})
export class UserService {
protected basePath = 'http://petstore.swagger.io/v2';
public defaultHeaders = new HttpHeaders();
public configuration = new Configuration();
public encoder: HttpParameterCodec;
constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: Configuration) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
if (Array.isArray(basePath) && basePath.length > 0) {
basePath = basePath[0];
}
if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
// @ts-ignore
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
return httpParams;
}
private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}
if (typeof value === "object") {
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, (value as Date).toISOString().substr(0, 10));
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}.${k}` : k));
}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
}
/**
* Create user
* This can only be done by the logged in user.
* @param user Created user object
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createUser(user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public createUser(user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public createUser(user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public createUser(user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (user === null || user === undefined) {
throw new Error('Required parameter user was null or undefined when calling createUser.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user`;
return this.httpClient.request<any>('post', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: user,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Creates list of users with given input array
*
* @param user List of user object
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createUsersWithArrayInput(user: Array<User>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public createUsersWithArrayInput(user: Array<User>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public createUsersWithArrayInput(user: Array<User>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public createUsersWithArrayInput(user: Array<User>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (user === null || user === undefined) {
throw new Error('Required parameter user was null or undefined when calling createUsersWithArrayInput.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user/createWithArray`;
return this.httpClient.request<any>('post', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: user,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Creates list of users with given input array
*
* @param user List of user object
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createUsersWithListInput(user: Array<User>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public createUsersWithListInput(user: Array<User>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public createUsersWithListInput(user: Array<User>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public createUsersWithListInput(user: Array<User>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (user === null || user === undefined) {
throw new Error('Required parameter user was null or undefined when calling createUsersWithListInput.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user/createWithList`;
return this.httpClient.request<any>('post', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: user,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling deleteUser.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
return this.httpClient.request<any>('delete', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<User>;
public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<User>>;
public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<User>>;
public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling getUserByName.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
return this.httpClient.request<User>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<string>;
public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpResponse<string>>;
public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<HttpEvent<string>>;
public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable<any> {
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling loginUser.');
}
if (password === null || password === undefined) {
throw new Error('Required parameter password was null or undefined when calling loginUser.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
if (username !== undefined && username !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>username, 'username');
}
if (password !== undefined && password !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>password, 'password');
}
let localVarHeaders = this.defaultHeaders;
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/xml',
'application/json'
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user/login`;
return this.httpClient.request<string>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Logs out current logged in user session
*
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user/logout`;
return this.httpClient.request<any>('get', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
/**
* Updated user
* This can only be done by the logged in user.
* @param username name that need to be deleted
* @param user Updated user object
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateUser(username: string, user: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any>;
public updateUser(username: string, user: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpResponse<any>>;
public updateUser(username: string, user: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<HttpEvent<any>>;
public updateUser(username: string, user: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable<any> {
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling updateUser.');
}
if (user === null || user === undefined) {
throw new Error('Required parameter user was null or undefined when calling updateUser.');
}
let localVarHeaders = this.defaultHeaders;
let localVarCredential: string | undefined;
// authentication (api_key) required
localVarCredential = this.configuration.lookupCredential('api_key');
if (localVarCredential) {
localVarHeaders = localVarHeaders.set('api_key', localVarCredential);
}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/user/${this.configuration.encodeParam({name: "username", value: username, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
return this.httpClient.request<any>('put', `${this.configuration.basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: user,
responseType: <any>responseType_,
withCredentials: this.configuration.withCredentials,
headers: localVarHeaders,
observe: observe,
reportProgress: reportProgress
}
);
}
}

View File

@@ -0,0 +1,17 @@
import { Server } from 'http'
import { print } from 'configs/utils'
import CONSTANTS from 'configs/constants'
import createServer from 'configs/application'
import { bootstrapAfter } from 'configs/bootstrap'
module.exports = (async (): Promise<Server> => {
try {
const app = await createServer()
return app.listen(CONSTANTS.PORT, () => {
print.log(`server listening on ${CONSTANTS.PORT}, in ${CONSTANTS.ENV_LABEL} mode.`)
bootstrapAfter()
})
} catch (e) {
console.log(e)
}
})()

View File

@@ -0,0 +1,19 @@
import server from 'server'
import request from 'supertest'
describe('routers: session', () => {
let app
beforeAll(async () => {
app = await server
})
it('should be return 200 status code', async () => {
const res = await request(app).get('/apis/sessions')
expect(res.status).toEqual(200)
})
afterAll(async done => {
app.close()
done()
})
})

View File

@@ -0,0 +1 @@
export * from './sessions.controller'

View File

@@ -0,0 +1,31 @@
import {
BadRequestError,
Post,
JsonController,
BodyParam,
Get,
} from 'routing-controllers'
import { SessionsService } from '../services'
import { Prisma } from '@prisma/client'
import { Service } from 'typedi'
@JsonController()
@Service()
export class SessionsController {
constructor(private sessionsService: SessionsService) {}
@Get('/sessions')
async query() {
return []
}
@Post('/sessions')
async create(
@BodyParam('username') name: string,
): Promise<Prisma.SessionGetPayload<any>> {
if (!name) {
throw new BadRequestError('username is required')
}
return await this.sessionsService.create({ name })
}
}

View File

@@ -0,0 +1,23 @@
import { PrismaClient } from '@prisma/client'
declare global {
namespace NodeJS {
interface Global {
prisma: PrismaClient
}
}
}
let prisma: PrismaClient
if (process.env.NODE_ENV === 'production') {
prisma = new PrismaClient()
} else {
if (!global.prisma) {
global.prisma = new PrismaClient()
}
prisma = global.prisma
}
export default prisma

View File

@@ -0,0 +1,3 @@
## Jobs
You can add scheduled tasks, email tasks, or any third-party work here.

View File

@@ -0,0 +1 @@
export * from './sessions.service'

View File

@@ -0,0 +1,21 @@
import { Service } from 'typedi'
import prisma from 'app/helpers/client'
import { Prisma } from '@prisma/client'
@Service()
export class SessionsService {
/**
* Type 'Prisma.SessionCreateInput' is automatically generated.
* Whenever you modify file 'prisma/schema.prisma' and then run command:
* prisma generate
* prisma migrate dev
* The types is automatically updated.
*
* About CRUD: https://www.prisma.io/docs/concepts/components/prisma-client/crud
*/
async create(session: Prisma.SessionCreateInput) {
return prisma.session.create({
data: session,
})
}
}

View File

@@ -0,0 +1,19 @@
const { nodeExternalsPlugin } = require('esbuild-node-externals')
require('esbuild')
.build({
entryPoints: ['app.ts'],
bundle: true,
outfile: 'dist/index.js',
platform: 'node',
plugins: [
nodeExternalsPlugin({
dependencies: false,
}),
],
external: ['cors', 'kcors'],
})
.catch(err => {
console.log(err)
process.exit(1)
})

View File

@@ -0,0 +1,20 @@
import 'reflect-metadata'
import Koa from 'koa'
import { Container } from 'typedi'
import { routingConfigs } from './routing.options'
import { useMiddlewares } from './koa.middlewares'
import { useKoaServer, useContainer } from 'routing-controllers'
const createServer = async (): Promise<Koa> => {
const koa: Koa = new Koa()
useMiddlewares(koa)
useContainer(Container)
const app: Koa = useKoaServer<Koa>(koa, routingConfigs)
return app
}
export default createServer

View File

@@ -0,0 +1,18 @@
import { join } from 'path'
import { print } from './utils'
import dotenv from 'dotenv'
// "before" will trigger before the app lift.
export const bootstrapBefore = (): object => {
// solve ncc path link.
const result = dotenv.config({ path: join(__dirname, '../.env') })
if (result.error) {
print.danger('Environment variable not loaded: not found ".env" file.')
return {}
}
print.log('.env loaded.')
return result.parsed
}
// "after" will trigger after the "container" mounted..
export const bootstrapAfter = (): any => {}

View File

@@ -0,0 +1,9 @@
const development = {
ENV_LABEL: 'DEVELOPMENT',
PORT: 3001,
}
export default development
export type EevRecord = typeof development

View File

@@ -0,0 +1,5 @@
export enum ENVS {
DEVELOPMENT = 'DEVELOPMENT',
STAGING = 'STAGING',
PRODUCTION = 'PRODUCTION',
}

View File

@@ -0,0 +1,54 @@
import { bootstrapBefore } from '../bootstrap'
import development, { EevRecord } from './development'
import staging from './staging'
import production from './production'
import { ENVS } from './envs'
const parsedEnvs = bootstrapBefore()
const getCurrentEnv = (): ENVS => {
const env = process.env?.ENV
if (typeof env === 'undefined') {
console.warn(`/n> ENV is not set, fallback to ${ENVS.DEVELOPMENT}.`)
}
const upperCaseEnv = `${env}`.toUpperCase()
if (upperCaseEnv === ENVS.PRODUCTION) return ENVS.PRODUCTION
if (upperCaseEnv === ENVS.STAGING) return ENVS.STAGING
return ENVS.DEVELOPMENT
}
const getCurrentConstants = (ident: ENVS): EevRecord => {
let constants = development
const source =
ident === ENVS.PRODUCTION
? production
: ident === ENVS.STAGING
? staging
: development
Object.keys(development).forEach(key => {
const sourceValue = source[key]
const processValue = process.env[key]
const parsedValue = parsedEnvs[key]
if (typeof sourceValue !== 'undefined') {
constants[key] = sourceValue
}
if (typeof processValue !== 'undefined') {
constants[key] = processValue
}
if (typeof parsedValue !== 'undefined') {
constants[key] = parsedValue
}
})
constants.ENV_LABEL = source.ENV_LABEL
return constants
}
export const CURRENT_ENV = getCurrentEnv()
export const isProd = () => CURRENT_ENV === ENVS.PRODUCTION
const CONSTANTS = getCurrentConstants(CURRENT_ENV)
export default CONSTANTS

View File

@@ -0,0 +1,7 @@
import { EevRecord } from './development'
const production: Partial<EevRecord> = {
ENV_LABEL: 'PRODUCTION',
}
export default production

View File

@@ -0,0 +1,7 @@
import { EevRecord } from './development'
const staging: Partial<EevRecord> = {
ENV_LABEL: 'STAGING',
}
export default staging

View File

@@ -0,0 +1,12 @@
import { InterceptorInterface, Action, Interceptor } from 'routing-controllers'
import { Service } from 'typedi'
@Interceptor()
@Service()
export class AutoAssignJSONInterceptor implements InterceptorInterface {
intercept(action: Action, content: any): any {
if (typeof content === 'object')
return JSON.stringify(Object.assign({ message: 'ok' }, content))
return JSON.stringify({ message: content })
}
}

View File

@@ -0,0 +1,14 @@
import Koa from 'koa'
import logger from 'koa-logger'
import bodyParser from 'koa-bodyparser'
import { isProd } from './constants'
export const useMiddlewares = <T extends Koa>(app: T): T => {
if (isProd()) {
app.use(logger())
}
app.use(bodyParser())
return app
}

View File

@@ -0,0 +1,18 @@
import { KoaMiddlewareInterface, Middleware } from 'routing-controllers'
import { Service } from 'typedi'
@Middleware({ type: 'before' })
@Service()
export class HeaderMiddleware implements KoaMiddlewareInterface {
async use(context: any, next: (err?: any) => any): Promise<any> {
context.set('Access-Control-Allow-Methods', 'GET,HEAD,PUT,POST,DELETE,PATCH')
context.set(
'Access-Control-Allow-Origin',
context.request.header.origin || context.request.origin,
)
context.set('Access-Control-Allow-Headers', ['content-type'])
context.set('Access-Control-Allow-Credentials', 'true')
context.set('Content-Type', 'application/json; charset=utf-8')
return next()
}
}

View File

@@ -0,0 +1,21 @@
import { RoutingControllersOptions } from 'routing-controllers'
import * as controllers from 'app/controllers'
import * as middlewares from './routing.middlewares'
import * as interceptors from './interceptors'
import { dictToArray } from './utils'
export const routingConfigs: RoutingControllersOptions = {
controllers: dictToArray(controllers),
middlewares: dictToArray(middlewares),
interceptors: dictToArray(interceptors),
// router prefix
// e.g. api => http://hostname:port/{routePrefix}/{controller.method}
routePrefix: '/apis',
// auto validate entity item
// learn more: https://github.com/typestack/class-validator
validation: true,
}

View File

@@ -0,0 +1,8 @@
export const dictToArray = (dict: object): Array<any> =>
Object.keys(dict).map(name => dict[name])
export const print = {
log: (text: string) => console.log('\x1b[37m%s \x1b[2m%s\x1b[0m', '>', text),
danger: (text: string) => console.log('\x1b[31m%s \x1b[31m%s\x1b[0m', '>', text),
tip: (text: string) => console.log('\x1b[36m%s \x1b[36m%s\x1b[0m', '>', text),
}

View File

@@ -1,186 +0,0 @@
import { HttpParameterCodec } from '@angular/common/http';
import { Param } from './param';
export interface ConfigurationParameters {
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Override the default method for encoding path parameters in various
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam?: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials?: {[ key: string ]: string | (() => string | undefined)};
}
export class Configuration {
/**
* @deprecated Since 5.0. Use credentials instead
*/
apiKeys?: {[ key: string ]: string};
username?: string;
password?: string;
/**
* @deprecated Since 5.0. Use credentials instead
*/
accessToken?: string | (() => string);
basePath?: string;
withCredentials?: boolean;
/**
* Takes care of encoding query- and form-parameters.
*/
encoder?: HttpParameterCodec;
/**
* Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p>
* See {@link README.md} for more details
* </p>
*/
encodeParam: (param: Param) => string;
/**
* The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'.
*/
credentials: {[ key: string ]: string | (() => string | undefined)};
constructor(configurationParameters: ConfigurationParameters = {}) {
this.apiKeys = configurationParameters.apiKeys;
this.username = configurationParameters.username;
this.password = configurationParameters.password;
this.accessToken = configurationParameters.accessToken;
this.basePath = configurationParameters.basePath;
this.withCredentials = configurationParameters.withCredentials;
this.encoder = configurationParameters.encoder;
if (configurationParameters.encodeParam) {
this.encodeParam = configurationParameters.encodeParam;
}
else {
this.encodeParam = param => this.defaultEncodeParam(param);
}
if (configurationParameters.credentials) {
this.credentials = configurationParameters.credentials;
}
else {
this.credentials = {};
}
// init default api_key credential
if (!this.credentials['api_key']) {
this.credentials['api_key'] = () => {
if (this.apiKeys === null || this.apiKeys === undefined) {
return undefined;
} else {
return this.apiKeys['api_key'] || this.apiKeys['api_key'];
}
};
}
// init default petstore_auth credential
if (!this.credentials['petstore_auth']) {
this.credentials['petstore_auth'] = () => {
return typeof this.accessToken === 'function'
? this.accessToken()
: this.accessToken;
};
}
}
/**
* Select the correct content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param contentTypes - the array of content types that are available for selection
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderContentType (contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
}
const type = contentTypes.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return contentTypes[0];
}
return type;
}
/**
* Select the correct accept content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param accepts - the array of content types that are available for selection.
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
}
const type = accepts.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return accepts[0];
}
return type;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i');
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json');
}
public lookupCredential(key: string): string | undefined {
const value = this.credentials[key];
return typeof value === 'function'
? value()
: value;
}
private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format.
// All other styles and Date-formats are probably handled incorrectly.
//
// But: if that's all you need (i.e.: the most common use-case): no need for customization!
const value = param.dataFormat === 'date-time' && param.value instanceof Date
? (param.value as Date).toISOString()
: param.value;
return encodeURIComponent(String(value));
}
}

View File

@@ -0,0 +1,18 @@
version: '3.3'
services:
restapi.postgres:
container_name: koa-ts
image: postgres:13
volumes:
- postgres:/var/lib/postgres
restart: always
ports:
- ${POSTGRES_PORT}:${POSTGRES_PORT}
env_file:
- ./.env
labels:
com.startupteam.description: "postgres container for koa-ts"
volumes:
postgres: {}

View File

@@ -1,20 +0,0 @@
import { HttpParameterCodec } from '@angular/common/http';
/**
* Custom HttpParameterCodec
* Workaround for https://github.com/angular/angular/issues/18261
*/
export class CustomHttpParameterCodec implements HttpParameterCodec {
encodeKey(k: string): string {
return encodeURIComponent(k);
}
encodeValue(v: string): string {
return encodeURIComponent(v);
}
decodeKey(k: string): string {
return decodeURIComponent(k);
}
decodeValue(v: string): string {
return decodeURIComponent(v);
}
}

View File

@@ -1,57 +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 openapi-petstore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=$(git remote)
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${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://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@@ -1,6 +0,0 @@
export * from './api/api';
export * from './model/models';
export * from './variables';
export * from './configuration';
export * from './api.module';
export * from './param';

View File

@@ -1,22 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* Describes the result of uploading an image resource
*/
export interface ApiResponse {
code?: number;
type?: string;
message?: string;
}

View File

@@ -1,21 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A category for a pet
*/
export interface Category {
id?: number;
name?: string;
}

View File

@@ -1,6 +0,0 @@
export * from './apiResponse';
export * from './category';
export * from './order';
export * from './pet';
export * from './tag';
export * from './user';

View File

@@ -1,37 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* An order for a pets from the pet store
*/
export interface Order {
id?: number;
petId?: number;
quantity?: number;
shipDate?: string;
/**
* Order Status
*/
status?: Order.StatusEnum;
complete?: boolean;
}
export namespace Order {
export type StatusEnum = 'placed' | 'approved' | 'delivered';
export const StatusEnum = {
Placed: 'placed' as StatusEnum,
Approved: 'approved' as StatusEnum,
Delivered: 'delivered' as StatusEnum
};
}

View File

@@ -1,39 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Category } from './category';
import { Tag } from './tag';
/**
* A pet for sale in the pet store
*/
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 const StatusEnum = {
Available: 'available' as StatusEnum,
Pending: 'pending' as StatusEnum,
Sold: 'sold' as StatusEnum
};
}

View File

@@ -1,21 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A tag for a pet
*/
export interface Tag {
id?: number;
name?: string;
}

View File

@@ -1,30 +0,0 @@
/**
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
/**
* A User who is purchasing from the pet store
*/
export interface User {
id?: number;
username?: string;
firstName?: string;
lastName?: string;
email?: string;
password?: string;
phone?: string;
/**
* User Status
*/
userStatus?: number;
}

View File

@@ -0,0 +1,22 @@
{
"verbose": false,
"debug": false,
"exec": "ts-node -r tsconfig-paths/register ./app.ts",
"ignore": [
"mochawesome-report",
"node_modules",
"./test",
"**/*.d.ts",
"*.test.ts",
"*.spec.ts",
"fixtures/*",
"test/**/*",
"docs/*"
],
"events": {
"restart": ""
},
"watch": ["./app", "./configs", "./app.ts"],
"ext": "ts",
"inspect": true
}

View File

@@ -0,0 +1,50 @@
{
"name": "Petstore",
"version": "0.0.1",
"license": "MIT",
"main": "app.ts",
"scripts": {
"dev": "export NODE_ENV=development; ts-node-dev -r tsconfig-paths/register app.ts",
"dev:db": "docker compose -f docker-compose.yml up -d",
"prettier": "prettier --write '**/*.{js,ts}'",
"test": "jest --config .jest.config.js --no-cache --detectOpenHandles",
"prod:build": "node ./build.js",
"prod:start": "prisma generate && prisma migrate deploy && export NODE_ENV=production; node ./dist/index.js"
},
"repository": "git@github.com:unix/koa-ts.git",
"engines": {
"node": ">= 14.x"
},
"prettier": "@geist-ui/prettier-config",
"devDependencies": {
"@geist-ui/prettier-config": "^1.0.1",
"@types/jest": "^25.2.2",
"@types/koa": "^2.13.4",
"@types/koa-bodyparser": "^4.3.5",
"@types/node": "^17.0.8",
"esbuild": "^0.14.11",
"esbuild-node-externals": "^1.4.1",
"jest": "^26.6.3",
"prettier": "^2.5.1",
"prisma": "^4.6.1",
"supertest": "^4.0.2",
"ts-jest": "^26.5.3",
"ts-node-dev": "^1.1.8",
"tsconfig-paths": "^3.12.0",
"typescript": "^4.5.4"
},
"dependencies": {
"@prisma/client": "^4.6.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"dotenv": "^12.0.3",
"koa": "^2.13.4",
"koa-bodyparser": "^4.3.0",
"koa-logger": "^3.2.1",
"koa-multer": "^1.0.2",
"koa-router": "^10.1.1",
"reflect-metadata": "^0.1.13",
"routing-controllers": "^0.9.0",
"typedi": "^0.10.0"
}
}

View File

@@ -1,69 +0,0 @@
/**
* Standard parameter styles defined by OpenAPI spec
*/
export type StandardParamStyle =
| 'matrix'
| 'label'
| 'form'
| 'simple'
| 'spaceDelimited'
| 'pipeDelimited'
| 'deepObject'
;
/**
* The OpenAPI standard {@link StandardParamStyle}s may be extended by custom styles by the user.
*/
export type ParamStyle = StandardParamStyle | string;
/**
* Standard parameter locations defined by OpenAPI spec
*/
export type ParamLocation = 'query' | 'header' | 'path' | 'cookie';
/**
* Standard types as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataType =
| "integer"
| "number"
| "boolean"
| "string"
| "object"
| "array"
;
/**
* Standard {@link DataType}s plus your own types/classes.
*/
export type DataType = StandardDataType | string;
/**
* Standard formats as defined in <a href="https://swagger.io/specification/#data-types">OpenAPI Specification: Data Types</a>
*/
export type StandardDataFormat =
| "int32"
| "int64"
| "float"
| "double"
| "byte"
| "binary"
| "date"
| "date-time"
| "password"
;
export type DataFormat = StandardDataFormat | string;
/**
* The parameter to encode.
*/
export interface Param {
name: string;
value: unknown;
in: ParamLocation;
style: ParamStyle,
explode: boolean;
dataType: DataType;
dataFormat: DataFormat | undefined;
}

View File

@@ -0,0 +1,14 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Session {
id Int @id @default(autoincrement())
name String
createdAt DateTime @default(now())
}

View File

@@ -0,0 +1,3 @@
## Test Utils
This folder is used to store test utils, or any mock function.

View File

@@ -0,0 +1,39 @@
{
"compilerOptions": {
"allowJs": true,
"moduleResolution": "Node",
"module": "commonjs",
"outDir": "./dist",
"lib": ["ESNext"],
"removeComments": true,
"skipLibCheck": true,
"noImplicitAny": false,
"esModuleInterop": true,
"preserveConstEnums": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"typeRoots": [
"node_modules/@types",
"typings"
],
"baseUrl": ".",
"paths": {
"configs/*": ["./configs/*"],
"app": ["app"]
},
},
"compileOnSave": false,
"include": [
"app/**/*",
"configs/**/*",
"**/*.ts",
"**/*.tsx"
],
"files": [
"app.ts",
],
"exclude": [
"node_modules",
"dist"
]
}

View File

@@ -1,9 +0,0 @@
import { InjectionToken } from '@angular/core';
export const BASE_PATH = new InjectionToken<string>('basePath');
export const COLLECTION_FORMATS = {
'csv': ',',
'tsv': ' ',
'ssv': ' ',
'pipes': '|'
}

File diff suppressed because it is too large Load Diff