diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index c167e58b2..000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,31 +0,0 @@ -version: 2 -jobs: - build: - working_directory: ~/repo - docker: - - image: cimg/node:lts-browsers - steps: - - checkout - - restore_cache: - keys: - - v1-dependencies-{{ checksum "package.json" }} - - v1-dependencies- - - run: - name: Install dependencies - command: yarn install - - save_cache: - key: v1-dependencies-{{ checksum "package.json" }} - paths: - - node_modules - - run: - name: Build library - command: yarn run release - - run: - name: Run unit tests - command: yarn run test:coverage - - run: - name: Run e2e tests - command: yarn run test:e2e - - run: - name: Submit to Codecov - command: yarn run codecov diff --git a/.gitignore b/.gitignore index 2b7422568..27633cd2e 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ test/e2e/generated samples/generated samples/swagger-codegen-cli-v2.jar samples/swagger-codegen-cli-v3.jar +generated \ No newline at end of file diff --git a/.prettierrc.json b/.prettierrc.json index d7d68f56b..2467418b3 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -1,5 +1,5 @@ { - "semi": true, + "parser": "typescript", "singleQuote": true, "trailingComma": "es5", "arrowParens": "avoid", diff --git a/bin/index.js b/bin/index.js index decf79420..7fe25f227 100755 --- a/bin/index.js +++ b/bin/index.js @@ -32,7 +32,6 @@ if (OpenAPI) { OpenAPI.generate({ input: params.input, output: params.output, - httpClient: params.client, clientName: params.name, useOptions: params.useOptions, useUnionTypes: params.useUnionTypes, diff --git a/docs/angular-support.md b/docs/angular-support.md deleted file mode 100644 index 45905fd37..000000000 --- a/docs/angular-support.md +++ /dev/null @@ -1,89 +0,0 @@ -# Angular support - -This tool allows you to generate a client based on the [`Angular HttpClient`](https://angular.io/guide/http). -The generated services are fully injectable and make use of the [RxJS](https://rxjs.dev/) Observer pattern. -If you want to generate the Angular based client then you can specify `--client angular` in the openapi call: - -`openapi --input ./spec.json --output ./generated --client angular` - -The Angular client has been tested with the following versions: - -``` -"@angular/common": "13.1.3", -"@angular/core": "13.1.3", -"rxjs": "7.5.2", -``` - -## Example - -In the AppModule you can import the services and add them to the list of injectable services: - -```typescript -import { HttpClientModule } from '@angular/common/http'; -import { NgModule } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { OrganizationService } from './generated/services/OrganizationService'; - -@NgModule({ - imports: [ - BrowserModule, - HttpClientModule, - ], - providers: [ - OrganizationService, - ], - bootstrap: [ - AppComponent, - ], -}) -export class AppModule {} - -platformBrowserDynamic() - .bootstrapModule(AppModule) - .catch(err => console.error(err)); -``` - -Inside the component you can inject the service and just use it as you would with any observable: - -```typescript -import { Component } from '@angular/core'; -import { throwError} from 'rxjs'; -import { catchError, map, retry } from 'rxjs/operators'; - -import type { OrganizationService } from './generated/services/OrganizationService'; - -@Component({ - selector: 'app-root', - template: `
Angular is ready
`, -}) -export class AppComponent { - constructor(private readonly organizationService: OrganizationService) { - - // Supports making a simple call - this.organizationService - .createOrganization({ - name: 'OrgName', - description: 'OrgDescription', - }) - .subscribe(organization => { - console.log(organization); - }); - - // Or creating flows with rety(), catchError() and map() - this.organizationService - .getOrganizations() - .pipe( - retry(3), - catchError(error => - throwError(error) - ), - map(organizations => organizations[0]), - ) - .subscribe(organization => { - console.log(organization); - }); - } -} -``` diff --git a/samples/spec/hubspot.json b/samples/spec/hubspot.json new file mode 100644 index 000000000..5bc84b5fd --- /dev/null +++ b/samples/spec/hubspot.json @@ -0,0 +1,1599 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "Companies", + "version": "v3" + }, + "servers": [ + { + "url": "https://api.hubapi.com/" + } + ], + "tags": [ + { + "name": "Associations" + }, + { + "name": "Basic" + }, + { + "name": "Batch" + }, + { + "name": "Search" + } + ], + "paths": { + "/crm/v3/objects/companies": { + "get": { + "tags": ["Basic"], + "summary": "List", + "description": "Read a page of companies. Control what is returned via the `properties` query param.", + "operationId": "get-/crm/v3/objects/companies_getPage", + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "The maximum number of results to display per page.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "integer", + "format": "int32", + "default": 10 + } + }, + { + "name": "after", + "in": "query", + "description": "The paging cursor token of the last successfully read resource will be returned as the `paging.next.after` JSON property of a paged response containing more results.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "string" + } + }, + { + "name": "properties", + "in": "query", + "description": "A comma separated list of the properties to be returned in the response. If any of the specified properties are not present on the requested object(s), they will be ignored.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "associations", + "in": "query", + "description": "A comma separated list of object types to retrieve associated IDs for. If any of the specified associations do not exist, they will be ignored.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "archived", + "in": "query", + "description": "Whether to return only results that have been archived.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "boolean", + "default": false + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CollectionResponseSimplePublicObjectWithAssociationsForwardPaging" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2": ["crm.objects.companies.read"] + }, + { + "oauth2_legacy": ["contacts"] + } + ] + }, + "post": { + "tags": ["Basic"], + "summary": "Create", + "description": "Create a company with the given properties and return a copy of the object, including the ID. Documentation and examples for creating standard companies is provided.", + "operationId": "post-/crm/v3/objects/companies_create", + "parameters": [], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SimplePublicObjectInput" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SimplePublicObject" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + } + }, + "/crm/v3/objects/companies/batch/archive": { + "post": { + "tags": ["Batch"], + "summary": "Archive a batch of companies by ID", + "operationId": "post-/crm/v3/objects/companies/batch/archive_archive", + "parameters": [], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchInputSimplePublicObjectId" + } + } + }, + "required": true + }, + "responses": { + "204": { + "description": "No content", + "content": {} + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + } + }, + "/crm/v3/objects/companies/batch/create": { + "post": { + "tags": ["Batch"], + "summary": "Create a batch of companies", + "operationId": "post-/crm/v3/objects/companies/batch/create_create", + "parameters": [], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchInputSimplePublicObjectInput" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchResponseSimplePublicObject" + } + } + } + }, + "207": { + "description": "multiple statuses", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchResponseSimplePublicObjectWithErrors" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + } + }, + "/crm/v3/objects/companies/batch/read": { + "post": { + "tags": ["Batch"], + "summary": "Read a batch of companies by internal ID, or unique property values", + "operationId": "post-/crm/v3/objects/companies/batch/read_read", + "parameters": [ + { + "name": "archived", + "in": "query", + "description": "Whether to return only results that have been archived.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "boolean", + "default": false + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchReadInputSimplePublicObjectId" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchResponseSimplePublicObject" + } + } + } + }, + "207": { + "description": "multiple statuses", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchResponseSimplePublicObjectWithErrors" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2": ["crm.objects.companies.read"] + }, + { + "oauth2_legacy": ["contacts"] + } + ] + } + }, + "/crm/v3/objects/companies/batch/update": { + "post": { + "tags": ["Batch"], + "summary": "Update a batch of companies", + "operationId": "post-/crm/v3/objects/companies/batch/update_update", + "parameters": [], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchInputSimplePublicObjectBatchInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchResponseSimplePublicObject" + } + } + } + }, + "207": { + "description": "multiple statuses", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchResponseSimplePublicObjectWithErrors" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + } + }, + "/crm/v3/objects/companies/search": { + "post": { + "tags": ["Search"], + "operationId": "post-/crm/v3/objects/companies/search_doSearch", + "parameters": [], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicObjectSearchRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CollectionResponseWithTotalSimplePublicObjectForwardPaging" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2": ["crm.objects.companies.read"] + }, + { + "oauth2_legacy": ["contacts"] + } + ], + "x-hubspot-rate-limit-exemptions": ["ten-secondly"] + } + }, + "/crm/v3/objects/companies/{companyId}": { + "get": { + "tags": ["Basic"], + "summary": "Read", + "description": "Read an Object identified by `{companyId}`. `{companyId}` refers to the internal object ID by default, or optionally any unique property value as specified by the `idProperty` query param. Control what is returned via the `properties` query param.", + "operationId": "get-/crm/v3/objects/companies/{companyId}_getById", + "parameters": [ + { + "name": "companyId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "properties", + "in": "query", + "description": "A comma separated list of the properties to be returned in the response. If any of the specified properties are not present on the requested object(s), they will be ignored.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "associations", + "in": "query", + "description": "A comma separated list of object types to retrieve associated IDs for. If any of the specified associations do not exist, they will be ignored.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + { + "name": "archived", + "in": "query", + "description": "Whether to return only results that have been archived.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "boolean", + "default": false + } + }, + { + "name": "idProperty", + "in": "query", + "description": "The name of a property whose values are unique for this object type", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SimplePublicObjectWithAssociations" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2": ["crm.objects.companies.read"] + }, + { + "oauth2_legacy": ["contacts"] + } + ] + }, + "delete": { + "tags": ["Basic"], + "summary": "Archive", + "description": "Move an Object identified by `{companyId}` to the recycling bin.", + "operationId": "delete-/crm/v3/objects/companies/{companyId}_archive", + "parameters": [ + { + "name": "companyId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No content", + "content": {} + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + }, + "patch": { + "tags": ["Basic"], + "summary": "Update", + "description": "Perform a partial update of an Object identified by `{companyId}`. `{companyId}` refers to the internal object ID by default, or optionally any unique property value as specified by the `idProperty` query param. Provided property values will be overwritten. Read-only and non-existent properties will be ignored. Properties values can be cleared by passing an empty string.", + "operationId": "patch-/crm/v3/objects/companies/{companyId}_update", + "parameters": [ + { + "name": "companyId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "idProperty", + "in": "query", + "description": "The name of a property whose values are unique for this object type", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SimplePublicObjectInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SimplePublicObject" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + } + }, + "/crm/v3/objects/companies/{companyId}/associations/{toObjectType}": { + "get": { + "tags": ["Associations"], + "summary": "List associations of a company by type", + "operationId": "get-/crm/v3/objects/companies/{companyId}/associations/{toObjectType}_getAll", + "parameters": [ + { + "name": "companyId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "toObjectType", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "after", + "in": "query", + "description": "The paging cursor token of the last successfully read resource will be returned as the `paging.next.after` JSON property of a paged response containing more results.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "The maximum number of results to display per page.", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "integer", + "format": "int32", + "default": 500 + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CollectionResponseAssociatedIdForwardPaging" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2": ["crm.objects.companies.read"] + }, + { + "oauth2_legacy": ["contacts"] + } + ] + } + }, + "/crm/v3/objects/companies/{companyId}/associations/{toObjectType}/{toObjectId}/{associationType}": { + "put": { + "tags": ["Associations"], + "summary": "Associate a company with another object", + "operationId": "put-/crm/v3/objects/companies/{companyId}/associations/{toObjectType}/{toObjectId}/{associationType}_create", + "parameters": [ + { + "name": "companyId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "toObjectType", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "toObjectId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "associationType", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SimplePublicObjectWithAssociations" + } + } + } + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + }, + "delete": { + "tags": ["Associations"], + "summary": "Remove an association between two companies", + "operationId": "delete-/crm/v3/objects/companies/{companyId}/associations/{toObjectType}/{toObjectId}/{associationType}_archive", + "parameters": [ + { + "name": "companyId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "toObjectType", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "toObjectId", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + }, + { + "name": "associationType", + "in": "path", + "required": true, + "style": "simple", + "explode": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No content", + "content": {} + }, + "default": { + "$ref": "#/components/responses/Error" + } + }, + "security": [ + { + "hapikey": [] + }, + { + "oauth2_legacy": ["contacts"] + }, + { + "oauth2": ["crm.objects.companies.write"] + } + ] + } + } + }, + "components": { + "schemas": { + "AssociatedId": { + "required": ["id", "type"], + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "BatchInputSimplePublicObjectBatchInput": { + "required": ["inputs"], + "type": "object", + "properties": { + "inputs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObjectBatchInput" + } + } + } + }, + "BatchInputSimplePublicObjectId": { + "required": ["inputs"], + "type": "object", + "properties": { + "inputs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObjectId" + } + } + } + }, + "BatchInputSimplePublicObjectInput": { + "required": ["inputs"], + "type": "object", + "properties": { + "inputs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObjectInput" + } + } + } + }, + "BatchReadInputSimplePublicObjectId": { + "required": ["inputs", "properties"], + "type": "object", + "properties": { + "properties": { + "type": "array", + "items": { + "type": "string" + } + }, + "idProperty": { + "type": "string" + }, + "inputs": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObjectId" + } + } + } + }, + "BatchResponseSimplePublicObject": { + "required": ["completedAt", "results", "startedAt", "status"], + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": ["PENDING", "PROCESSING", "CANCELED", "COMPLETE"] + }, + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObject" + } + }, + "requestedAt": { + "type": "string", + "format": "date-time" + }, + "startedAt": { + "type": "string", + "format": "date-time" + }, + "completedAt": { + "type": "string", + "format": "date-time" + }, + "links": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "BatchResponseSimplePublicObjectWithErrors": { + "required": ["completedAt", "results", "startedAt", "status"], + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": ["PENDING", "PROCESSING", "CANCELED", "COMPLETE"] + }, + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObject" + } + }, + "numErrors": { + "type": "integer", + "format": "int32" + }, + "errors": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StandardError" + } + }, + "requestedAt": { + "type": "string", + "format": "date-time" + }, + "startedAt": { + "type": "string", + "format": "date-time" + }, + "completedAt": { + "type": "string", + "format": "date-time" + }, + "links": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + }, + "CollectionResponseAssociatedId": { + "required": ["results"], + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AssociatedId" + } + }, + "paging": { + "$ref": "#/components/schemas/Paging" + } + } + }, + "CollectionResponseAssociatedIdForwardPaging": { + "required": ["results"], + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AssociatedId" + } + }, + "paging": { + "$ref": "#/components/schemas/ForwardPaging" + } + } + }, + "CollectionResponseSimplePublicObjectWithAssociationsForwardPaging": { + "required": ["results"], + "type": "object", + "properties": { + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObjectWithAssociations" + } + }, + "paging": { + "$ref": "#/components/schemas/ForwardPaging" + } + } + }, + "CollectionResponseWithTotalSimplePublicObjectForwardPaging": { + "required": ["results", "total"], + "type": "object", + "properties": { + "total": { + "type": "integer", + "format": "int32" + }, + "results": { + "type": "array", + "items": { + "$ref": "#/components/schemas/SimplePublicObject" + } + }, + "paging": { + "$ref": "#/components/schemas/ForwardPaging" + } + } + }, + "Error": { + "required": ["category", "correlationId", "message"], + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "A human readable message describing the error along with remediation steps where appropriate", + "example": "An error occurred" + }, + "correlationId": { + "type": "string", + "description": "A unique identifier for the request. Include this value with any error reports or support tickets", + "format": "uuid", + "example": "aeb5f871-7f07-4993-9211-075dc63e7cbf" + }, + "category": { + "type": "string", + "description": "The error category" + }, + "subCategory": { + "type": "string", + "description": "A specific category that contains more specific detail about the error" + }, + "errors": { + "type": "array", + "description": "further information about the error", + "items": { + "$ref": "#/components/schemas/ErrorDetail" + } + }, + "context": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Context about the error condition", + "example": { + "invalidPropertyName": ["propertyValue"], + "missingScopes": ["scope1", "scope2"] + } + }, + "links": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "A map of link names to associated URIs containing documentation about the error or recommended remediation steps" + } + }, + "example": { + "message": "Invalid input (details will vary based on the error)", + "correlationId": "aeb5f871-7f07-4993-9211-075dc63e7cbf", + "category": "VALIDATION_ERROR", + "links": { + "knowledge-base": "https://www.hubspot.com/products/service/knowledge-base" + } + } + }, + "ErrorCategory": { + "required": ["httpStatus", "name"], + "type": "object", + "properties": { + "httpStatus": { + "type": "string", + "enum": [ + "CONTINUE", + "SWITCHING_PROTOCOLS", + "PROCESSING", + "OK", + "CREATED", + "ACCEPTED", + "NON_AUTHORITATIVE_INFORMATION", + "NO_CONTENT", + "RESET_CONTENT", + "PARTIAL_CONTENT", + "MULTI_STATUS", + "ALREADY_REPORTED", + "IM_USED", + "MULTIPLE_CHOICES", + "MOVED_PERMANENTLY", + "FOUND", + "SEE_OTHER", + "NOT_MODIFIED", + "USE_PROXY", + "TEMPORARY_REDIRECT", + "PERMANENT_REDIRECT", + "BAD_REQUEST", + "UNAUTHORIZED", + "PAYMENT_REQUIRED", + "FORBIDDEN", + "NOT_FOUND", + "METHOD_NOT_ALLOWED", + "NOT_ACCEPTABLE", + "PROXY_AUTHENTICATION_REQUIRED", + "REQUEST_TIMEOUT", + "CONFLICT", + "GONE", + "LENGTH_REQUIRED", + "PRECONDITION_FAILED", + "REQUEST_ENTITY_TOO_LARGE", + "REQUEST_URI_TOO_LONG", + "UNSUPPORTED_MEDIA_TYPE", + "REQUESTED_RANGE_NOT_SATISFIABLE", + "EXPECTATION_FAILED", + "IM_A_TEAPOT", + "MISDIRECTED_REQUEST", + "UNPROCESSABLE_ENTITY", + "LOCKED", + "FAILED_DEPENDENCY", + "UPGRADE_REQUIRED", + "PRECONDITION_REQUIRED", + "TOO_MANY_REQUESTS", + "REQUEST_HEADERS_FIELDS_TOO_LARGE", + "INTERNAL_STALE_SERVICE_DISCOVERY", + "UNAVAILABLE_FOR_LEGAL_REASONS", + "INTERNAL_SERVER_ERROR", + "NOT_IMPLEMENTED", + "BAD_GATEWAY", + "SERVICE_UNAVAILABLE", + "GATEWAY_TIMEOUT", + "HTTP_VERSION_NOT_SUPPORTED", + "VARIANT_ALSO_NEGOTIATES", + "INSUFFICIENT_STORAGE", + "LOOP_DETECTED", + "NOT_EXTENDED", + "NETWORK_AUTHENTICATION_REQUIRED" + ] + }, + "name": { + "type": "string" + } + } + }, + "ErrorDetail": { + "required": ["message"], + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "A human readable message describing the error along with remediation steps where appropriate" + }, + "in": { + "type": "string", + "description": "The name of the field or parameter in which the error was found." + }, + "code": { + "type": "string", + "description": "The status code associated with the error detail" + }, + "subCategory": { + "type": "string", + "description": "A specific category that contains more specific detail about the error" + }, + "context": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + }, + "description": "Context about the error condition", + "example": { + "missingScopes": ["scope1", "scope2"] + } + } + } + }, + "Filter": { + "required": ["operator", "propertyName"], + "type": "object", + "properties": { + "value": { + "type": "string" + }, + "propertyName": { + "type": "string" + }, + "operator": { + "type": "string", + "description": "null", + "enum": [ + "EQ", + "NEQ", + "LT", + "LTE", + "GT", + "GTE", + "BETWEEN", + "IN", + "NOT_IN", + "HAS_PROPERTY", + "NOT_HAS_PROPERTY", + "CONTAINS_TOKEN", + "NOT_CONTAINS_TOKEN" + ] + } + } + }, + "FilterGroup": { + "required": ["filters"], + "type": "object", + "properties": { + "filters": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Filter" + } + } + } + }, + "ForwardPaging": { + "type": "object", + "properties": { + "next": { + "$ref": "#/components/schemas/NextPage" + } + } + }, + "NextPage": { + "required": ["after"], + "type": "object", + "properties": { + "after": { + "type": "string" + }, + "link": { + "type": "string" + } + }, + "example": { + "after": "NTI1Cg%3D%3D", + "link": "?after=NTI1Cg%3D%3D" + } + }, + "Paging": { + "type": "object", + "properties": { + "next": { + "$ref": "#/components/schemas/NextPage" + }, + "prev": { + "$ref": "#/components/schemas/PreviousPage" + } + } + }, + "PreviousPage": { + "required": ["before"], + "type": "object", + "properties": { + "before": { + "type": "string" + }, + "link": { + "type": "string" + } + } + }, + "PublicObjectSearchRequest": { + "required": ["after", "filterGroups", "limit", "properties", "sorts"], + "type": "object", + "properties": { + "filterGroups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FilterGroup" + } + }, + "sorts": { + "type": "array", + "items": { + "type": "string" + } + }, + "query": { + "type": "string" + }, + "properties": { + "type": "array", + "items": { + "type": "string" + } + }, + "limit": { + "type": "integer", + "format": "int32" + }, + "after": { + "type": "integer", + "format": "int32" + } + } + }, + "SimplePublicObject": { + "required": ["createdAt", "id", "properties", "updatedAt"], + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "archived": { + "type": "boolean" + }, + "archivedAt": { + "type": "string", + "format": "date-time" + } + }, + "example": { + "id": "512", + "properties": { + "city": "Cambridge", + "createdate": "2019-10-30T03:30:17.883Z", + "domain": "biglytics.net", + "hs_lastmodifieddate": "2019-12-07T16:50:06.678Z", + "industry": "Technology", + "name": "Biglytics", + "phone": "(877) 929-0687", + "state": "Massachusetts" + }, + "createdAt": "2019-10-30T03:30:17.883Z", + "updatedAt": "2019-12-07T16:50:06.678Z", + "archived": false + } + }, + "SimplePublicObjectBatchInput": { + "required": ["id", "properties"], + "type": "object", + "properties": { + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "id": { + "type": "string" + } + }, + "example": { + "id": "1", + "properties": { + "city": "Cambridge", + "domain": "biglytics.net", + "industry": "Technology", + "name": "Biglytics", + "phone": "(877) 929-0687", + "state": "Massachusetts" + } + } + }, + "SimplePublicObjectId": { + "required": ["id"], + "type": "object", + "properties": { + "id": { + "type": "string" + } + } + }, + "SimplePublicObjectInput": { + "required": ["properties"], + "type": "object", + "properties": { + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "example": { + "properties": { + "city": "Cambridge", + "domain": "biglytics.net", + "industry": "Technology", + "name": "Biglytics", + "phone": "(877) 929-0687", + "state": "Massachusetts" + } + } + }, + "SimplePublicObjectWithAssociations": { + "required": ["createdAt", "id", "properties", "updatedAt"], + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "properties": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "archived": { + "type": "boolean" + }, + "archivedAt": { + "type": "string", + "format": "date-time" + }, + "associations": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/CollectionResponseAssociatedId" + } + } + }, + "example": { + "properties": { + "city": "Cambridge", + "createdate": "2019-10-30T03:30:17.883Z", + "domain": "biglytics.net", + "hs_lastmodifieddate": "2019-12-07T16:50:06.678Z", + "industry": "Technology", + "name": "Biglytics", + "phone": "(877) 929-0687", + "state": "Massachusetts" + } + } + }, + "StandardError": { + "required": ["category", "context", "errors", "links", "message", "status"], + "type": "object", + "properties": { + "status": { + "type": "string" + }, + "id": { + "type": "string" + }, + "category": { + "$ref": "#/components/schemas/ErrorCategory" + }, + "subCategory": { + "type": "object", + "properties": {} + }, + "message": { + "type": "string" + }, + "errors": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ErrorDetail" + } + }, + "context": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "links": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + }, + "responses": { + "Error": { + "description": "An error occurred.", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "securitySchemes": { + "oauth2_legacy": { + "type": "oauth2", + "flows": { + "authorizationCode": { + "authorizationUrl": "https://app.hubspot.com/oauth/authorize", + "tokenUrl": "https://api.hubapi.com/oauth/v1/token", + "scopes": { + "contacts": "Read from and write to my Contacts" + } + } + } + }, + "hapikey": { + "type": "apiKey", + "name": "hapikey", + "in": "query" + }, + "oauth2": { + "type": "oauth2", + "flows": { + "authorizationCode": { + "authorizationUrl": "https://app.hubspot.com/oauth/authorize", + "tokenUrl": "https://api.hubapi.com/oauth/v1/token", + "scopes": { + "crm.objects.companies.read": " ", + "crm.objects.companies.write": " " + } + } + } + } + } + }, + "x-hubspot-available-client-libraries": ["PHP", "Node", "Python", "Ruby"] +} diff --git a/src/HttpClient.ts b/src/HttpClient.ts deleted file mode 100644 index 40c77c7c9..000000000 --- a/src/HttpClient.ts +++ /dev/null @@ -1,7 +0,0 @@ -export enum HttpClient { - FETCH = 'fetch', - XHR = 'xhr', - NODE = 'node', - AXIOS = 'axios', - ANGULAR = 'angular', -} diff --git a/src/Indent.ts b/src/Indent.ts deleted file mode 100644 index 4203f34c5..000000000 --- a/src/Indent.ts +++ /dev/null @@ -1,5 +0,0 @@ -export enum Indent { - SPACE_4 = '4', - SPACE_2 = '2', - TAB = 'tab', -} diff --git a/src/client/interfaces/Client.d.ts b/src/client/interfaces/Client.ts similarity index 100% rename from src/client/interfaces/Client.d.ts rename to src/client/interfaces/Client.ts diff --git a/src/client/interfaces/Enum.d.ts b/src/client/interfaces/Enum.ts similarity index 100% rename from src/client/interfaces/Enum.d.ts rename to src/client/interfaces/Enum.ts diff --git a/src/client/interfaces/Model.d.ts b/src/client/interfaces/Model.ts similarity index 100% rename from src/client/interfaces/Model.d.ts rename to src/client/interfaces/Model.ts diff --git a/src/client/interfaces/ModelComposition.d.ts b/src/client/interfaces/ModelComposition.ts similarity index 100% rename from src/client/interfaces/ModelComposition.d.ts rename to src/client/interfaces/ModelComposition.ts diff --git a/src/client/interfaces/Operation.d.ts b/src/client/interfaces/Operation.ts similarity index 100% rename from src/client/interfaces/Operation.d.ts rename to src/client/interfaces/Operation.ts diff --git a/src/client/interfaces/OperationError.d.ts b/src/client/interfaces/OperationError.ts similarity index 100% rename from src/client/interfaces/OperationError.d.ts rename to src/client/interfaces/OperationError.ts diff --git a/src/client/interfaces/OperationParameter.d.ts b/src/client/interfaces/OperationParameter.ts similarity index 100% rename from src/client/interfaces/OperationParameter.d.ts rename to src/client/interfaces/OperationParameter.ts diff --git a/src/client/interfaces/OperationParameters.d.ts b/src/client/interfaces/OperationParameters.ts similarity index 100% rename from src/client/interfaces/OperationParameters.d.ts rename to src/client/interfaces/OperationParameters.ts diff --git a/src/client/interfaces/OperationResponse.d.ts b/src/client/interfaces/OperationResponse.ts similarity index 100% rename from src/client/interfaces/OperationResponse.d.ts rename to src/client/interfaces/OperationResponse.ts diff --git a/src/client/interfaces/Schema.d.ts b/src/client/interfaces/Schema.ts similarity index 100% rename from src/client/interfaces/Schema.d.ts rename to src/client/interfaces/Schema.ts diff --git a/src/client/interfaces/Service.d.ts b/src/client/interfaces/Service.ts similarity index 100% rename from src/client/interfaces/Service.d.ts rename to src/client/interfaces/Service.ts diff --git a/src/client/interfaces/Type.d.ts b/src/client/interfaces/Type.ts similarity index 100% rename from src/client/interfaces/Type.d.ts rename to src/client/interfaces/Type.ts diff --git a/src/index.ts b/src/index.ts index 78bf05468..aeee9d19d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,22 +1,15 @@ -import { HttpClient } from './HttpClient'; -import { Indent } from './Indent'; import { parse as parseV2 } from './openApi/v2'; import { parse as parseV3 } from './openApi/v3'; import { getOpenApiSpec } from './utils/getOpenApiSpec'; import { getOpenApiVersion, OpenApiVersion } from './utils/getOpenApiVersion'; -import { isDefined } from './utils/isDefined'; import { isString } from './utils/isString'; import { postProcessClient } from './utils/postProcessClient'; import { registerHandlebarTemplates } from './utils/registerHandlebarTemplates'; import { writeClient } from './utils/writeClient'; -export { HttpClient } from './HttpClient'; -export { Indent } from './Indent'; - export type Options = { input: string | Record; output: string; - httpClient?: HttpClient; clientName?: string; useOptions?: boolean; useUnionTypes?: boolean; @@ -24,7 +17,6 @@ export type Options = { exportServices?: boolean; exportModels?: boolean; exportSchemas?: boolean; - indent?: Indent; postfix?: string; request?: string; write?: boolean; @@ -36,7 +28,6 @@ export type Options = { * service layer, etc. * @param input The relative location of the OpenAPI spec * @param output The relative location of the output directory - * @param httpClient The selected httpClient (fetch, xhr, node or axios) * @param clientName Custom client class name * @param useOptions Use options or arguments functions * @param useUnionTypes Use union types instead of enums @@ -44,7 +35,6 @@ export type Options = { * @param exportServices Generate services * @param exportModels Generate models * @param exportSchemas Generate schemas - * @param indent Indentation options (4, 2 or tab) * @param postfix Service name postfix * @param request Path to custom request file * @param write Write the files to disk (true or false) @@ -52,7 +42,6 @@ export type Options = { export const generate = async ({ input, output, - httpClient = HttpClient.FETCH, clientName, useOptions = false, useUnionTypes = false, @@ -60,19 +49,13 @@ export const generate = async ({ exportServices = true, exportModels = true, exportSchemas = false, - indent = Indent.SPACE_4, postfix = 'Service', request, write = true, }: Options): Promise => { - if (httpClient === HttpClient.ANGULAR && isDefined(clientName)) { - throw new Error('Angular client does not support --name property'); - } - const openApi = isString(input) ? await getOpenApiSpec(input) : input; const openApiVersion = getOpenApiVersion(openApi); const templates = registerHandlebarTemplates({ - httpClient, useUnionTypes, useOptions, }); @@ -86,14 +69,12 @@ export const generate = async ({ clientFinal, templates, output, - httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas, - indent, postfix, clientName, request @@ -109,14 +90,12 @@ export const generate = async ({ clientFinal, templates, output, - httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas, - indent, postfix, clientName, request @@ -126,7 +105,4 @@ export const generate = async ({ } }; -export default { - HttpClient, - generate, -}; +export default { generate }; diff --git a/src/openApi/v2/parser/getOperationResponse.ts b/src/openApi/v2/parser/getOperationResponse.ts index 8f6c3ca56..e590abcb0 100644 --- a/src/openApi/v2/parser/getOperationResponse.ts +++ b/src/openApi/v2/parser/getOperationResponse.ts @@ -18,8 +18,8 @@ export const getOperationResponse = ( code: responseCode, description: response.description || null, export: 'generic', - type: 'any', - base: 'any', + type: responseCode === 204 ? 'undefined' : 'any', + base: responseCode === 204 ? 'undefined' : 'any', template: null, link: null, isDefinition: false, diff --git a/src/openApi/v2/parser/getOperationResults.ts b/src/openApi/v2/parser/getOperationResults.ts index 9d8111fe8..dc929b78c 100644 --- a/src/openApi/v2/parser/getOperationResults.ts +++ b/src/openApi/v2/parser/getOperationResults.ts @@ -15,7 +15,7 @@ export const getOperationResults = (operationResponses: OperationResponse[]): Op // Filter out success response codes, but skip "204 No Content" operationResponses.forEach(operationResponse => { const { code } = operationResponse; - if (code && code !== 204 && code >= 200 && code < 300) { + if (code && code >= 200 && code < 300) { operationResults.push(operationResponse); } }); diff --git a/src/openApi/v3/parser/getOperationResponse.ts b/src/openApi/v3/parser/getOperationResponse.ts index dff19ec13..5403fb2cd 100644 --- a/src/openApi/v3/parser/getOperationResponse.ts +++ b/src/openApi/v3/parser/getOperationResponse.ts @@ -19,8 +19,8 @@ export const getOperationResponse = ( code: responseCode, description: response.description || null, export: 'generic', - type: 'any', - base: 'any', + type: responseCode === 204 ? 'undefined' : 'any', + base: responseCode === 204 ? 'undefined' : 'any', template: null, link: null, isDefinition: false, diff --git a/src/openApi/v3/parser/getOperationResults.ts b/src/openApi/v3/parser/getOperationResults.ts index 9d8111fe8..dc929b78c 100644 --- a/src/openApi/v3/parser/getOperationResults.ts +++ b/src/openApi/v3/parser/getOperationResults.ts @@ -15,7 +15,7 @@ export const getOperationResults = (operationResponses: OperationResponse[]): Op // Filter out success response codes, but skip "204 No Content" operationResponses.forEach(operationResponse => { const { code } = operationResponse; - if (code && code !== 204 && code >= 200 && code < 300) { + if (code && code >= 200 && code < 300) { operationResults.push(operationResponse); } }); diff --git a/src/templates/client.hbs b/src/templates/client.hbs deleted file mode 100644 index b535311f1..000000000 --- a/src/templates/client.hbs +++ /dev/null @@ -1,40 +0,0 @@ -{{>header}} - -import type { BaseHttpRequest } from './core/BaseHttpRequest'; -import type { OpenAPIConfig } from './core/OpenAPI'; -import { {{{httpRequest}}} } from './core/{{{httpRequest}}}'; - -{{#if services}} -{{#each services}} -import { {{{name}}}{{{@root.postfix}}} } from './services/{{{name}}}{{{@root.postfix}}}'; -{{/each}} -{{/if}} - -type HttpRequestConstructor = new (config: OpenAPIConfig) => BaseHttpRequest; - -export class {{{clientName}}} { - - {{#each services}} - public readonly {{{camelCase name}}}: {{{name}}}{{{@root.postfix}}}; - {{/each}} - - private readonly request: BaseHttpRequest; - - constructor(config?: Partial, HttpRequest: HttpRequestConstructor = {{{httpRequest}}}) { - this.request = new HttpRequest({ - BASE: config?.BASE ?? '{{{server}}}', - VERSION: config?.VERSION ?? '{{{version}}}', - WITH_CREDENTIALS: config?.WITH_CREDENTIALS ?? false, - CREDENTIALS: config?.CREDENTIALS ?? 'include', - TOKEN: config?.TOKEN, - USERNAME: config?.USERNAME, - PASSWORD: config?.PASSWORD, - HEADERS: config?.HEADERS, - ENCODE_PATH: config?.ENCODE_PATH, - }); - - {{#each services}} - this.{{{camelCase name}}} = new {{{name}}}{{{@root.postfix}}}(this.request); - {{/each}} - } -} diff --git a/src/templates/core/ApiError.hbs b/src/templates/core/ApiError.hbs deleted file mode 100644 index 19af17e1a..000000000 --- a/src/templates/core/ApiError.hbs +++ /dev/null @@ -1,20 +0,0 @@ -{{>header}} - -import type { ApiResult } from './ApiResult'; - -export class ApiError extends Error { - public readonly url: string; - public readonly status: number; - public readonly statusText: string; - public readonly body: any; - - constructor(response: ApiResult, message: string) { - super(message); - - this.name = 'ApiError'; - this.url = response.url; - this.status = response.status; - this.statusText = response.statusText; - this.body = response.body; - } -} diff --git a/src/templates/core/ApiRequestOptions.hbs b/src/templates/core/ApiRequestOptions.hbs deleted file mode 100644 index 355929a71..000000000 --- a/src/templates/core/ApiRequestOptions.hbs +++ /dev/null @@ -1,15 +0,0 @@ -{{>header}} - -export type ApiRequestOptions = { - readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; - readonly url: string; - readonly path?: Record; - readonly cookies?: Record; - readonly headers?: Record; - readonly query?: Record; - readonly formData?: Record; - readonly body?: any; - readonly mediaType?: string; - readonly responseHeader?: string; - readonly errors?: Record; -}; diff --git a/src/templates/core/ApiResult.hbs b/src/templates/core/ApiResult.hbs deleted file mode 100644 index a768b8c5a..000000000 --- a/src/templates/core/ApiResult.hbs +++ /dev/null @@ -1,9 +0,0 @@ -{{>header}} - -export type ApiResult = { - readonly url: string; - readonly ok: boolean; - readonly status: number; - readonly statusText: string; - readonly body: any; -}; diff --git a/src/templates/core/BaseHttpRequest.hbs b/src/templates/core/BaseHttpRequest.hbs index fc7f0df5f..9bbabad0e 100644 --- a/src/templates/core/BaseHttpRequest.hbs +++ b/src/templates/core/BaseHttpRequest.hbs @@ -1,14 +1,19 @@ {{>header}} -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; +export type HttpRequestOptions = { + readonly method: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'PATCH'; + readonly url: string; + readonly path?: Record; + readonly cookies?: Record; + readonly headers?: Record; + readonly query?: Record; + readonly formData?: Record; + readonly body?: any; + readonly mediaType?: string; + readonly responseHeader?: string; + readonly errors?: Record; +}; -export class BaseHttpRequest { - - constructor(protected readonly config: OpenAPIConfig) {} - - public request(options: ApiRequestOptions): CancelablePromise { - throw new Error('Not Implemented'); - } +export interface HttpRequest { + request(options: HttpRequestOptions): Promise; } diff --git a/src/templates/core/CancelablePromise.hbs b/src/templates/core/CancelablePromise.hbs deleted file mode 100644 index 67a92a67b..000000000 --- a/src/templates/core/CancelablePromise.hbs +++ /dev/null @@ -1,127 +0,0 @@ -{{>header}} - -export class CancelError extends Error { - - constructor(message: string) { - super(message); - this.name = 'CancelError'; - } - - public get isCancelled(): boolean { - return true; - } -} - -export interface OnCancel { - readonly isResolved: boolean; - readonly isRejected: boolean; - readonly isCancelled: boolean; - - (cancelHandler: () => void): void; -} - -export class CancelablePromise implements Promise { - readonly [Symbol.toStringTag]: string; - - #isResolved: boolean; - #isRejected: boolean; - #isCancelled: boolean; - readonly #cancelHandlers: (() => void)[]; - readonly #promise: Promise; - #resolve?: (value: T | PromiseLike) => void; - #reject?: (reason?: any) => void; - - constructor( - executor: ( - resolve: (value: T | PromiseLike) => void, - reject: (reason?: any) => void, - onCancel: OnCancel - ) => void - ) { - this.#isResolved = false; - this.#isRejected = false; - this.#isCancelled = false; - this.#cancelHandlers = []; - this.#promise = new Promise((resolve, reject) => { - this.#resolve = resolve; - this.#reject = reject; - - const onResolve = (value: T | PromiseLike): void => { - if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; - } - this.#isResolved = true; - this.#resolve?.(value); - }; - - const onReject = (reason?: any): void => { - if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; - } - this.#isRejected = true; - this.#reject?.(reason); - }; - - const onCancel = (cancelHandler: () => void): void => { - if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; - } - this.#cancelHandlers.push(cancelHandler); - }; - - Object.defineProperty(onCancel, 'isResolved', { - get: (): boolean => this.#isResolved, - }); - - Object.defineProperty(onCancel, 'isRejected', { - get: (): boolean => this.#isRejected, - }); - - Object.defineProperty(onCancel, 'isCancelled', { - get: (): boolean => this.#isCancelled, - }); - - return executor(onResolve, onReject, onCancel as OnCancel); - }); - } - - public then( - onFulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onRejected?: ((reason: any) => TResult2 | PromiseLike) | null - ): Promise { - return this.#promise.then(onFulfilled, onRejected); - } - - public catch( - onRejected?: ((reason: any) => TResult | PromiseLike) | null - ): Promise { - return this.#promise.catch(onRejected); - } - - public finally(onFinally?: (() => void) | null): Promise { - return this.#promise.finally(onFinally); - } - - public cancel(): void { - if (this.#isResolved || this.#isRejected || this.#isCancelled) { - return; - } - this.#isCancelled = true; - if (this.#cancelHandlers.length) { - try { - for (const cancelHandler of this.#cancelHandlers) { - cancelHandler(); - } - } catch (error) { - console.warn('Cancellation threw an error', error); - return; - } - } - this.#cancelHandlers.length = 0; - this.#reject?.(new CancelError('Request aborted')); - } - - public get isCancelled(): boolean { - return this.#isCancelled; - } -} diff --git a/src/templates/core/HttpRequest.hbs b/src/templates/core/HttpRequest.hbs deleted file mode 100644 index 3a3a3308e..000000000 --- a/src/templates/core/HttpRequest.hbs +++ /dev/null @@ -1,24 +0,0 @@ -{{>header}} - -import type { ApiRequestOptions } from './ApiRequestOptions'; -import { BaseHttpRequest } from './BaseHttpRequest'; -import type { CancelablePromise } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; -import { request as __request } from './request'; - -export class {{httpRequest}} extends BaseHttpRequest { - - constructor(config: OpenAPIConfig) { - super(config); - } - - /** - * Request method - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ - public request(options: ApiRequestOptions): CancelablePromise { - return __request(this.config, options); - } -} diff --git a/src/templates/core/OpenAPI.hbs b/src/templates/core/OpenAPI.hbs deleted file mode 100644 index 19e66fbf1..000000000 --- a/src/templates/core/OpenAPI.hbs +++ /dev/null @@ -1,30 +0,0 @@ -{{>header}} - -import type { ApiRequestOptions } from './ApiRequestOptions'; - -type Resolver = (options: ApiRequestOptions) => Promise; -type Headers = Record; - -export type OpenAPIConfig = { - BASE: string; - VERSION: string; - WITH_CREDENTIALS: boolean; - CREDENTIALS: 'include' | 'omit' | 'same-origin'; - TOKEN?: string | Resolver; - USERNAME?: string | Resolver; - PASSWORD?: string | Resolver; - HEADERS?: Headers | Resolver; - ENCODE_PATH?: (path: string) => string; -}; - -export const OpenAPI: OpenAPIConfig = { - BASE: '{{{server}}}', - VERSION: '{{{version}}}', - WITH_CREDENTIALS: false, - CREDENTIALS: 'include', - TOKEN: undefined, - USERNAME: undefined, - PASSWORD: undefined, - HEADERS: undefined, - ENCODE_PATH: undefined, -}; diff --git a/src/templates/core/angular/getHeaders.hbs b/src/templates/core/angular/getHeaders.hbs deleted file mode 100644 index bd0ac822d..000000000 --- a/src/templates/core/angular/getHeaders.hbs +++ /dev/null @@ -1,44 +0,0 @@ -const getHeaders = (config: OpenAPIConfig, options: ApiRequestOptions): Observable => { - return forkJoin({ - token: resolve(options, config.TOKEN), - username: resolve(options, config.USERNAME), - password: resolve(options, config.PASSWORD), - additionalHeaders: resolve(options, config.HEADERS), - }).pipe( - map(({ token, username, password, additionalHeaders }) => { - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([_, value]) => isDefined(value)) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new HttpHeaders(headers); - }), - ); -}; diff --git a/src/templates/core/angular/getRequestBody.hbs b/src/templates/core/angular/getRequestBody.hbs deleted file mode 100644 index 9c4049664..000000000 --- a/src/templates/core/angular/getRequestBody.hbs +++ /dev/null @@ -1,12 +0,0 @@ -const getRequestBody = (options: ApiRequestOptions): any => { - if (options.body) { - if (options.mediaType?.includes('/json')) { - return JSON.stringify(options.body) - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return; -}; diff --git a/src/templates/core/angular/getResponseBody.hbs b/src/templates/core/angular/getResponseBody.hbs deleted file mode 100644 index 9a6d359ba..000000000 --- a/src/templates/core/angular/getResponseBody.hbs +++ /dev/null @@ -1,6 +0,0 @@ -const getResponseBody = (response: HttpResponse): T | undefined => { - if (response.status !== 204 && response.body !== null) { - return response.body; - } - return; -}; diff --git a/src/templates/core/angular/getResponseHeader.hbs b/src/templates/core/angular/getResponseHeader.hbs deleted file mode 100644 index 291f7aecb..000000000 --- a/src/templates/core/angular/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -const getResponseHeader = (response: HttpResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const value = response.headers.get(responseHeader); - if (isString(value)) { - return value; - } - } - return; -}; diff --git a/src/templates/core/angular/request.hbs b/src/templates/core/angular/request.hbs deleted file mode 100644 index 57c98516e..000000000 --- a/src/templates/core/angular/request.hbs +++ /dev/null @@ -1,110 +0,0 @@ -{{>header}} - -import { HttpClient, HttpHeaders } from '@angular/common/http'; -import type { HttpResponse, HttpErrorResponse } from '@angular/common/http'; -import { forkJoin, of, throwError } from 'rxjs'; -import { catchError, map, switchMap } from 'rxjs/operators'; -import type { Observable } from 'rxjs'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isDefined}} - - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>angular/getHeaders}} - - -{{>angular/getRequestBody}} - - -{{>angular/sendRequest}} - - -{{>angular/getResponseHeader}} - - -{{>angular/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param http The Angular HTTP client - * @param options The request options from the service - * @returns Observable - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, http: HttpClient, options: ApiRequestOptions): Observable => { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - - return getHeaders(config, options).pipe( - switchMap(headers => { - return sendRequest(config, options, http, url, formData, body, headers); - }), - map(response => { - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - return { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? responseBody, - } as ApiResult; - }), - catchError((error: HttpErrorResponse) => { - if (!error.status) { - return throwError(error); - } - return of({ - url, - ok: error.ok, - status: error.status, - statusText: error.statusText, - body: error.error ?? error.statusText, - } as ApiResult); - }), - map(result => { - catchErrorCodes(options, result); - return result.body as T; - }), - catchError((error: ApiError) => { - return throwError(error); - }), - ); -}; diff --git a/src/templates/core/angular/sendRequest.hbs b/src/templates/core/angular/sendRequest.hbs deleted file mode 100644 index ad73d8332..000000000 --- a/src/templates/core/angular/sendRequest.hbs +++ /dev/null @@ -1,16 +0,0 @@ -export const sendRequest = ( - config: OpenAPIConfig, - options: ApiRequestOptions, - http: HttpClient, - url: string, - body: any, - formData: FormData | undefined, - headers: HttpHeaders -): Observable> => { - return http.request(options.method, url, { - headers, - body: body ?? formData, - withCredentials: config.WITH_CREDENTIALS, - observe: 'response', - }); -}; diff --git a/src/templates/core/axios/getHeaders.hbs b/src/templates/core/axios/getHeaders.hbs deleted file mode 100644 index 8977a5f1a..000000000 --- a/src/templates/core/axios/getHeaders.hbs +++ /dev/null @@ -1,30 +0,0 @@ -const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions, formData?: FormData): Promise> => { - const token = await resolve(options, config.TOKEN); - const username = await resolve(options, config.USERNAME); - const password = await resolve(options, config.PASSWORD); - const additionalHeaders = await resolve(options, config.HEADERS); - const formHeaders = typeof formData?.getHeaders === 'function' && formData?.getHeaders() || {} - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - ...formHeaders, - }) - .filter(([_, value]) => isDefined(value)) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - return headers; -}; diff --git a/src/templates/core/axios/getRequestBody.hbs b/src/templates/core/axios/getRequestBody.hbs deleted file mode 100644 index 0e17c414f..000000000 --- a/src/templates/core/axios/getRequestBody.hbs +++ /dev/null @@ -1,6 +0,0 @@ -const getRequestBody = (options: ApiRequestOptions): any => { - if (options.body) { - return options.body; - } - return; -}; diff --git a/src/templates/core/axios/getResponseBody.hbs b/src/templates/core/axios/getResponseBody.hbs deleted file mode 100644 index 8f2ff06b6..000000000 --- a/src/templates/core/axios/getResponseBody.hbs +++ /dev/null @@ -1,6 +0,0 @@ -const getResponseBody = (response: AxiosResponse): any => { - if (response.status !== 204) { - return response.data; - } - return; -}; diff --git a/src/templates/core/axios/getResponseHeader.hbs b/src/templates/core/axios/getResponseHeader.hbs deleted file mode 100644 index 7463f7440..000000000 --- a/src/templates/core/axios/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -const getResponseHeader = (response: AxiosResponse, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers[responseHeader]; - if (isString(content)) { - return content; - } - } - return; -}; diff --git a/src/templates/core/axios/request.hbs b/src/templates/core/axios/request.hbs deleted file mode 100644 index 439aebe87..000000000 --- a/src/templates/core/axios/request.hbs +++ /dev/null @@ -1,97 +0,0 @@ -{{>header}} - -import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'; -import FormData from 'form-data'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isDefined}} - - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isSuccess}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>axios/getHeaders}} - - -{{>axios/getRequestBody}} - - -{{>axios/sendRequest}} - - -{{>axios/getResponseHeader}} - - -{{>axios/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options, formData); - - if (!onCancel.isCancelled) { - const response = await sendRequest(config, options, url, body, formData, headers, onCancel); - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? responseBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; diff --git a/src/templates/core/axios/sendRequest.hbs b/src/templates/core/axios/sendRequest.hbs deleted file mode 100644 index 3f0d6e02f..000000000 --- a/src/templates/core/axios/sendRequest.hbs +++ /dev/null @@ -1,32 +0,0 @@ -const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Record, - onCancel: OnCancel -): Promise> => { - const source = axios.CancelToken.source(); - - const requestConfig: AxiosRequestConfig = { - url, - headers, - data: body ?? formData, - method: options.method, - withCredentials: config.WITH_CREDENTIALS, - cancelToken: source.token, - }; - - onCancel(() => source.cancel('The user aborted a request.')); - - try { - return await axios.request(requestConfig); - } catch (error) { - const axiosError = error as AxiosError; - if (axiosError.response) { - return axiosError.response; - } - throw error; - } -}; diff --git a/src/templates/core/fetch/getHeaders.hbs b/src/templates/core/fetch/getHeaders.hbs deleted file mode 100644 index 41a65005c..000000000 --- a/src/templates/core/fetch/getHeaders.hbs +++ /dev/null @@ -1,40 +0,0 @@ -const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const token = await resolve(options, config.TOKEN); - const username = await resolve(options, config.USERNAME); - const password = await resolve(options, config.PASSWORD); - const additionalHeaders = await resolve(options, config.HEADERS); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([_, value]) => isDefined(value)) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; diff --git a/src/templates/core/fetch/getRequestBody.hbs b/src/templates/core/fetch/getRequestBody.hbs deleted file mode 100644 index 9c4049664..000000000 --- a/src/templates/core/fetch/getRequestBody.hbs +++ /dev/null @@ -1,12 +0,0 @@ -const getRequestBody = (options: ApiRequestOptions): any => { - if (options.body) { - if (options.mediaType?.includes('/json')) { - return JSON.stringify(options.body) - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - return; -}; diff --git a/src/templates/core/fetch/getResponseBody.hbs b/src/templates/core/fetch/getResponseBody.hbs deleted file mode 100644 index 98ae33e22..000000000 --- a/src/templates/core/fetch/getResponseBody.hbs +++ /dev/null @@ -1,18 +0,0 @@ -const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const isJSON = contentType.toLowerCase().startsWith('application/json'); - if (isJSON) { - return await response.json(); - } else { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return; -}; diff --git a/src/templates/core/fetch/getResponseHeader.hbs b/src/templates/core/fetch/getResponseHeader.hbs deleted file mode 100644 index 0a63760fe..000000000 --- a/src/templates/core/fetch/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return; -}; diff --git a/src/templates/core/fetch/request.hbs b/src/templates/core/fetch/request.hbs deleted file mode 100644 index 4af6f9440..000000000 --- a/src/templates/core/fetch/request.hbs +++ /dev/null @@ -1,94 +0,0 @@ -{{>header}} - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isDefined}} - - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>fetch/getHeaders}} - - -{{>fetch/getRequestBody}} - - -{{>fetch/sendRequest}} - - -{{>fetch/getResponseHeader}} - - -{{>fetch/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - const response = await sendRequest(config, options, url, body, formData, headers, onCancel); - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? responseBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; diff --git a/src/templates/core/fetch/sendRequest.hbs b/src/templates/core/fetch/sendRequest.hbs deleted file mode 100644 index 73f71f428..000000000 --- a/src/templates/core/fetch/sendRequest.hbs +++ /dev/null @@ -1,26 +0,0 @@ -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - const request: RequestInit = { - headers, - body: body ?? formData, - method: options.method, - signal: controller.signal, - }; - - if (config.WITH_CREDENTIALS) { - request.credentials = config.CREDENTIALS; - } - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; diff --git a/src/templates/core/functions/base64.hbs b/src/templates/core/functions/base64.hbs deleted file mode 100644 index be275b851..000000000 --- a/src/templates/core/functions/base64.hbs +++ /dev/null @@ -1,8 +0,0 @@ -const base64 = (str: string): string => { - try { - return btoa(str); - } catch (err) { - // @ts-ignore - return Buffer.from(str).toString('base64'); - } -}; diff --git a/src/templates/core/functions/catchErrorCodes.hbs b/src/templates/core/functions/catchErrorCodes.hbs deleted file mode 100644 index b99916a83..000000000 --- a/src/templates/core/functions/catchErrorCodes.hbs +++ /dev/null @@ -1,21 +0,0 @@ -const catchErrorCodes = (options: ApiRequestOptions, result: ApiResult): void => { - const errors: Record = { - 400: 'Bad Request', - 401: 'Unauthorized', - 403: 'Forbidden', - 404: 'Not Found', - 500: 'Internal Server Error', - 502: 'Bad Gateway', - 503: 'Service Unavailable', - ...options.errors, - } - - const error = errors[result.status]; - if (error) { - throw new ApiError(result, error); - } - - if (!result.ok) { - throw new ApiError(result, 'Generic Error'); - } -}; diff --git a/src/templates/core/functions/getFormData.hbs b/src/templates/core/functions/getFormData.hbs deleted file mode 100644 index 0e6309a30..000000000 --- a/src/templates/core/functions/getFormData.hbs +++ /dev/null @@ -1,26 +0,0 @@ -const getFormData = (options: ApiRequestOptions): FormData | undefined => { - if (options.formData) { - const formData = new FormData(); - - const process = (key: string, value: any) => { - if (isString(value) || isBlob(value)) { - formData.append(key, value); - } else { - formData.append(key, JSON.stringify(value)); - } - }; - - Object.entries(options.formData) - .filter(([_, value]) => isDefined(value)) - .forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach(v => process(key, v)); - } else { - process(key, value); - } - }); - - return formData; - } - return; -}; diff --git a/src/templates/core/functions/getQueryString.hbs b/src/templates/core/functions/getQueryString.hbs deleted file mode 100644 index eac37f5e4..000000000 --- a/src/templates/core/functions/getQueryString.hbs +++ /dev/null @@ -1,33 +0,0 @@ -const getQueryString = (params: Record): string => { - const qs: string[] = []; - - const append = (key: string, value: any) => { - qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`); - }; - - const process = (key: string, value: any) => { - if (isDefined(value)) { - if (Array.isArray(value)) { - value.forEach(v => { - process(key, v); - }); - } else if (typeof value === 'object') { - Object.entries(value).forEach(([k, v]) => { - process(`${key}[${k}]`, v); - }); - } else { - append(key, value); - } - } - }; - - Object.entries(params).forEach(([key, value]) => { - process(key, value); - }); - - if (qs.length > 0) { - return `?${qs.join('&')}`; - } - - return ''; -}; diff --git a/src/templates/core/functions/getUrl.hbs b/src/templates/core/functions/getUrl.hbs deleted file mode 100644 index fe181ab2e..000000000 --- a/src/templates/core/functions/getUrl.hbs +++ /dev/null @@ -1,18 +0,0 @@ -const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => { - const encoder = config.ENCODE_PATH || encodeURI; - - const path = options.url - .replace('{api-version}', config.VERSION) - .replace(/{(.*?)}/g, (substring: string, group: string) => { - if (options.path?.hasOwnProperty(group)) { - return encoder(String(options.path[group])); - } - return substring; - }); - - const url = `${config.BASE}${path}`; - if (options.query) { - return `${url}${getQueryString(options.query)}`; - } - return url; -}; diff --git a/src/templates/core/functions/isBlob.hbs b/src/templates/core/functions/isBlob.hbs deleted file mode 100644 index caf44ddda..000000000 --- a/src/templates/core/functions/isBlob.hbs +++ /dev/null @@ -1,12 +0,0 @@ -const isBlob = (value: any): value is Blob => { - return ( - typeof value === 'object' && - typeof value.type === 'string' && - typeof value.stream === 'function' && - typeof value.arrayBuffer === 'function' && - typeof value.constructor === 'function' && - typeof value.constructor.name === 'string' && - /^(Blob|File)$/.test(value.constructor.name) && - /^(Blob|File)$/.test(value[Symbol.toStringTag]) - ); -}; diff --git a/src/templates/core/functions/isDefined.hbs b/src/templates/core/functions/isDefined.hbs deleted file mode 100644 index ef6d0fc79..000000000 --- a/src/templates/core/functions/isDefined.hbs +++ /dev/null @@ -1,3 +0,0 @@ -const isDefined = (value: T | null | undefined): value is Exclude => { - return value !== undefined && value !== null; -}; diff --git a/src/templates/core/functions/isFormData.hbs b/src/templates/core/functions/isFormData.hbs deleted file mode 100644 index 8bcbed6b4..000000000 --- a/src/templates/core/functions/isFormData.hbs +++ /dev/null @@ -1,3 +0,0 @@ -const isFormData = (value: any): value is FormData => { - return value instanceof FormData; -}; diff --git a/src/templates/core/functions/isString.hbs b/src/templates/core/functions/isString.hbs deleted file mode 100644 index b9888d56b..000000000 --- a/src/templates/core/functions/isString.hbs +++ /dev/null @@ -1,3 +0,0 @@ -const isString = (value: any): value is string => { - return typeof value === 'string'; -}; diff --git a/src/templates/core/functions/isStringWithValue.hbs b/src/templates/core/functions/isStringWithValue.hbs deleted file mode 100644 index b1659067c..000000000 --- a/src/templates/core/functions/isStringWithValue.hbs +++ /dev/null @@ -1,3 +0,0 @@ -const isStringWithValue = (value: any): value is string => { - return isString(value) && value !== ''; -}; diff --git a/src/templates/core/functions/isSuccess.hbs b/src/templates/core/functions/isSuccess.hbs deleted file mode 100644 index 318af1241..000000000 --- a/src/templates/core/functions/isSuccess.hbs +++ /dev/null @@ -1,3 +0,0 @@ -const isSuccess = (status: number): boolean => { - return status >= 200 && status < 300; -}; diff --git a/src/templates/core/functions/resolve.hbs b/src/templates/core/functions/resolve.hbs deleted file mode 100644 index 40dbed816..000000000 --- a/src/templates/core/functions/resolve.hbs +++ /dev/null @@ -1,8 +0,0 @@ -type Resolver = (options: ApiRequestOptions) => Promise; - -const resolve = async (options: ApiRequestOptions, resolver?: T | Resolver): Promise => { - if (typeof resolver === 'function') { - return (resolver as Resolver)(options); - } - return resolver; -}; diff --git a/src/templates/core/node/getHeaders.hbs b/src/templates/core/node/getHeaders.hbs deleted file mode 100644 index 80f2cbcce..000000000 --- a/src/templates/core/node/getHeaders.hbs +++ /dev/null @@ -1,40 +0,0 @@ -const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const token = await resolve(options, config.TOKEN); - const username = await resolve(options, config.USERNAME); - const password = await resolve(options, config.PASSWORD); - const additionalHeaders = await resolve(options, config.HEADERS); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([_, value]) => isDefined(value)) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; diff --git a/src/templates/core/node/getRequestBody.hbs b/src/templates/core/node/getRequestBody.hbs deleted file mode 100644 index e0b420c2b..000000000 --- a/src/templates/core/node/getRequestBody.hbs +++ /dev/null @@ -1,12 +0,0 @@ -const getRequestBody = (options: ApiRequestOptions): any => { - if (options.body) { - if (options.mediaType?.includes('/json')) { - return JSON.stringify(options.body) - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body as any; - } else { - return JSON.stringify(options.body); - } - } - return; -}; diff --git a/src/templates/core/node/getResponseBody.hbs b/src/templates/core/node/getResponseBody.hbs deleted file mode 100644 index 98ae33e22..000000000 --- a/src/templates/core/node/getResponseBody.hbs +++ /dev/null @@ -1,18 +0,0 @@ -const getResponseBody = async (response: Response): Promise => { - if (response.status !== 204) { - try { - const contentType = response.headers.get('Content-Type'); - if (contentType) { - const isJSON = contentType.toLowerCase().startsWith('application/json'); - if (isJSON) { - return await response.json(); - } else { - return await response.text(); - } - } - } catch (error) { - console.error(error); - } - } - return; -}; diff --git a/src/templates/core/node/getResponseHeader.hbs b/src/templates/core/node/getResponseHeader.hbs deleted file mode 100644 index 0a63760fe..000000000 --- a/src/templates/core/node/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -const getResponseHeader = (response: Response, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = response.headers.get(responseHeader); - if (isString(content)) { - return content; - } - } - return; -}; diff --git a/src/templates/core/node/request.hbs b/src/templates/core/node/request.hbs deleted file mode 100644 index 8405467d5..000000000 --- a/src/templates/core/node/request.hbs +++ /dev/null @@ -1,98 +0,0 @@ -{{>header}} - -import { AbortController } from 'abort-controller'; -import FormData from 'form-data'; -import fetch, { BodyInit, Headers, RequestInit, Response } from 'node-fetch'; - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isDefined}} - - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>node/getHeaders}} - - -{{>node/getRequestBody}} - - -{{>node/sendRequest}} - - -{{>node/getResponseHeader}} - - -{{>node/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - const response = await sendRequest(options, url, body, formData, headers, onCancel); - const responseBody = await getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - const result: ApiResult = { - url, - ok: response.ok, - status: response.status, - statusText: response.statusText, - body: responseHeader ?? responseBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; diff --git a/src/templates/core/node/sendRequest.hbs b/src/templates/core/node/sendRequest.hbs deleted file mode 100644 index b7b160f44..000000000 --- a/src/templates/core/node/sendRequest.hbs +++ /dev/null @@ -1,21 +0,0 @@ -export const sendRequest = async ( - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const controller = new AbortController(); - - const request: RequestInit = { - headers, - method: options.method, - body: body ?? formData, - signal: controller.signal, - }; - - onCancel(() => controller.abort()); - - return await fetch(url, request); -}; diff --git a/src/templates/core/request.hbs b/src/templates/core/request.hbs deleted file mode 100644 index c4e2478dd..000000000 --- a/src/templates/core/request.hbs +++ /dev/null @@ -1,5 +0,0 @@ -{{~#equals @root.httpClient 'fetch'}}{{>fetch/request}}{{/equals~}} -{{~#equals @root.httpClient 'xhr'}}{{>xhr/request}}{{/equals~}} -{{~#equals @root.httpClient 'axios'}}{{>axios/request}}{{/equals~}} -{{~#equals @root.httpClient 'angular'}}{{>angular/request}}{{/equals~}} -{{~#equals @root.httpClient 'node'}}{{>node/request}}{{/equals~}} diff --git a/src/templates/core/xhr/getHeaders.hbs b/src/templates/core/xhr/getHeaders.hbs deleted file mode 100644 index 41a65005c..000000000 --- a/src/templates/core/xhr/getHeaders.hbs +++ /dev/null @@ -1,40 +0,0 @@ -const getHeaders = async (config: OpenAPIConfig, options: ApiRequestOptions): Promise => { - const token = await resolve(options, config.TOKEN); - const username = await resolve(options, config.USERNAME); - const password = await resolve(options, config.PASSWORD); - const additionalHeaders = await resolve(options, config.HEADERS); - - const headers = Object.entries({ - Accept: 'application/json', - ...additionalHeaders, - ...options.headers, - }) - .filter(([_, value]) => isDefined(value)) - .reduce((headers, [key, value]) => ({ - ...headers, - [key]: String(value), - }), {} as Record); - - if (isStringWithValue(token)) { - headers['Authorization'] = `Bearer ${token}`; - } - - if (isStringWithValue(username) && isStringWithValue(password)) { - const credentials = base64(`${username}:${password}`); - headers['Authorization'] = `Basic ${credentials}`; - } - - if (options.body) { - if (options.mediaType) { - headers['Content-Type'] = options.mediaType; - } else if (isBlob(options.body)) { - headers['Content-Type'] = options.body.type || 'application/octet-stream'; - } else if (isString(options.body)) { - headers['Content-Type'] = 'text/plain'; - } else if (!isFormData(options.body)) { - headers['Content-Type'] = 'application/json'; - } - } - - return new Headers(headers); -}; diff --git a/src/templates/core/xhr/getRequestBody.hbs b/src/templates/core/xhr/getRequestBody.hbs deleted file mode 100644 index c0b4a534f..000000000 --- a/src/templates/core/xhr/getRequestBody.hbs +++ /dev/null @@ -1,13 +0,0 @@ -const getRequestBody = (options: ApiRequestOptions): any => { - if (options.body) { - if (options.mediaType?.includes('/json')) { - return JSON.stringify(options.body) - } else if (isString(options.body) || isBlob(options.body) || isFormData(options.body)) { - return options.body; - } else { - return JSON.stringify(options.body); - } - } - - return; -}; diff --git a/src/templates/core/xhr/getResponseBody.hbs b/src/templates/core/xhr/getResponseBody.hbs deleted file mode 100644 index 96da1f9f1..000000000 --- a/src/templates/core/xhr/getResponseBody.hbs +++ /dev/null @@ -1,18 +0,0 @@ -const getResponseBody = (xhr: XMLHttpRequest): any => { - if (xhr.status !== 204) { - try { - const contentType = xhr.getResponseHeader('Content-Type'); - if (contentType) { - const isJSON = contentType.toLowerCase().startsWith('application/json'); - if (isJSON) { - return JSON.parse(xhr.responseText); - } else { - return xhr.responseText; - } - } - } catch (error) { - console.error(error); - } - } - return; -}; diff --git a/src/templates/core/xhr/getResponseHeader.hbs b/src/templates/core/xhr/getResponseHeader.hbs deleted file mode 100644 index d99e4c8c1..000000000 --- a/src/templates/core/xhr/getResponseHeader.hbs +++ /dev/null @@ -1,9 +0,0 @@ -const getResponseHeader = (xhr: XMLHttpRequest, responseHeader?: string): string | undefined => { - if (responseHeader) { - const content = xhr.getResponseHeader(responseHeader); - if (isString(content)) { - return content; - } - } - return; -}; diff --git a/src/templates/core/xhr/request.hbs b/src/templates/core/xhr/request.hbs deleted file mode 100644 index 47f92870b..000000000 --- a/src/templates/core/xhr/request.hbs +++ /dev/null @@ -1,97 +0,0 @@ -{{>header}} - -import { ApiError } from './ApiError'; -import type { ApiRequestOptions } from './ApiRequestOptions'; -import type { ApiResult } from './ApiResult'; -import { CancelablePromise } from './CancelablePromise'; -import type { OnCancel } from './CancelablePromise'; -import type { OpenAPIConfig } from './OpenAPI'; - -{{>functions/isDefined}} - - -{{>functions/isString}} - - -{{>functions/isStringWithValue}} - - -{{>functions/isBlob}} - - -{{>functions/isFormData}} - - -{{>functions/isSuccess}} - - -{{>functions/base64}} - - -{{>functions/getQueryString}} - - -{{>functions/getUrl}} - - -{{>functions/getFormData}} - - -{{>functions/resolve}} - - -{{>fetch/getHeaders}} - - -{{>xhr/getRequestBody}} - - -{{>xhr/sendRequest}} - - -{{>xhr/getResponseHeader}} - - -{{>xhr/getResponseBody}} - - -{{>functions/catchErrorCodes}} - - -/** - * Request method - * @param config The OpenAPI configuration object - * @param options The request options from the service - * @returns CancelablePromise - * @throws ApiError - */ -export const request = (config: OpenAPIConfig, options: ApiRequestOptions): CancelablePromise => { - return new CancelablePromise(async (resolve, reject, onCancel) => { - try { - const url = getUrl(config, options); - const formData = getFormData(options); - const body = getRequestBody(options); - const headers = await getHeaders(config, options); - - if (!onCancel.isCancelled) { - const response = await sendRequest(config, options, url, body, formData, headers, onCancel); - const responseBody = getResponseBody(response); - const responseHeader = getResponseHeader(response, options.responseHeader); - - const result: ApiResult = { - url, - ok: isSuccess(response.status), - status: response.status, - statusText: response.statusText, - body: responseHeader ?? responseBody, - }; - - catchErrorCodes(options, result); - - resolve(result.body); - } - } catch (error) { - reject(error); - } - }); -}; diff --git a/src/templates/core/xhr/sendRequest.hbs b/src/templates/core/xhr/sendRequest.hbs deleted file mode 100644 index 0badf8daa..000000000 --- a/src/templates/core/xhr/sendRequest.hbs +++ /dev/null @@ -1,26 +0,0 @@ -export const sendRequest = async ( - config: OpenAPIConfig, - options: ApiRequestOptions, - url: string, - body: any, - formData: FormData | undefined, - headers: Headers, - onCancel: OnCancel -): Promise => { - const xhr = new XMLHttpRequest(); - xhr.open(options.method, url, true); - xhr.withCredentials = config.WITH_CREDENTIALS; - - headers.forEach((value, key) => { - xhr.setRequestHeader(key, value); - }); - - return new Promise((resolve, reject) => { - xhr.onload = () => resolve(xhr); - xhr.onabort = () => reject(new Error('Request aborted')); - xhr.onerror = () => reject(new Error('Network error')); - xhr.send(body ?? formData); - - onCancel(() => xhr.abort()); - }); -}; diff --git a/src/templates/exportModel.hbs b/src/templates/exportModel.hbs index 7ddb2c3e8..25f3309c3 100644 --- a/src/templates/exportModel.hbs +++ b/src/templates/exportModel.hbs @@ -1,11 +1,10 @@ -{{>header}} - -{{#if imports}} +{{!-- {{>header}} --}} +{{!-- {{#if imports}} {{#each imports}} import type { {{{this}}} } from './{{{this}}}'; {{/each}} -{{/if}} +{{/if}} --}} {{#equals export 'interface'}} {{>exportInterface}} diff --git a/src/templates/exportService.hbs b/src/templates/exportService.hbs index 67b7a1f8f..f2e788f12 100644 --- a/src/templates/exportService.hbs +++ b/src/templates/exportService.hbs @@ -1,39 +1,28 @@ {{>header}} -{{#equals @root.httpClient 'angular'}} -import { Injectable } from '@angular/core'; -import { HttpClient } from '@angular/common/http'; -import type { Observable } from 'rxjs'; - -{{/equals}} +import type { HttpRequest } from './core'; {{#if imports}} -{{#each imports}} -import type { {{{this}}} } from '../models/{{{this}}}'; -{{/each}} - -{{/if}} -{{#notEquals @root.httpClient 'angular'}} -import type { CancelablePromise } from '../core/CancelablePromise'; -{{/notEquals}} -{{#if @root.exportClient}} -import type { BaseHttpRequest } from '../core/BaseHttpRequest'; -{{else}} -import { OpenAPI } from '../core/OpenAPI'; -import { request as __request } from '../core/request'; +import type { {{#each imports}}{{{this}}},{{/each}} } from './models'; {{/if}} -{{#equals @root.httpClient 'angular'}} -@Injectable() -{{/equals}} -export class {{{name}}}{{{@root.postfix}}} { - {{#if @root.exportClient}} - - constructor(private readonly httpRequest: BaseHttpRequest) {} +{{#each operations}} + export interface {{name}}Params { + {{#each parameters}} + {{#if description}} + /** {{{escapeComment description}}} **/ {{/if}} - {{#equals @root.httpClient 'angular'}} + {{{name}}}{{>isRequired}}: {{>type}}, + {{/each}} + } + + export type {{name}}Result = + {{#each results}}| {{>type}}{{/each}}; + +{{/each}} + - constructor(private readonly http: HttpClient) {} - {{/equals}} +export class {{{name}}}{{{@root.postfix}}} { + constructor(private readonly http: HttpRequest) {} {{#each operations}} /** @@ -58,52 +47,42 @@ export class {{{name}}}{{{@root.postfix}}} { {{/each}} * @throws ApiError */ - {{#if @root.exportClient}} - public {{{name}}}({{>parameters}}): CancelablePromise<{{>result}}> { - return this.httpRequest.request({ - {{else}} - {{#equals @root.httpClient 'angular'}} - public {{{name}}}({{>parameters}}): Observable<{{>result}}> { - return __request(OpenAPI, this.http, { - {{else}} - public static {{{name}}}({{>parameters}}): CancelablePromise<{{>result}}> { - return __request(OpenAPI, { - {{/equals}} - {{/if}} + public {{{name}}}({{>parameters}}): Promise<{{>result}}> { + return this.http.request({ method: '{{{method}}}', url: '{{{path}}}', {{#if parametersPath}} path: { {{#each parametersPath}} - '{{{prop}}}': {{{name}}}, + {{{prop}}}, {{/each}} }, {{/if}} {{#if parametersCookie}} cookies: { {{#each parametersCookie}} - '{{{prop}}}': {{{name}}}, + {{{prop}}}, {{/each}} }, {{/if}} {{#if parametersHeader}} headers: { {{#each parametersHeader}} - '{{{prop}}}': {{{name}}}, + {{{prop}}}, {{/each}} }, {{/if}} {{#if parametersQuery}} query: { {{#each parametersQuery}} - '{{{prop}}}': {{{name}}}, + {{{prop}}}, {{/each}} }, {{/if}} {{#if parametersForm}} formData: { {{#each parametersForm}} - '{{{prop}}}': {{{name}}}, + {{{prop}}}, {{/each}} }, {{/if}} diff --git a/src/templates/index.hbs b/src/templates/index.hbs deleted file mode 100644 index 855d0c63a..000000000 --- a/src/templates/index.hbs +++ /dev/null @@ -1,46 +0,0 @@ -{{>header}} - -{{#if @root.exportClient}} -export { {{{clientName}}} } from './client'; -{{/if}} -{{#if @root.exportCore}} -export { ApiError } from './core/ApiError'; -{{#if @root.exportClient}} -export { BaseHttpRequest } from './core/BaseHttpRequest'; -{{/if}} -export { CancelablePromise, CancelError } from './core/CancelablePromise'; -export { OpenAPI } from './core/OpenAPI'; -export type { OpenAPIConfig } from './core/OpenAPI'; -{{/if}} -{{#if @root.exportModels}} -{{#if models}} - -{{#each models}} -{{#if @root.useUnionTypes}} -export type { {{{name}}} } from './models/{{{name}}}'; -{{else if enum}} -export { {{{name}}} } from './models/{{{name}}}'; -{{else if enums}} -export { {{{name}}} } from './models/{{{name}}}'; -{{else}} -export type { {{{name}}} } from './models/{{{name}}}'; -{{/if}} -{{/each}} -{{/if}} -{{/if}} -{{#if @root.exportSchemas}} -{{#if models}} - -{{#each models}} -export { ${{{name}}} } from './schemas/${{{name}}}'; -{{/each}} -{{/if}} -{{/if}} -{{#if @root.exportServices}} -{{#if services}} - -{{#each services}} -export { {{{name}}}{{{@root.postfix}}} } from './services/{{{name}}}{{{@root.postfix}}}'; -{{/each}} -{{/if}} -{{/if}} diff --git a/src/templates/partials/parameters.hbs b/src/templates/partials/parameters.hbs index afbb74f4f..44830df5a 100644 --- a/src/templates/partials/parameters.hbs +++ b/src/templates/partials/parameters.hbs @@ -4,14 +4,7 @@ {{#each parameters}} {{{name}}}{{#if default}} = {{{default}}}{{/if}}, {{/each}} -}: { -{{#each parameters}} -{{#if description}} -/** {{{escapeComment description}}} **/ -{{/if}} -{{{name}}}{{>isRequired}}: {{>type}}, -{{/each}} -} +}: {{{name}}}Params {{~else}} {{#each parameters}} diff --git a/src/templates/partials/result.hbs b/src/templates/partials/result.hbs index c8f4770fd..98928915b 100644 --- a/src/templates/partials/result.hbs +++ b/src/templates/partials/result.hbs @@ -1,5 +1,5 @@ {{~#if results~}} -{{#each results}}{{>type}}{{#unless @last}} | {{/unless}}{{/each}} +{{name}}Result {{~else~}} void {{~/if~}} diff --git a/src/utils/formatCode.spec.ts b/src/utils/formatCode.spec.ts deleted file mode 100644 index df46263b1..000000000 --- a/src/utils/formatCode.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { formatCode } from './formatCode'; - -const input1 = `{ foo: true }`; - -const output1 = `{ foo: true }`; - -const input2 = `{ foo: true, bar: 123 }`; - -const output2 = `{ foo: true, bar: 123 }`; - -const input3 = `{ -foo: true, -bar: 123 -}`; - -const output3 = `{ -\tfoo: true, -\tbar: 123 -}`; - -const input4 = `{ -\t\t\t\tfoo: true, -\t\t\t\tbar: 123 -}`; - -const output4 = `{ -\tfoo: true, -\tbar: 123 -}`; - -describe('format', () => { - it('should produce correct result', () => { - expect(formatCode(``)).toEqual(''); - expect(formatCode(`{}`)).toEqual('{}'); - expect(formatCode(input1)).toEqual(output1); - expect(formatCode(input2)).toEqual(output2); - expect(formatCode(input3)).toEqual(output3); - expect(formatCode(input4)).toEqual(output4); - }); -}); diff --git a/src/utils/formatCode.ts b/src/utils/formatCode.ts deleted file mode 100644 index 42cfd5cf4..000000000 --- a/src/utils/formatCode.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { EOL } from 'os'; - -export const formatCode = (s: string): string => { - let indent: number = 0; - let lines = s.split(EOL); - lines = lines.map(line => { - line = line.trim().replace(/^\*/g, ' *'); - let i = indent; - if (line.endsWith('(') || line.endsWith('{') || line.endsWith('[')) { - indent++; - } - if ((line.startsWith(')') || line.startsWith('}') || line.startsWith(']')) && i) { - indent--; - i--; - } - const result = `${'\t'.repeat(i)}${line}`; - if (result.trim() === '') { - return ''; - } - return result; - }); - return lines.join(EOL); -}; diff --git a/src/utils/formatIndentation.ts b/src/utils/formatIndentation.ts deleted file mode 100644 index a2764d99c..000000000 --- a/src/utils/formatIndentation.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { EOL } from 'os'; - -import { Indent } from '../Indent'; - -export const formatIndentation = (s: string, indent: Indent): string => { - let lines = s.split(EOL); - lines = lines.map(line => { - switch (indent) { - case Indent.SPACE_4: - return line.replace(/\t/g, ' '); - case Indent.SPACE_2: - return line.replace(/\t/g, ' '); - case Indent.TAB: - return line; // Default output is tab formatted - } - }); - return lines.join(EOL); -}; diff --git a/src/utils/getHttpRequestName.ts b/src/utils/getHttpRequestName.ts deleted file mode 100644 index 53b7ad05a..000000000 --- a/src/utils/getHttpRequestName.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { HttpClient } from '../HttpClient'; - -/** - * Generate the HttpRequest filename based on the selected client - * @param httpClient The selected httpClient (fetch, xhr, node or axios) - */ -export const getHttpRequestName = (httpClient: HttpClient): string => { - switch (httpClient) { - case HttpClient.FETCH: - return 'FetchHttpRequest'; - case HttpClient.XHR: - return 'XHRHttpRequest'; - case HttpClient.NODE: - return 'NodeHttpRequest'; - case HttpClient.AXIOS: - return 'AxiosHttpRequest'; - case HttpClient.ANGULAR: - return 'AngularHttpRequest'; - } -}; diff --git a/src/utils/registerHandlebarHelpers.spec.ts b/src/utils/registerHandlebarHelpers.spec.ts index f71ca0008..93df9a611 100644 --- a/src/utils/registerHandlebarHelpers.spec.ts +++ b/src/utils/registerHandlebarHelpers.spec.ts @@ -1,12 +1,10 @@ import Handlebars from 'handlebars/runtime'; -import { HttpClient } from '../HttpClient'; import { registerHandlebarHelpers } from './registerHandlebarHelpers'; describe('registerHandlebarHelpers', () => { it('should register the helpers', () => { registerHandlebarHelpers({ - httpClient: HttpClient.FETCH, useOptions: false, useUnionTypes: false, }); diff --git a/src/utils/registerHandlebarHelpers.ts b/src/utils/registerHandlebarHelpers.ts index 58b2ad189..749f3b35f 100644 --- a/src/utils/registerHandlebarHelpers.ts +++ b/src/utils/registerHandlebarHelpers.ts @@ -4,14 +4,9 @@ import { EOL } from 'os'; import type { Enum } from '../client/interfaces/Enum'; import type { Model } from '../client/interfaces/Model'; -import type { HttpClient } from '../HttpClient'; import { unique } from './unique'; -export const registerHandlebarHelpers = (root: { - httpClient: HttpClient; - useOptions: boolean; - useUnionTypes: boolean; -}): void => { +export const registerHandlebarHelpers = (root: { useOptions: boolean; useUnionTypes: boolean }): void => { Handlebars.registerHelper( 'equals', function (this: any, a: string, b: string, options: Handlebars.HelperOptions): string { diff --git a/src/utils/registerHandlebarTemplates.spec.ts b/src/utils/registerHandlebarTemplates.spec.ts index 5e1302384..b267976fb 100644 --- a/src/utils/registerHandlebarTemplates.spec.ts +++ b/src/utils/registerHandlebarTemplates.spec.ts @@ -1,21 +1,19 @@ -import { HttpClient } from '../HttpClient'; import { registerHandlebarTemplates } from './registerHandlebarTemplates'; describe('registerHandlebarTemplates', () => { it('should return correct templates', () => { const templates = registerHandlebarTemplates({ - httpClient: HttpClient.FETCH, useOptions: false, useUnionTypes: false, }); - expect(templates.index).toBeDefined(); + // expect(templates.index).toBeDefined(); expect(templates.exports.model).toBeDefined(); expect(templates.exports.schema).toBeDefined(); expect(templates.exports.service).toBeDefined(); - expect(templates.core.settings).toBeDefined(); - expect(templates.core.apiError).toBeDefined(); - expect(templates.core.apiRequestOptions).toBeDefined(); - expect(templates.core.apiResult).toBeDefined(); - expect(templates.core.request).toBeDefined(); + // expect(templates.core.settings).toBeDefined(); + // expect(templates.core.apiError).toBeDefined(); + // expect(templates.core.apiRequestOptions).toBeDefined(); + // expect(templates.core.apiResult).toBeDefined(); + // expect(templates.core.request).toBeDefined(); }); }); diff --git a/src/utils/registerHandlebarTemplates.ts b/src/utils/registerHandlebarTemplates.ts index bf77cbdc1..6615ef221 100644 --- a/src/utils/registerHandlebarTemplates.ts +++ b/src/utils/registerHandlebarTemplates.ts @@ -1,61 +1,9 @@ import Handlebars from 'handlebars/runtime'; -import { HttpClient } from '../HttpClient'; -import templateClient from '../templates/client.hbs'; -import angularGetHeaders from '../templates/core/angular/getHeaders.hbs'; -import angularGetRequestBody from '../templates/core/angular/getRequestBody.hbs'; -import angularGetResponseBody from '../templates/core/angular/getResponseBody.hbs'; -import angularGetResponseHeader from '../templates/core/angular/getResponseHeader.hbs'; -import angularRequest from '../templates/core/angular/request.hbs'; -import angularSendRequest from '../templates/core/angular/sendRequest.hbs'; -import templateCoreApiError from '../templates/core/ApiError.hbs'; -import templateCoreApiRequestOptions from '../templates/core/ApiRequestOptions.hbs'; -import templateCoreApiResult from '../templates/core/ApiResult.hbs'; -import axiosGetHeaders from '../templates/core/axios/getHeaders.hbs'; -import axiosGetRequestBody from '../templates/core/axios/getRequestBody.hbs'; -import axiosGetResponseBody from '../templates/core/axios/getResponseBody.hbs'; -import axiosGetResponseHeader from '../templates/core/axios/getResponseHeader.hbs'; -import axiosRequest from '../templates/core/axios/request.hbs'; -import axiosSendRequest from '../templates/core/axios/sendRequest.hbs'; import templateCoreBaseHttpRequest from '../templates/core/BaseHttpRequest.hbs'; -import templateCancelablePromise from '../templates/core/CancelablePromise.hbs'; -import fetchGetHeaders from '../templates/core/fetch/getHeaders.hbs'; -import fetchGetRequestBody from '../templates/core/fetch/getRequestBody.hbs'; -import fetchGetResponseBody from '../templates/core/fetch/getResponseBody.hbs'; -import fetchGetResponseHeader from '../templates/core/fetch/getResponseHeader.hbs'; -import fetchRequest from '../templates/core/fetch/request.hbs'; -import fetchSendRequest from '../templates/core/fetch/sendRequest.hbs'; -import functionBase64 from '../templates/core/functions/base64.hbs'; -import functionCatchErrorCodes from '../templates/core/functions/catchErrorCodes.hbs'; -import functionGetFormData from '../templates/core/functions/getFormData.hbs'; -import functionGetQueryString from '../templates/core/functions/getQueryString.hbs'; -import functionGetUrl from '../templates/core/functions/getUrl.hbs'; -import functionIsBlob from '../templates/core/functions/isBlob.hbs'; -import functionIsDefined from '../templates/core/functions/isDefined.hbs'; -import functionIsFormData from '../templates/core/functions/isFormData.hbs'; -import functionIsString from '../templates/core/functions/isString.hbs'; -import functionIsStringWithValue from '../templates/core/functions/isStringWithValue.hbs'; -import functionIsSuccess from '../templates/core/functions/isSuccess.hbs'; -import functionResolve from '../templates/core/functions/resolve.hbs'; -import templateCoreHttpRequest from '../templates/core/HttpRequest.hbs'; -import nodeGetHeaders from '../templates/core/node/getHeaders.hbs'; -import nodeGetRequestBody from '../templates/core/node/getRequestBody.hbs'; -import nodeGetResponseBody from '../templates/core/node/getResponseBody.hbs'; -import nodeGetResponseHeader from '../templates/core/node/getResponseHeader.hbs'; -import nodeRequest from '../templates/core/node/request.hbs'; -import nodeSendRequest from '../templates/core/node/sendRequest.hbs'; -import templateCoreSettings from '../templates/core/OpenAPI.hbs'; -import templateCoreRequest from '../templates/core/request.hbs'; -import xhrGetHeaders from '../templates/core/xhr/getHeaders.hbs'; -import xhrGetRequestBody from '../templates/core/xhr/getRequestBody.hbs'; -import xhrGetResponseBody from '../templates/core/xhr/getResponseBody.hbs'; -import xhrGetResponseHeader from '../templates/core/xhr/getResponseHeader.hbs'; -import xhrRequest from '../templates/core/xhr/request.hbs'; -import xhrSendRequest from '../templates/core/xhr/sendRequest.hbs'; import templateExportModel from '../templates/exportModel.hbs'; import templateExportSchema from '../templates/exportSchema.hbs'; import templateExportService from '../templates/exportService.hbs'; -import templateIndex from '../templates/index.hbs'; import partialBase from '../templates/partials/base.hbs'; import partialExportComposition from '../templates/partials/exportComposition.hbs'; import partialExportEnum from '../templates/partials/exportEnum.hbs'; @@ -86,22 +34,13 @@ import partialTypeUnion from '../templates/partials/typeUnion.hbs'; import { registerHandlebarHelpers } from './registerHandlebarHelpers'; export interface Templates { - index: Handlebars.TemplateDelegate; - client: Handlebars.TemplateDelegate; exports: { model: Handlebars.TemplateDelegate; schema: Handlebars.TemplateDelegate; service: Handlebars.TemplateDelegate; }; core: { - settings: Handlebars.TemplateDelegate; - apiError: Handlebars.TemplateDelegate; - apiRequestOptions: Handlebars.TemplateDelegate; - apiResult: Handlebars.TemplateDelegate; - cancelablePromise: Handlebars.TemplateDelegate; - request: Handlebars.TemplateDelegate; baseHttpRequest: Handlebars.TemplateDelegate; - httpRequest: Handlebars.TemplateDelegate; }; } @@ -109,31 +48,18 @@ export interface Templates { * Read all the Handlebar templates that we need and return on wrapper object * so we can easily access the templates in out generator / write functions. */ -export const registerHandlebarTemplates = (root: { - httpClient: HttpClient; - useOptions: boolean; - useUnionTypes: boolean; -}): Templates => { +export const registerHandlebarTemplates = (root: { useOptions: boolean; useUnionTypes: boolean }): Templates => { registerHandlebarHelpers(root); // Main templates (entry points for the files we write to disk) const templates: Templates = { - index: Handlebars.template(templateIndex), - client: Handlebars.template(templateClient), exports: { model: Handlebars.template(templateExportModel), schema: Handlebars.template(templateExportSchema), service: Handlebars.template(templateExportService), }, core: { - settings: Handlebars.template(templateCoreSettings), - apiError: Handlebars.template(templateCoreApiError), - apiRequestOptions: Handlebars.template(templateCoreApiRequestOptions), - apiResult: Handlebars.template(templateCoreApiResult), - cancelablePromise: Handlebars.template(templateCancelablePromise), - request: Handlebars.template(templateCoreRequest), baseHttpRequest: Handlebars.template(templateCoreBaseHttpRequest), - httpRequest: Handlebars.template(templateCoreHttpRequest), }, }; @@ -166,59 +92,5 @@ export const registerHandlebarTemplates = (root: { Handlebars.registerPartial('typeIntersection', Handlebars.template(partialTypeIntersection)); Handlebars.registerPartial('base', Handlebars.template(partialBase)); - // Generic functions used in 'request' file @see src/templates/core/request.hbs for more info - Handlebars.registerPartial('functions/catchErrorCodes', Handlebars.template(functionCatchErrorCodes)); - Handlebars.registerPartial('functions/getFormData', Handlebars.template(functionGetFormData)); - Handlebars.registerPartial('functions/getQueryString', Handlebars.template(functionGetQueryString)); - Handlebars.registerPartial('functions/getUrl', Handlebars.template(functionGetUrl)); - Handlebars.registerPartial('functions/isBlob', Handlebars.template(functionIsBlob)); - Handlebars.registerPartial('functions/isDefined', Handlebars.template(functionIsDefined)); - Handlebars.registerPartial('functions/isFormData', Handlebars.template(functionIsFormData)); - Handlebars.registerPartial('functions/isString', Handlebars.template(functionIsString)); - Handlebars.registerPartial('functions/isStringWithValue', Handlebars.template(functionIsStringWithValue)); - Handlebars.registerPartial('functions/isSuccess', Handlebars.template(functionIsSuccess)); - Handlebars.registerPartial('functions/base64', Handlebars.template(functionBase64)); - Handlebars.registerPartial('functions/resolve', Handlebars.template(functionResolve)); - - // Specific files for the fetch client implementation - Handlebars.registerPartial('fetch/getHeaders', Handlebars.template(fetchGetHeaders)); - Handlebars.registerPartial('fetch/getRequestBody', Handlebars.template(fetchGetRequestBody)); - Handlebars.registerPartial('fetch/getResponseBody', Handlebars.template(fetchGetResponseBody)); - Handlebars.registerPartial('fetch/getResponseHeader', Handlebars.template(fetchGetResponseHeader)); - Handlebars.registerPartial('fetch/sendRequest', Handlebars.template(fetchSendRequest)); - Handlebars.registerPartial('fetch/request', Handlebars.template(fetchRequest)); - - // Specific files for the xhr client implementation - Handlebars.registerPartial('xhr/getHeaders', Handlebars.template(xhrGetHeaders)); - Handlebars.registerPartial('xhr/getRequestBody', Handlebars.template(xhrGetRequestBody)); - Handlebars.registerPartial('xhr/getResponseBody', Handlebars.template(xhrGetResponseBody)); - Handlebars.registerPartial('xhr/getResponseHeader', Handlebars.template(xhrGetResponseHeader)); - Handlebars.registerPartial('xhr/sendRequest', Handlebars.template(xhrSendRequest)); - Handlebars.registerPartial('xhr/request', Handlebars.template(xhrRequest)); - - // Specific files for the node client implementation - Handlebars.registerPartial('node/getHeaders', Handlebars.template(nodeGetHeaders)); - Handlebars.registerPartial('node/getRequestBody', Handlebars.template(nodeGetRequestBody)); - Handlebars.registerPartial('node/getResponseBody', Handlebars.template(nodeGetResponseBody)); - Handlebars.registerPartial('node/getResponseHeader', Handlebars.template(nodeGetResponseHeader)); - Handlebars.registerPartial('node/sendRequest', Handlebars.template(nodeSendRequest)); - Handlebars.registerPartial('node/request', Handlebars.template(nodeRequest)); - - // Specific files for the axios client implementation - Handlebars.registerPartial('axios/getHeaders', Handlebars.template(axiosGetHeaders)); - Handlebars.registerPartial('axios/getRequestBody', Handlebars.template(axiosGetRequestBody)); - Handlebars.registerPartial('axios/getResponseBody', Handlebars.template(axiosGetResponseBody)); - Handlebars.registerPartial('axios/getResponseHeader', Handlebars.template(axiosGetResponseHeader)); - Handlebars.registerPartial('axios/sendRequest', Handlebars.template(axiosSendRequest)); - Handlebars.registerPartial('axios/request', Handlebars.template(axiosRequest)); - - // Specific files for the angular client implementation - Handlebars.registerPartial('angular/getHeaders', Handlebars.template(angularGetHeaders)); - Handlebars.registerPartial('angular/getRequestBody', Handlebars.template(angularGetRequestBody)); - Handlebars.registerPartial('angular/getResponseBody', Handlebars.template(angularGetResponseBody)); - Handlebars.registerPartial('angular/getResponseHeader', Handlebars.template(angularGetResponseHeader)); - Handlebars.registerPartial('angular/sendRequest', Handlebars.template(angularSendRequest)); - Handlebars.registerPartial('angular/request', Handlebars.template(angularRequest)); - return templates; }; diff --git a/src/utils/writeClient.spec.ts b/src/utils/writeClient.spec.ts index 3c06a95a5..d602699e4 100644 --- a/src/utils/writeClient.spec.ts +++ b/src/utils/writeClient.spec.ts @@ -1,6 +1,4 @@ import type { Client } from '../client/interfaces/Client'; -import { HttpClient } from '../HttpClient'; -import { Indent } from '../Indent'; import { mkdir, rmdir, writeFile } from './fileSystem'; import type { Templates } from './registerHandlebarTemplates'; import { writeClient } from './writeClient'; @@ -17,40 +15,26 @@ describe('writeClient', () => { }; const templates: Templates = { - index: () => 'index', - client: () => 'client', + // index: () => 'index', + // client: () => 'client', exports: { model: () => 'model', schema: () => 'schema', service: () => 'service', }, core: { - settings: () => 'settings', - apiError: () => 'apiError', - apiRequestOptions: () => 'apiRequestOptions', - apiResult: () => 'apiResult', - cancelablePromise: () => 'cancelablePromise', - request: () => 'request', + // settings: () => 'settings', + // apiError: () => 'apiError', + // apiRequestOptions: () => 'apiRequestOptions', + // apiResult: () => 'apiResult', + // cancelablePromise: () => 'cancelablePromise', + // request: () => 'request', baseHttpRequest: () => 'baseHttpRequest', - httpRequest: () => 'httpRequest', + // httpRequest: () => 'httpRequest', }, }; - await writeClient( - client, - templates, - './dist', - HttpClient.FETCH, - false, - false, - true, - true, - true, - true, - Indent.SPACE_4, - 'Service', - 'AppClient' - ); + await writeClient(client, templates, './dist', false, false, true, true, true, true, 'Service', 'AppClient'); expect(rmdir).toBeCalled(); expect(mkdir).toBeCalled(); diff --git a/src/utils/writeClient.ts b/src/utils/writeClient.ts index a0ffc1821..00611bd95 100644 --- a/src/utils/writeClient.ts +++ b/src/utils/writeClient.ts @@ -1,15 +1,10 @@ import { resolve } from 'path'; import type { Client } from '../client/interfaces/Client'; -import type { HttpClient } from '../HttpClient'; -import type { Indent } from '../Indent'; -import { mkdir, rmdir } from './fileSystem'; -import { isDefined } from './isDefined'; +import { mkdir } from './fileSystem'; import { isSubDirectory } from './isSubdirectory'; import type { Templates } from './registerHandlebarTemplates'; -import { writeClientClass } from './writeClientClass'; import { writeClientCore } from './writeClientCore'; -import { writeClientIndex } from './writeClientIndex'; import { writeClientModels } from './writeClientModels'; import { writeClientSchemas } from './writeClientSchemas'; import { writeClientServices } from './writeClientServices'; @@ -19,7 +14,6 @@ import { writeClientServices } from './writeClientServices'; * @param client Client object with all the models, services, etc. * @param templates Templates wrapper with all loaded Handlebars templates * @param output The relative location of the output directory - * @param httpClient The selected httpClient (fetch, xhr, node or axios) * @param useOptions Use options or arguments functions * @param useUnionTypes Use union types instead of enums * @param exportCore Generate core client classes @@ -27,7 +21,6 @@ import { writeClientServices } from './writeClientServices'; * @param exportModels Generate models * @param exportSchemas Generate schemas * @param exportSchemas Generate schemas - * @param indent Indentation options (4, 2 or tab) * @param postfix Service name postfix * @param clientName Custom client class name * @param request Path to custom request file @@ -36,14 +29,12 @@ export const writeClient = async ( client: Client, templates: Templates, output: string, - httpClient: HttpClient, useOptions: boolean, useUnionTypes: boolean, exportCore: boolean, exportServices: boolean, exportModels: boolean, exportSchemas: boolean, - indent: Indent, postfix: string, clientName?: string, request?: string @@ -58,58 +49,29 @@ export const writeClient = async ( throw new Error(`Output folder is not a subdirectory of the current working directory`); } + await mkdir(outputPath); + if (exportCore) { - await rmdir(outputPathCore); - await mkdir(outputPathCore); - await writeClientCore(client, templates, outputPathCore, httpClient, indent, clientName, request); + await writeClientCore(client, templates, outputPathCore, clientName, request); } if (exportServices) { - await rmdir(outputPathServices); - await mkdir(outputPathServices); await writeClientServices( client.services, templates, outputPathServices, - httpClient, useUnionTypes, useOptions, - indent, postfix, clientName ); } if (exportSchemas) { - await rmdir(outputPathSchemas); - await mkdir(outputPathSchemas); - await writeClientSchemas(client.models, templates, outputPathSchemas, httpClient, useUnionTypes, indent); + await writeClientSchemas(client.models, templates, outputPathSchemas, useUnionTypes); } if (exportModels) { - await rmdir(outputPathModels); - await mkdir(outputPathModels); - await writeClientModels(client.models, templates, outputPathModels, httpClient, useUnionTypes, indent); - } - - if (isDefined(clientName)) { - await mkdir(outputPath); - await writeClientClass(client, templates, outputPath, httpClient, clientName, indent, postfix); - } - - if (exportCore || exportServices || exportSchemas || exportModels) { - await mkdir(outputPath); - await writeClientIndex( - client, - templates, - outputPath, - useUnionTypes, - exportCore, - exportServices, - exportModels, - exportSchemas, - postfix, - clientName - ); + await writeClientModels(client.models, templates, outputPathModels, useUnionTypes); } }; diff --git a/src/utils/writeClientClass.spec.ts b/src/utils/writeClientClass.spec.ts deleted file mode 100644 index 102f2eb57..000000000 --- a/src/utils/writeClientClass.spec.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { Client } from '../client/interfaces/Client'; -import { HttpClient } from '../HttpClient'; -import { Indent } from '../Indent'; -import { writeFile } from './fileSystem'; -import type { Templates } from './registerHandlebarTemplates'; -import { writeClientClass } from './writeClientClass'; - -jest.mock('./fileSystem'); - -describe('writeClientClass', () => { - it('should write to filesystem', async () => { - const client: Client = { - server: 'http://localhost:8080', - version: 'v1', - models: [], - services: [], - }; - - const templates: Templates = { - index: () => 'index', - client: () => 'client', - exports: { - model: () => 'model', - schema: () => 'schema', - service: () => 'service', - }, - core: { - settings: () => 'settings', - apiError: () => 'apiError', - apiRequestOptions: () => 'apiRequestOptions', - apiResult: () => 'apiResult', - cancelablePromise: () => 'cancelablePromise', - request: () => 'request', - baseHttpRequest: () => 'baseHttpRequest', - httpRequest: () => 'httpRequest', - }, - }; - - await writeClientClass(client, templates, './dist', HttpClient.FETCH, 'AppClient', Indent.SPACE_4, ''); - - expect(writeFile).toBeCalled(); - }); -}); diff --git a/src/utils/writeClientClass.ts b/src/utils/writeClientClass.ts deleted file mode 100644 index 549a5c5b8..000000000 --- a/src/utils/writeClientClass.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { resolve } from 'path'; - -import type { Client } from '../client/interfaces/Client'; -import type { HttpClient } from '../HttpClient'; -import type { Indent } from '../Indent'; -import { writeFile } from './fileSystem'; -import { formatCode as f } from './formatCode'; -import { formatIndentation as i } from './formatIndentation'; -import { getHttpRequestName } from './getHttpRequestName'; -import type { Templates } from './registerHandlebarTemplates'; -import { sortModelsByName } from './sortModelsByName'; -import { sortServicesByName } from './sortServicesByName'; - -/** - * Generate the OpenAPI client index file using the Handlebar template and write it to disk. - * The index file just contains all the exports you need to use the client as a standalone - * library. But yuo can also import individual models and services directly. - * @param client Client object, containing, models, schemas and services - * @param templates The loaded handlebar templates - * @param outputPath Directory to write the generated files to - * @param httpClient The selected httpClient (fetch, xhr, node or axios) - * @param clientName Custom client class name - * @param indent Indentation options (4, 2 or tab) - * @param postfix Service name postfix - */ -export const writeClientClass = async ( - client: Client, - templates: Templates, - outputPath: string, - httpClient: HttpClient, - clientName: string, - indent: Indent, - postfix: string -): Promise => { - const templateResult = templates.client({ - clientName, - postfix, - server: client.server, - version: client.version, - models: sortModelsByName(client.models), - services: sortServicesByName(client.services), - httpRequest: getHttpRequestName(httpClient), - }); - - await writeFile(resolve(outputPath, 'client.ts'), i(f(templateResult), indent)); -}; diff --git a/src/utils/writeClientCore.spec.ts b/src/utils/writeClientCore.spec.ts index cb2cc2925..597d6477e 100644 --- a/src/utils/writeClientCore.spec.ts +++ b/src/utils/writeClientCore.spec.ts @@ -1,6 +1,4 @@ import type { Client } from '../client/interfaces/Client'; -import { HttpClient } from '../HttpClient'; -import { Indent } from '../Indent'; import { writeFile } from './fileSystem'; import type { Templates } from './registerHandlebarTemplates'; import { writeClientCore } from './writeClientCore'; @@ -17,26 +15,17 @@ describe('writeClientCore', () => { }; const templates: Templates = { - index: () => 'index', - client: () => 'client', exports: { model: () => 'model', schema: () => 'schema', service: () => 'service', }, core: { - settings: () => 'settings', - apiError: () => 'apiError', - apiRequestOptions: () => 'apiRequestOptions', - apiResult: () => 'apiResult', - cancelablePromise: () => 'cancelablePromise', - request: () => 'request', baseHttpRequest: () => 'baseHttpRequest', - httpRequest: () => 'httpRequest', }, }; - await writeClientCore(client, templates, '/', HttpClient.FETCH, Indent.SPACE_4); + await writeClientCore(client, templates, '/'); expect(writeFile).toBeCalledWith('/OpenAPI.ts', 'settings'); expect(writeFile).toBeCalledWith('/ApiError.ts', 'apiError'); diff --git a/src/utils/writeClientCore.ts b/src/utils/writeClientCore.ts index 6d35849d2..05aed9d8a 100644 --- a/src/utils/writeClientCore.ts +++ b/src/utils/writeClientCore.ts @@ -1,12 +1,7 @@ import { resolve } from 'path'; import type { Client } from '../client/interfaces/Client'; -import type { HttpClient } from '../HttpClient'; -import type { Indent } from '../Indent'; import { copyFile, exists, writeFile } from './fileSystem'; -import { formatIndentation as i } from './formatIndentation'; -import { getHttpRequestName } from './getHttpRequestName'; -import { isDefined } from './isDefined'; import type { Templates } from './registerHandlebarTemplates'; /** @@ -14,8 +9,6 @@ import type { Templates } from './registerHandlebarTemplates'; * @param client Client object, containing, models, schemas and services * @param templates The loaded handlebar templates * @param outputPath Directory to write the generated files to - * @param httpClient The selected httpClient (fetch, xhr, node or axios) - * @param indent Indentation options (4, 2 or tab) * @param clientName Custom client class name * @param request Path to custom request file */ @@ -23,31 +16,18 @@ export const writeClientCore = async ( client: Client, templates: Templates, outputPath: string, - httpClient: HttpClient, - indent: Indent, clientName?: string, request?: string ): Promise => { - const httpRequest = getHttpRequestName(httpClient); const context = { - httpClient, clientName, - httpRequest, server: client.server, version: client.version, }; - await writeFile(resolve(outputPath, 'OpenAPI.ts'), i(templates.core.settings(context), indent)); - await writeFile(resolve(outputPath, 'ApiError.ts'), i(templates.core.apiError(context), indent)); - await writeFile(resolve(outputPath, 'ApiRequestOptions.ts'), i(templates.core.apiRequestOptions(context), indent)); - await writeFile(resolve(outputPath, 'ApiResult.ts'), i(templates.core.apiResult(context), indent)); - await writeFile(resolve(outputPath, 'CancelablePromise.ts'), i(templates.core.cancelablePromise(context), indent)); - await writeFile(resolve(outputPath, 'request.ts'), i(templates.core.request(context), indent)); + const content = templates.core.baseHttpRequest(context); - if (isDefined(clientName)) { - await writeFile(resolve(outputPath, 'BaseHttpRequest.ts'), i(templates.core.baseHttpRequest(context), indent)); - await writeFile(resolve(outputPath, `${httpRequest}.ts`), i(templates.core.httpRequest(context), indent)); - } + await writeFile(resolve(`${outputPath}.ts`), content); if (request) { const requestFile = resolve(process.cwd(), request); diff --git a/src/utils/writeClientIndex.spec.ts b/src/utils/writeClientIndex.spec.ts deleted file mode 100644 index 6284dfd2e..000000000 --- a/src/utils/writeClientIndex.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { Client } from '../client/interfaces/Client'; -import { writeFile } from './fileSystem'; -import type { Templates } from './registerHandlebarTemplates'; -import { writeClientIndex } from './writeClientIndex'; - -jest.mock('./fileSystem'); - -describe('writeClientIndex', () => { - it('should write to filesystem', async () => { - const client: Client = { - server: 'http://localhost:8080', - version: '1.0', - models: [], - services: [], - }; - - const templates: Templates = { - index: () => 'index', - client: () => 'client', - exports: { - model: () => 'model', - schema: () => 'schema', - service: () => 'service', - }, - core: { - settings: () => 'settings', - apiError: () => 'apiError', - apiRequestOptions: () => 'apiRequestOptions', - apiResult: () => 'apiResult', - cancelablePromise: () => 'cancelablePromise', - request: () => 'request', - baseHttpRequest: () => 'baseHttpRequest', - httpRequest: () => 'httpRequest', - }, - }; - - await writeClientIndex(client, templates, '/', true, true, true, true, true, 'Service'); - - expect(writeFile).toBeCalledWith('/index.ts', 'index'); - }); -}); diff --git a/src/utils/writeClientIndex.ts b/src/utils/writeClientIndex.ts deleted file mode 100644 index eaecd1b40..000000000 --- a/src/utils/writeClientIndex.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { resolve } from 'path'; - -import type { Client } from '../client/interfaces/Client'; -import { writeFile } from './fileSystem'; -import { isDefined } from './isDefined'; -import { Templates } from './registerHandlebarTemplates'; -import { sortModelsByName } from './sortModelsByName'; -import { sortServicesByName } from './sortServicesByName'; - -/** - * Generate the OpenAPI client index file using the Handlebar template and write it to disk. - * The index file just contains all the exports you need to use the client as a standalone - * library. But yuo can also import individual models and services directly. - * @param client Client object, containing, models, schemas and services - * @param templates The loaded handlebar templates - * @param outputPath Directory to write the generated files to - * @param useUnionTypes Use union types instead of enums - * @param exportCore Generate core - * @param exportServices Generate services - * @param exportModels Generate models - * @param exportSchemas Generate schemas - * @param postfix Service name postfix - * @param clientName Custom client class name - */ -export const writeClientIndex = async ( - client: Client, - templates: Templates, - outputPath: string, - useUnionTypes: boolean, - exportCore: boolean, - exportServices: boolean, - exportModels: boolean, - exportSchemas: boolean, - postfix: string, - clientName?: string -): Promise => { - const templateResult = templates.index({ - exportCore, - exportServices, - exportModels, - exportSchemas, - useUnionTypes, - postfix, - clientName, - server: client.server, - version: client.version, - models: sortModelsByName(client.models), - services: sortServicesByName(client.services), - exportClient: isDefined(clientName), - }); - - await writeFile(resolve(outputPath, 'index.ts'), templateResult); -}; diff --git a/src/utils/writeClientModels.spec.ts b/src/utils/writeClientModels.spec.ts index 81b7b58b6..8beca0129 100644 --- a/src/utils/writeClientModels.spec.ts +++ b/src/utils/writeClientModels.spec.ts @@ -1,6 +1,4 @@ import type { Model } from '../client/interfaces/Model'; -import { HttpClient } from '../HttpClient'; -import { Indent } from '../Indent'; import { writeFile } from './fileSystem'; import type { Templates } from './registerHandlebarTemplates'; import { writeClientModels } from './writeClientModels'; @@ -30,26 +28,17 @@ describe('writeClientModels', () => { ]; const templates: Templates = { - index: () => 'index', - client: () => 'client', exports: { model: () => 'model', schema: () => 'schema', service: () => 'service', }, core: { - settings: () => 'settings', - apiError: () => 'apiError', - apiRequestOptions: () => 'apiRequestOptions', - apiResult: () => 'apiResult', - cancelablePromise: () => 'cancelablePromise', - request: () => 'request', baseHttpRequest: () => 'baseHttpRequest', - httpRequest: () => 'httpRequest', }, }; - await writeClientModels(models, templates, '/', HttpClient.FETCH, false, Indent.SPACE_4); + await writeClientModels(models, templates, '/', false); expect(writeFile).toBeCalledWith('/User.ts', 'model'); }); diff --git a/src/utils/writeClientModels.ts b/src/utils/writeClientModels.ts index 997569b9f..2a4f8f460 100644 --- a/src/utils/writeClientModels.ts +++ b/src/utils/writeClientModels.ts @@ -1,11 +1,8 @@ import { resolve } from 'path'; +import prettier from 'prettier'; import type { Model } from '../client/interfaces/Model'; -import type { HttpClient } from '../HttpClient'; -import type { Indent } from '../Indent'; import { writeFile } from './fileSystem'; -import { formatCode as f } from './formatCode'; -import { formatIndentation as i } from './formatIndentation'; import type { Templates } from './registerHandlebarTemplates'; /** @@ -13,25 +10,16 @@ import type { Templates } from './registerHandlebarTemplates'; * @param models Array of Models to write * @param templates The loaded handlebar templates * @param outputPath Directory to write the generated files to - * @param httpClient The selected httpClient (fetch, xhr, node or axios) * @param useUnionTypes Use union types instead of enums - * @param indent Indentation options (4, 2 or tab) */ export const writeClientModels = async ( models: Model[], templates: Templates, outputPath: string, - httpClient: HttpClient, - useUnionTypes: boolean, - indent: Indent + useUnionTypes: boolean ): Promise => { - for (const model of models) { - const file = resolve(outputPath, `${model.name}.ts`); - const templateResult = templates.exports.model({ - ...model, - httpClient, - useUnionTypes, - }); - await writeFile(file, i(f(templateResult), indent)); - } + const file = resolve(`${outputPath}.ts`); + const templateResult = models.map(model => templates.exports.model({ ...model, useUnionTypes })).join('\n'); + const prettireConfig = await prettier.resolveConfig(process.cwd()); + await writeFile(file, prettier.format(templateResult, prettireConfig ?? {})); }; diff --git a/src/utils/writeClientSchemas.spec.ts b/src/utils/writeClientSchemas.spec.ts index 499aba3e8..217595eaf 100644 --- a/src/utils/writeClientSchemas.spec.ts +++ b/src/utils/writeClientSchemas.spec.ts @@ -1,6 +1,4 @@ import type { Model } from '../client/interfaces/Model'; -import { HttpClient } from '../HttpClient'; -import { Indent } from '../Indent'; import { writeFile } from './fileSystem'; import type { Templates } from './registerHandlebarTemplates'; import { writeClientSchemas } from './writeClientSchemas'; @@ -30,26 +28,17 @@ describe('writeClientSchemas', () => { ]; const templates: Templates = { - index: () => 'index', - client: () => 'client', exports: { model: () => 'model', schema: () => 'schema', service: () => 'service', }, core: { - settings: () => 'settings', - apiError: () => 'apiError', - apiRequestOptions: () => 'apiRequestOptions', - apiResult: () => 'apiResult', - cancelablePromise: () => 'cancelablePromise', - request: () => 'request', baseHttpRequest: () => 'baseHttpRequest', - httpRequest: () => 'httpRequest', }, }; - await writeClientSchemas(models, templates, '/', HttpClient.FETCH, false, Indent.SPACE_4); + await writeClientSchemas(models, templates, '/', false); expect(writeFile).toBeCalledWith('/$User.ts', 'schema'); }); diff --git a/src/utils/writeClientSchemas.ts b/src/utils/writeClientSchemas.ts index e1c885f64..27b226b9a 100644 --- a/src/utils/writeClientSchemas.ts +++ b/src/utils/writeClientSchemas.ts @@ -1,11 +1,8 @@ import { resolve } from 'path'; +import prettier from 'prettier'; import type { Model } from '../client/interfaces/Model'; -import type { HttpClient } from '../HttpClient'; -import type { Indent } from '../Indent'; import { writeFile } from './fileSystem'; -import { formatCode as f } from './formatCode'; -import { formatIndentation as i } from './formatIndentation'; import type { Templates } from './registerHandlebarTemplates'; /** @@ -13,25 +10,22 @@ import type { Templates } from './registerHandlebarTemplates'; * @param models Array of Models to write * @param templates The loaded handlebar templates * @param outputPath Directory to write the generated files to - * @param httpClient The selected httpClient (fetch, xhr, node or axios) * @param useUnionTypes Use union types instead of enums - * @param indent Indentation options (4, 2 or tab) */ export const writeClientSchemas = async ( models: Model[], templates: Templates, outputPath: string, - httpClient: HttpClient, - useUnionTypes: boolean, - indent: Indent + useUnionTypes: boolean ): Promise => { for (const model of models) { const file = resolve(outputPath, `$${model.name}.ts`); const templateResult = templates.exports.schema({ ...model, - httpClient, useUnionTypes, }); - await writeFile(file, i(f(templateResult), indent)); + + const prettireConfig = await prettier.resolveConfig(process.cwd()); + await writeFile(file, prettier.format(templateResult, prettireConfig ?? {})); } }; diff --git a/src/utils/writeClientServices.spec.ts b/src/utils/writeClientServices.spec.ts index 38a649483..dbf10a960 100644 --- a/src/utils/writeClientServices.spec.ts +++ b/src/utils/writeClientServices.spec.ts @@ -1,6 +1,4 @@ import type { Service } from '../client/interfaces/Service'; -import { HttpClient } from '../HttpClient'; -import { Indent } from '../Indent'; import { writeFile } from './fileSystem'; import type { Templates } from './registerHandlebarTemplates'; import { writeClientServices } from './writeClientServices'; @@ -18,26 +16,17 @@ describe('writeClientServices', () => { ]; const templates: Templates = { - index: () => 'index', - client: () => 'client', exports: { model: () => 'model', schema: () => 'schema', service: () => 'service', }, core: { - settings: () => 'settings', - apiError: () => 'apiError', - apiRequestOptions: () => 'apiRequestOptions', - apiResult: () => 'apiResult', - cancelablePromise: () => 'cancelablePromise', - request: () => 'request', baseHttpRequest: () => 'baseHttpRequest', - httpRequest: () => 'httpRequest', }, }; - await writeClientServices(services, templates, '/', HttpClient.FETCH, false, false, Indent.SPACE_4, 'Service'); + await writeClientServices(services, templates, '/', false, false, 'Service'); expect(writeFile).toBeCalledWith('/UserService.ts', 'service'); }); diff --git a/src/utils/writeClientServices.ts b/src/utils/writeClientServices.ts index 2f95341d2..84ebc201a 100644 --- a/src/utils/writeClientServices.ts +++ b/src/utils/writeClientServices.ts @@ -1,11 +1,8 @@ import { resolve } from 'path'; +import prettier from 'prettier'; import type { Service } from '../client/interfaces/Service'; -import type { HttpClient } from '../HttpClient'; -import type { Indent } from '../Indent'; import { writeFile } from './fileSystem'; -import { formatCode as f } from './formatCode'; -import { formatIndentation as i } from './formatIndentation'; import { isDefined } from './isDefined'; import type { Templates } from './registerHandlebarTemplates'; @@ -14,10 +11,8 @@ import type { Templates } from './registerHandlebarTemplates'; * @param services Array of Services to write * @param templates The loaded handlebar templates * @param outputPath Directory to write the generated files to - * @param httpClient The selected httpClient (fetch, xhr, node or axios) * @param useUnionTypes Use union types instead of enums * @param useOptions Use options or arguments functions - * @param indent Indentation options (4, 2 or tab) * @param postfix Service name postfix * @param clientName Custom client class name */ @@ -25,23 +20,33 @@ export const writeClientServices = async ( services: Service[], templates: Templates, outputPath: string, - httpClient: HttpClient, useUnionTypes: boolean, useOptions: boolean, - indent: Indent, postfix: string, clientName?: string ): Promise => { - for (const service of services) { - const file = resolve(outputPath, `${service.name}${postfix}.ts`); - const templateResult = templates.exports.service({ - ...service, - httpClient, - useUnionTypes, - useOptions, - postfix, - exportClient: isDefined(clientName), - }); - await writeFile(file, i(f(templateResult), indent)); - } + const file = resolve(`${outputPath}.ts`); + const service = services.reduce( + (acc, curr) => { + acc.operations.push(...curr.operations); + acc.imports.push(...curr.imports); + return acc; + }, + { name: 'Company', imports: [], operations: [] } as Service + ); + service.imports = Array.from(new Set(service.imports)); + service.operations = Array.from(new Set(service.operations)); + // console.dir( + // service.operations.filter(x => x.path === '/crm/v3/objects/companies/batch/archive'), + // { depth: 9 } + // ); + const templateResult = templates.exports.service({ + ...service, + useUnionTypes, + useOptions, + postfix, + exportClient: isDefined(clientName), + }); + const prettireConfig = await prettier.resolveConfig(process.cwd()); + await writeFile(file, prettier.format(templateResult, prettireConfig ?? {})); }; diff --git a/test/e2e/assets/index.html b/test/e2e/assets/index.html deleted file mode 100644 index ff6dd5554..000000000 --- a/test/e2e/assets/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/test/e2e/assets/main-angular.ts b/test/e2e/assets/main-angular.ts deleted file mode 100644 index 1ed564d2f..000000000 --- a/test/e2e/assets/main-angular.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { HttpClientModule } from '@angular/common/http'; -import { Component, NgModule } from '@angular/core'; -import { BrowserModule } from '@angular/platform-browser'; -import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; - -import { OpenAPI } from './core/OpenAPI'; -import { CollectionFormatService } from './services/CollectionFormatService'; -import { ComplexService } from './services/ComplexService'; -import { DefaultService } from './services/DefaultService'; -import { DefaultsService } from './services/DefaultsService'; -import { DuplicateService } from './services/DuplicateService'; -import { ErrorService } from './services/ErrorService'; -import { HeaderService } from './services/HeaderService'; -import { MultipleTags1Service } from './services/MultipleTags1Service'; -import { MultipleTags2Service } from './services/MultipleTags2Service'; -import { MultipleTags3Service } from './services/MultipleTags3Service'; -import { NoContentService } from './services/NoContentService'; -import { ParametersService } from './services/ParametersService'; -import { ResponseService } from './services/ResponseService'; -import { SimpleService } from './services/SimpleService'; -import { TypesService } from './services/TypesService'; - -@Component({ - selector: 'app-root', - template: `
Angular is ready
`, -}) -export class AppComponent { - constructor( - private readonly collectionFormatService: CollectionFormatService, - private readonly complexService: ComplexService, - private readonly defaultService: DefaultService, - private readonly defaultsService: DefaultsService, - private readonly duplicateService: DuplicateService, - private readonly errorService: ErrorService, - private readonly headerService: HeaderService, - private readonly multipleTags1Service: MultipleTags1Service, - private readonly multipleTags2Service: MultipleTags2Service, - private readonly multipleTags3Service: MultipleTags3Service, - private readonly noContentService: NoContentService, - private readonly parametersService: ParametersService, - private readonly responseService: ResponseService, - private readonly simpleService: SimpleService, - private readonly typesService: TypesService - ) { - (window as any).api = { - OpenAPI, - CollectionFormatService: this.collectionFormatService, - ComplexService: this.complexService, - DefaultService: this.defaultService, - DefaultsService: this.defaultsService, - DuplicateService: this.duplicateService, - ErrorService: this.errorService, - HeaderService: this.headerService, - MultipleTags1Service: this.multipleTags1Service, - MultipleTags2Service: this.multipleTags2Service, - MultipleTags3Service: this.multipleTags3Service, - NoContentService: this.noContentService, - ParametersService: this.parametersService, - ResponseService: this.responseService, - SimpleService: this.simpleService, - TypesService: this.typesService, - }; - } -} - -@NgModule({ - imports: [BrowserModule, HttpClientModule], - providers: [ - CollectionFormatService, - ComplexService, - DefaultService, - DefaultsService, - DuplicateService, - ErrorService, - HeaderService, - MultipleTags1Service, - MultipleTags2Service, - MultipleTags3Service, - NoContentService, - ParametersService, - ResponseService, - SimpleService, - TypesService, - ], - bootstrap: [AppComponent], -}) -export class AppModule {} - -platformBrowserDynamic() - .bootstrapModule(AppModule) - .catch(err => console.error(err)); diff --git a/test/e2e/assets/main.ts b/test/e2e/assets/main.ts deleted file mode 100644 index 4bbf7cd3b..000000000 --- a/test/e2e/assets/main.ts +++ /dev/null @@ -1,3 +0,0 @@ -import * as api from './index'; - -(window as any).api = api; diff --git a/test/e2e/scripts/generateClient.ts b/test/e2e/scripts/generateClient.ts index 9c0402528..9a6b2c1f1 100644 --- a/test/e2e/scripts/generateClient.ts +++ b/test/e2e/scripts/generateClient.ts @@ -3,7 +3,6 @@ import { generate as __generate } from '../../../'; export const generateClient = async ( dir: string, version: string, - client: 'fetch' | 'xhr' | 'node' | 'axios' | 'angular', useOptions: boolean = false, useUnionTypes: boolean = false, clientName?: string @@ -11,7 +10,6 @@ export const generateClient = async ( await __generate({ input: `./test/spec/${version}.json`, output: `./test/e2e/generated/${dir}/`, - httpClient: client, useOptions, useUnionTypes, clientName, diff --git a/test/index.js b/test/index.js index 2d4bc491c..da091205c 100644 --- a/test/index.js +++ b/test/index.js @@ -7,17 +7,12 @@ const generate = async (input, output) => { await OpenAPI.generate({ input, output, - httpClient: OpenAPI.HttpClient.FETCH, useOptions: false, useUnionTypes: false, exportCore: true, exportSchemas: true, exportModels: true, exportServices: true, - // clientName: 'DemoAppClient', - // indent: OpenAPI.Indent.SPACE_2, - // postfix: 'Api', - // request: './test/custom/request.ts', }); }; diff --git a/test/index.spec.ts b/test/index.spec.ts index 78a0197d5..c2d7fb5b9 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -1,14 +1,13 @@ import { readFileSync } from 'fs'; import { sync } from 'glob'; -import { generate, HttpClient } from '../'; +import { generate } from '../'; describe('v2', () => { it('should generate', async () => { await generate({ input: './test/spec/v2.json', output: './test/generated/v2/', - httpClient: HttpClient.FETCH, useOptions: false, useUnionTypes: false, exportCore: true, @@ -29,7 +28,6 @@ describe('v3', () => { await generate({ input: './test/spec/v3.json', output: './test/generated/v3/', - httpClient: HttpClient.FETCH, useOptions: false, useUnionTypes: false, exportCore: true, diff --git a/types/index.d.ts b/types/index.d.ts index a4bd6fa28..ae988e432 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,21 +1,6 @@ -export declare enum HttpClient { - FETCH = 'fetch', - XHR = 'xhr', - NODE = 'node', - AXIOS = 'axios', - ANGULAR = 'angular', -} - -export declare enum Indent { - SPACE_4 = '4', - SPACE_2 = '2', - TAB = 'tab', -} - export type Options = { input: string | Record; output: string; - httpClient?: HttpClient | 'fetch' | 'xhr' | 'node' | 'axios' | 'angular'; clientName?: string; useOptions?: boolean; useUnionTypes?: boolean; @@ -23,7 +8,6 @@ export type Options = { exportServices?: boolean; exportModels?: boolean; exportSchemas?: boolean; - indent?: Indent | '4' | '2' | 'tab'; postfix?: string; request?: string; write?: boolean; @@ -31,8 +15,4 @@ export type Options = { export declare function generate(options: Options): Promise; -export default { - HttpClient, - Indent, - generate, -}; +export default { generate };