From 2e1aac428bcaa924ed47ee37c3e33e983e40e490 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Mon, 30 Nov 2020 15:02:53 +0700 Subject: [PATCH 1/8] Added custom httpClient generation --- README.md | 23 +- bin/index.js | 4 +- package.json | 22 +- src/index.ts | 8 +- src/templates/core/functions/getUrl.hbs | 2 +- src/templates/core/httpClient/request.hbs | 26 + src/templates/core/httpClient/sendRequest.hbs | 15 + src/templates/core/request.hbs | 1 + src/utils/registerHandlebarTemplates.ts | 6 + src/utils/writeClient.ts | 6 +- src/utils/writeClientServices.ts | 12 +- test/__snapshots__/index.spec.js.snap | 6 +- test/spec/creditContract.yaml | 591 ++++++++++++++++++ 13 files changed, 691 insertions(+), 31 deletions(-) create mode 100644 src/templates/core/httpClient/request.hbs create mode 100644 src/templates/core/httpClient/sendRequest.hbs create mode 100644 test/spec/creditContract.yaml diff --git a/README.md b/README.md index 824c675e3..cf1dc48e6 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ - Supports JSON and YAML files for input - Supports generation through CLI, Node.js and NPX - Supports tsc and @babel/plugin-transform-typescript +- Supports custom httpClients with methods GET, POST, PUT, DELETE ## Install @@ -37,21 +38,23 @@ $ openapi --help Usage: openapi [options] Options: - -V, --version output the version number - -i, --input OpenAPI specification, can be a path, url or string content (required) - -o, --output Output directory (required) - -c, --client HTTP client to generate [fetch, xhr, node] (default: "fetch") - --useOptions Use options instead of arguments - --useUnionTypes Use union types instead of enums - --exportCore Write core files to disk (default: true) - --exportServices Write services to disk (default: true) - --exportModels Write models to disk (default: true) - --exportSchemas Write schemas to disk (default: false) + -V, --version output the version number + -i, --input OpenAPI specification, can be a path, url or string content (required) + -o, --output Output directory (required) + -c, --client HTTP client to generate [fetch, xhr, node, httpClient] (default: "fetch") + --httpClientLibrary Library for httpClient with methods GET, POST, PUT, DELETE + --useOptions Use options instead of arguments + --useUnionTypes Use union types instead of enums + --exportCore Write core files to disk (default: true) + --exportServices Write services to disk (default: true) + --exportModels Write models to disk (default: true) + --exportSchemas Write schemas to disk (default: false) Examples $ openapi --input ./spec.json $ openapi --input ./spec.json --output ./dist $ openapi --input ./spec.json --output ./dist --client xhr + $ openapi --input ./spec.json --output ./dist --client httpClient --httpClientLibrary @myapp/XHR/HttpClient ``` diff --git a/bin/index.js b/bin/index.js index 99605b784..3b0dcbe24 100755 --- a/bin/index.js +++ b/bin/index.js @@ -12,7 +12,8 @@ program .version(pkg.version) .requiredOption('-i, --input ', 'OpenAPI specification, can be a path, url or string content (required)') .requiredOption('-o, --output ', 'Output directory (required)') - .option('-c, --client ', 'HTTP client to generate [fetch, xhr, node]', 'fetch') + .option('-c, --client ', 'HTTP client to generate [fetch, xhr, node, httpClient]', 'fetch') + .option('--httpClientLibrary ', 'Library for httpClient with methods GET, POST, PUT, DELETE', '') .option('--useOptions', 'Use options instead of arguments') .option('--useUnionTypes', 'Use union types instead of enums') .option('--exportCore ', 'Write core files to disk', true) @@ -28,6 +29,7 @@ if (OpenAPI) { input: program.input, output: program.output, httpClient: program.client, + httpClientLibrary: program.httpClientLibrary, useOptions: program.useOptions, useUnionTypes: program.useUnionTypes, exportCore: JSON.parse(program.exportCore) === true, diff --git a/package.json b/package.json index 8e866949c..b38d247ba 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,15 @@ { - "name": "openapi-typescript-codegen", - "version": "0.7.0", - "description": "Library that generates Typescript clients based on the OpenAPI specification.", - "author": "Ferdi Koomen", - "homepage": "https://github.com/ferdikoomen/openapi-typescript-codegen", + "name": "openapi-typescript-codegen-with-custom-client", + "version": "0.0.1", + "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", + "author": "Sundved", + "homepage": "https://github.com/Sundved/openapi-typescript-codegen", "repository": { "type": "git", - "url": "git+https://github.com/ferdikoomen/openapi-typescript-codegen.git" + "url": "git+https://github.com/Sundved/openapi-typescript-codegen.git" }, "bugs": { - "url": "https://github.com/ferdikoomen/openapi-typescript-codegen/issues" + "url": "https://github.com/Sundved/openapi-typescript-codegen/issues" }, "license": "MIT", "keywords": [ @@ -27,8 +27,8 @@ ], "maintainers": [ { - "name": "Ferdi Koomen", - "email": "info@madebyferdi.com" + "name": "Sundved", + "email": "sundved@gmail.com" } ], "main": "dist/index.js", @@ -57,8 +57,7 @@ "eslint:fix": "eslint \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --fix", "prettier": "prettier \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --check", "prettier:fix": "prettier \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --write", - "prepublish": "yarn run clean && yarn run release", - "codecov": "codecov --token=66c30c23-8954-4892-bef9-fbaed0a2e42b" + "prepublish": "yarn run clean && yarn run release" }, "dependencies": { "camelcase": "^6.2.0", @@ -82,7 +81,6 @@ "@types/node-fetch": "2.5.7", "@typescript-eslint/eslint-plugin": "4.8.1", "@typescript-eslint/parser": "4.8.2", - "codecov": "3.8.1", "eslint": "7.14.0", "eslint-config-prettier": "6.15.0", "eslint-plugin-prettier": "3.1.4", diff --git a/src/index.ts b/src/index.ts index c098715c4..f47a33e2c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ export enum HttpClient { FETCH = 'fetch', XHR = 'xhr', NODE = 'node', + HTTP_CLIENT = 'httpClient', } export type Options = { @@ -23,6 +24,7 @@ export type Options = { exportServices?: boolean; exportModels?: boolean; exportSchemas?: boolean; + httpClientLibrary?: string; write?: boolean; }; @@ -39,6 +41,7 @@ export type Options = { * @param exportServices: Generate services * @param exportModels: Generate models * @param exportSchemas: Generate schemas + * @param httpClientLibrary Library for httpClient * @param write Write the files to disk (true or false) */ export async function generate({ @@ -51,6 +54,7 @@ export async function generate({ exportServices = true, exportModels = true, exportSchemas = false, + httpClientLibrary = '', write = true, }: Options): Promise { const openApi = isString(input) ? await getOpenApiSpec(input) : input; @@ -62,7 +66,7 @@ export async function generate({ const client = parseV2(openApi); const clientFinal = postProcessClient(client); if (!write) break; - await writeClient(clientFinal, templates, output, httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas); + await writeClient(clientFinal, templates, output, httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas, httpClientLibrary); break; } @@ -70,7 +74,7 @@ export async function generate({ const client = parseV3(openApi); const clientFinal = postProcessClient(client); if (!write) break; - await writeClient(clientFinal, templates, output, httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas); + await writeClient(clientFinal, templates, output, httpClient, useOptions, useUnionTypes, exportCore, exportServices, exportModels, exportSchemas, httpClientLibrary); break; } } diff --git a/src/templates/core/functions/getUrl.hbs b/src/templates/core/functions/getUrl.hbs index be040bbb6..0cb791a86 100644 --- a/src/templates/core/functions/getUrl.hbs +++ b/src/templates/core/functions/getUrl.hbs @@ -3,7 +3,7 @@ function getUrl(options: ApiRequestOptions): string { const url = `${OpenAPI.BASE}${path}`; if (options.query) { - return `${url}${getQueryString(options.query)}`; + return `${url}${getQueryString({...options.query, ts: new Date().getTime()})}`; } return url; } diff --git a/src/templates/core/httpClient/request.hbs b/src/templates/core/httpClient/request.hbs new file mode 100644 index 000000000..92232017f --- /dev/null +++ b/src/templates/core/httpClient/request.hbs @@ -0,0 +1,26 @@ +{{>header}} +import type { ApiRequestOptions } from './ApiRequestOptions'; +import { OpenAPI } from './OpenAPI'; + +{{>functions/isDefined}} + + +{{>functions/getQueryString}} + + +{{>functions/getUrl}} + + +{{>httpClient/sendRequest}} + + +/** + * Request using XHR client + * @param options The request options from the the service + * @result ApiResult + */ +export function request(options: ApiRequestOptions): Promise { + const url = getUrl(options); + + return sendRequest(options, url); +} diff --git a/src/templates/core/httpClient/sendRequest.hbs b/src/templates/core/httpClient/sendRequest.hbs new file mode 100644 index 000000000..9195f2804 --- /dev/null +++ b/src/templates/core/httpClient/sendRequest.hbs @@ -0,0 +1,15 @@ +import {DELETE, GET, POST, PUT} from '{{>httpClientLibrary}}'; + +async function sendRequest(options: ApiRequestOptions, url: string): Promise { + + switch (options.method) { + case 'GET': + return GET(url); + case 'POST': + return POST(url, getRequestBody(options)); + case 'PUT': + return PUT(url, getRequestBody(options)); + case 'DELETE': + return DELETE(url, getRequestBody(options)); + } +} diff --git a/src/templates/core/request.hbs b/src/templates/core/request.hbs index 2a32097e5..0f7770acd 100644 --- a/src/templates/core/request.hbs +++ b/src/templates/core/request.hbs @@ -1,3 +1,4 @@ {{#equals @root.httpClient 'fetch'}}{{>fetch/request}}{{/equals}} {{#equals @root.httpClient 'xhr'}}{{>xhr/request}}{{/equals}} {{#equals @root.httpClient 'node'}}{{>node/request}}{{/equals}} +{{#equals @root.httpClient 'httpClient'}}{{>httpClient/request}}{{/equals}} diff --git a/src/utils/registerHandlebarTemplates.ts b/src/utils/registerHandlebarTemplates.ts index 6772eebd5..3a1c2be31 100644 --- a/src/utils/registerHandlebarTemplates.ts +++ b/src/utils/registerHandlebarTemplates.ts @@ -20,6 +20,8 @@ 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 httpClientRequest from '../templates/core/httpClient/request.hbs'; +import httpClientSendRequest from '../templates/core/httpClient/sendRequest.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'; @@ -165,6 +167,10 @@ export function registerHandlebarTemplates(): Templates { Handlebars.registerPartial('xhr/sendRequest', Handlebars.template(xhrSendRequest)); Handlebars.registerPartial('xhr/request', Handlebars.template(xhrRequest)); + // Specific files for the httpClient client implementation + Handlebars.registerPartial('httpClient/sendRequest', Handlebars.template(httpClientSendRequest)); + Handlebars.registerPartial('httpClient/request', Handlebars.template(httpClientRequest)); + // Specific files for the node client implementation Handlebars.registerPartial('node/getHeaders', Handlebars.template(nodeGetHeaders)); Handlebars.registerPartial('node/getRequestBody', Handlebars.template(nodeGetRequestBody)); diff --git a/src/utils/writeClient.ts b/src/utils/writeClient.ts index 4c4cb3c25..1e14aa7e7 100644 --- a/src/utils/writeClient.ts +++ b/src/utils/writeClient.ts @@ -23,6 +23,7 @@ import { writeClientServices } from './writeClientServices'; * @param exportServices: Generate services * @param exportModels: Generate models * @param exportSchemas: Generate schemas + * @param httpClientLibrary: Library for httpClient */ export async function writeClient( client: Client, @@ -34,7 +35,8 @@ export async function writeClient( exportCore: boolean, exportServices: boolean, exportModels: boolean, - exportSchemas: boolean + exportSchemas: boolean, + httpClientLibrary: string ): Promise { const outputPath = path.resolve(process.cwd(), output); const outputPathCore = path.resolve(outputPath, 'core'); @@ -55,7 +57,7 @@ export async function writeClient( if (exportServices) { await rmdir(outputPathServices); await mkdir(outputPathServices); - await writeClientServices(client.services, templates, outputPathServices, httpClient, useUnionTypes, useOptions); + await writeClientServices(client.services, templates, outputPathServices, httpClient, useUnionTypes, useOptions, httpClientLibrary); } if (exportSchemas) { diff --git a/src/utils/writeClientServices.ts b/src/utils/writeClientServices.ts index 6387356d8..8d0c7eea6 100644 --- a/src/utils/writeClientServices.ts +++ b/src/utils/writeClientServices.ts @@ -16,8 +16,17 @@ const VERSION_TEMPLATE_STRING = 'OpenAPI.VERSION'; * @param httpClient The selected httpClient (fetch, xhr or node) * @param useUnionTypes Use union types instead of enums * @param useOptions Use options or arguments functions + * @param httpClientLibrary Library for httpClient */ -export async function writeClientServices(services: Service[], templates: Templates, outputPath: string, httpClient: HttpClient, useUnionTypes: boolean, useOptions: boolean): Promise { +export async function writeClientServices( + services: Service[], + templates: Templates, + outputPath: string, + httpClient: HttpClient, + useUnionTypes: boolean, + useOptions: boolean, + httpClientLibrary: string +): Promise { for (const service of services) { const file = path.resolve(outputPath, `${service.name}.ts`); const useVersion = service.operations.some(operation => operation.path.includes(VERSION_TEMPLATE_STRING)); @@ -27,6 +36,7 @@ export async function writeClientServices(services: Service[], templates: Templa useUnionTypes, useVersion, useOptions, + httpClientLibrary, }); await writeFile(file, format(templateResult)); } diff --git a/test/__snapshots__/index.spec.js.snap b/test/__snapshots__/index.spec.js.snap index 5f230fc2f..b8ad72bba 100644 --- a/test/__snapshots__/index.spec.js.snap +++ b/test/__snapshots__/index.spec.js.snap @@ -131,7 +131,7 @@ function getUrl(options: ApiRequestOptions): string { const url = \`\${OpenAPI.BASE}\${path}\`; if (options.query) { - return \`\${url}\${getQueryString(options.query)}\`; + return \`\${url}\${getQueryString({...options.query, ts: new Date().getTime()})}\`; } return url; } @@ -284,6 +284,7 @@ export async function request(options: ApiRequestOptions): Promise { return result; } + " `; @@ -2374,7 +2375,7 @@ function getUrl(options: ApiRequestOptions): string { const url = \`\${OpenAPI.BASE}\${path}\`; if (options.query) { - return \`\${url}\${getQueryString(options.query)}\`; + return \`\${url}\${getQueryString({...options.query, ts: new Date().getTime()})}\`; } return url; } @@ -2527,6 +2528,7 @@ export async function request(options: ApiRequestOptions): Promise { return result; } + " `; diff --git a/test/spec/creditContract.yaml b/test/spec/creditContract.yaml new file mode 100644 index 000000000..94938a534 --- /dev/null +++ b/test/spec/creditContract.yaml @@ -0,0 +1,591 @@ +openapi: 3.0.1 +info: + title: Api Documentation + description: Api Documentation + termsOfService: urn:tos + contact: {} + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0 + version: "1.0" +servers: + - url: //localhost:8080/ +tags: + - name: /credit/contract + description: Кредитные договоры +paths: + /credit/contract/view: + post: + tags: + - /credit/contract + summary: Получение списка документов 'Информация о кредитных договорах' по заданным + фильтрам + operationId: getCreditContracts + requestBody: + description: Объект для параметров фильтрации документов 'Информация о кредитных + договорах' + content: + application/json: + schema: + $ref: '#/components/schemas/CreditContractViewFilter' + required: true + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/CreditContractListResponse' + 201: + description: Created + content: {} + 401: + description: Unauthorized + content: {} + 403: + description: Forbidden + content: {} + 404: + description: Not Found + content: {} + deprecated: false + x-codegen-request-body-name: filter + /credit/contract/{id}: + get: + tags: + - /credit/contract + summary: Получение документа 'Информация о кредитных договорах' по ID для страницы + деталей документа и редактирования существующего + operationId: getCreditContractById + parameters: + - name: id + in: path + description: ID документа 'Информация о кредитных договорах' + required: true + schema: + type: string + format: uuid + responses: + 200: + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ExtendedCreditContract' + 401: + description: Unauthorized + content: {} + 403: + description: Forbidden + content: {} + 404: + description: Not Found + content: {} + deprecated: false +components: + schemas: + Amount: + title: Amount + type: object + properties: + amount: + type: number + description: Сумма + example: 100.5 + currencyCode: + type: string + description: Числовой код валюты + example: "643" + currencyDescription: + type: string + description: Описание валюты (РОССИЙСКИЙ РУБЛЬ, ДОЛЛАР США, ЕВРО) + example: РОССИЙСКИЙ РУБЛЬ + currencyName: + type: string + description: Буквенный ISO-код валюты(USD/EUR/RUB) + example: RUB + description: Сумма + Branch: + title: Branch + type: object + properties: + code: + type: string + description: Код отделения + name: + type: string + description: Наименование подразделения, в котором обслуживается клиент. + description: Подразделение банка + CreditContractListResponse: + title: CreditContractListResponse + type: object + properties: + items: + type: array + description: Коллекция элементов + items: + $ref: '#/components/schemas/CreditContractView' + pagination: + $ref: '#/components/schemas/Pagination' + description: Обертка для списка с постраничной разбивкой + CreditContractView: + title: CreditContractView + type: object + properties: + acceptSuspensiveCondition: + type: boolean + description: Признак выполнения отлагательных условий + example: true + accountNumber: + type: string + description: Основной расчетный счет по кредитному договору + availableAmount: + $ref: '#/components/schemas/Amount' + contractAmount: + $ref: '#/components/schemas/Amount' + contractName: + type: string + description: Наименование кредитного договора + example: 1948. Кредит 'Доверие'; ЮЛ/ИП. Аннуитет. + contractNumber: + type: string + description: Номер документа + example: "12345" + credProdCode: + type: string + description: Код кредитного продукта + example: "2216" + creditDate: + type: string + description: Дата начала действия договора (выдачи средств) + format: date-time + creditDurationDays: + type: integer + description: Срок действия кредита в днях + format: int32 + example: 10 + creditLineAvailableAmount: + $ref: '#/components/schemas/Amount' + creditLineFinishDate: + type: string + description: 'Кредитная линия: Дата окончания выборки' + format: date-time + creditSegment: + type: string + description: Сегмент + example: "2" + debtAmount: + $ref: '#/components/schemas/Amount' + delayPeriodDays: + type: integer + description: Количество дней просрочки по кредитному договору + format: int32 + example: 10 + docDate: + type: string + description: Дата заключения договора + format: date-time + docType: + type: string + description: Тип документа + example: CreditContract + earlyRepaymentEnable: + type: boolean + description: Признак доступного досрочного погашения + example: true + endDate: + type: string + description: Дата окончания действия договора + example: "20171011" + hasReservationPayroll: + type: boolean + description: Признак наличия у организации зарплатного договора с резервированием + example: true + interestRate: + type: number + description: Актуальная ставка по кредиту + example: 1.1 + isClosed: + type: boolean + description: Признак закрытия + example: false + isCredit7Minutes: + type: boolean + description: Признак кредитного договора на кредит за 7 минут + example: false + isReglamentAllowed: + type: boolean + description: Признак разрешенного регламента для операции электронной выдачи + example: true + limitHistory: + type: array + description: График изменения лимита + items: + $ref: '#/components/schemas/LimitHistory' + monthlyPaymentDate: + type: string + description: Дата ежемесячного платежа + example: "20171011" + moratoriumDateEnd: + type: string + description: Дата окончания моратория + format: date-time + overdarftAvailableAmount: + $ref: '#/components/schemas/Amount' + overdraftLimitIndicator: + type: string + description: 'Овердрафт: индикатор изменения доступного лимита' + enum: + - REDUCED + - NOT_CHANGED + - INCREASED + productType: + type: string + description: Вид кредитного продукта + example: Кредит + restructAvailability: + type: string + description: Признак доступной реструктуризации по договору + example: YES + enum: + - YES + - NO + - STATE_AID + scheduledPaymentAmount: + $ref: '#/components/schemas/Amount' + scheduledPaymentDate: + type: string + description: Дата платежа (следующего) + format: date-time + updateDate: + type: string + description: Дата последнего обновления данных по кредитному контракту + format: date-time + description: Информация о кредитных договорах + CreditContractViewFilter: + title: CreditContractViewFilter + type: object + properties: + acceptSuspensiveCondition: + type: boolean + description: Признак выполнения отлагательных условий + example: true + dateFrom: + type: string + description: Дата начала + format: date-time + dateTo: + type: string + description: Дата окончания + format: date-time + isClosed: + type: boolean + description: Признак закрытия + example: false + isReglamentAllowed: + type: boolean + description: Признак разрешенного регламента для операции электронной выдачи + example: false + isTargetedCredit: + type: boolean + description: Признак целевого кредитования + example: false + number: + type: string + description: Номер документа + example: "1" + orderBy: + type: string + description: Сортировка + example: 'Формат: +fieldName или -fieldName' + pagination: + $ref: '#/components/schemas/Pagination' + productTypes: + type: array + description: Список видов кредитных продуктов + example: + - кредитная линия + - овердрафт + items: + type: string + segments: + type: array + description: Список сегментов + example: {} + items: + type: string + statusCodes: + type: array + description: Список статусов + example: {} + items: + type: string + description: Фильтр для отбора документов 'Информация о кредитных договорах' + ExtendedCreditContract: + title: ExtendedCreditContract + type: object + properties: + acceptSuspensiveCondition: + type: boolean + description: Признак выполнения отлагательных условий + example: true + accountNumber: + type: string + description: Основной расчетный счет по кредитному договору + availableAmount: + $ref: '#/components/schemas/Amount' + branch: + $ref: '#/components/schemas/Branch' + contractAmount: + $ref: '#/components/schemas/Amount' + contractId: + type: string + description: Идентификатор кредитного договора в ЕКС + example: "4688069399315" + contractName: + type: string + description: Наименование кредитного договора + example: 1948. Кредит 'Доверие'; ЮЛ/ИП. Аннуитет. + contractNumber: + type: string + description: Номер кредитного договора в ЕКС + example: 031/9031/022-340 + crConType: + type: string + description: Строковое описание типа кредита + example: 931 Корпоративное кредитование - возобновляемая кр линия с дифференцированными + ставками + credProdCode: + type: string + description: Код кредитного продукта + example: "1948" + creditDate: + type: string + description: Дата начала действия договора (выдачи средств) + format: date-time + creditDurationDays: + type: integer + description: Просрочка в днях + format: int32 + creditDurationMonths: + type: integer + description: Просрочка в месяцах + format: int32 + creditLineAvailableAmount: + $ref: '#/components/schemas/Amount' + creditLineFinishDate: + type: string + description: 'Кредитная линия: Дата окончания выборки' + format: date-time + creditSegment: + type: string + description: Сегмент + example: "2" + debtAmount: + $ref: '#/components/schemas/Amount' + debtorStatus: + type: string + description: Статус клиента + example: DEBTOR + delayPeriodDays: + type: integer + description: Количество дней просрочки по кредитному договору + format: int32 + example: 7 + docDate: + type: string + description: Дата заключения договора + format: date-time + docType: + type: string + description: Тип документа + example: CreditContract + earlyRepaymentEnable: + type: boolean + description: Признак доступного досрочного погашения + example: true + endDate: + type: string + description: Дата окончания действия договора + format: date-time + hasReservationPayroll: + type: boolean + description: Признак наличия у организации зарплатного договора с резервированием + example: true + interestRate: + type: number + description: Актуальная ставка по кредиту + example: 10.58 + isClosed: + type: boolean + description: Признак закрытия + example: false + isCredit7Minutes: + type: boolean + description: Признак кредитного договора на кредит за 7 минут + example: false + isReglamentAllowed: + type: boolean + description: Признак разрешенного регламента для операции электронной выдачи + example: true + isVklds: + type: boolean + description: Признак типа кредита ВКЛДС (Возобновляемая кр линия с дифференцированными + ставками) + example: false + limitDate: + type: string + description: Дата окончания периода доступности лимитных средств + format: date-time + limitHistory: + type: array + description: График изменения лимита + items: + $ref: '#/components/schemas/LimitHistory' + maxTrancheDuration: + type: integer + description: Максимальный срок транша (число дней) + format: int32 + example: 91 + moratoriumDateEnd: + type: string + description: Дата окончания моратория + format: date-time + orgName: + type: string + description: Наименование организации получателя кредита + example: ИП17 + orgTaxNumber: + type: string + description: ИНН организации получателя кредита + example: "4601234567" + overdarftAvailableAmount: + $ref: '#/components/schemas/Amount' + overdraftLimitIndicator: + type: string + description: 'Овердрафт: индикатор изменения доступного лимита' + enum: + - REDUCED + - NOT_CHANGED + - INCREASED + productType: + type: string + description: Вид кредитного продукта + example: кредитная линия + restructAvailability: + type: string + description: Признак доступной реструктуризации по договору + example: YES + enum: + - YES + - NO + - STATE_AID + restructRequestInfo: + $ref: '#/components/schemas/RestructRequestInfo' + scheduledPaymentAmount: + $ref: '#/components/schemas/Amount' + scheduledPaymentDate: + type: string + description: Дата следующего платежа + format: date-time + settlementAccounts: + type: array + description: Расчетные счета клиента для использования в рамках кредитного + договора + items: + type: string + trancheCount: + type: integer + description: Число траншей + format: int32 + example: 10 + updateDate: + type: string + description: Дата последнего обновления данных по кредитному контракту + format: date-time + description: Основная информация о кредитном договоре + LimitHistory: + title: LimitHistory + type: object + properties: + dateBegin: + type: string + description: Дата начала лимита + format: date-time + dateEnd: + type: string + description: Дата окончания лимита + format: date-time + period: + type: integer + description: Срок (в днях) + format: int32 + example: 91 + sum: + $ref: '#/components/schemas/Amount' + description: График изменения лимита + Pagination: + title: Pagination + type: object + properties: + count: + type: integer + description: Количество возвращаемых записей + format: int32 + hasNextPage: + type: boolean + description: Признак наличия следующей страницы + offset: + type: integer + description: Смещение от начала + format: int32 + description: Нумерация + RestructRequestInfo: + title: RestructRequestInfo + type: object + properties: + analysisType: + type: string + description: Вид анализа заявки + example: EXPRESS0 + enum: + - EXPRESS0 + - CF + - EXPRESS1 + - EXPRESS2 + - MANREPORT + - QUICKDECIS + - LEASINGFACT + - LEASINGFACTEXT + - CFRISKS + - R1D + - MFO + - KREDO + - CFSMART + - CCSMART + - CBC + - FACTORING + - RESTRUCT + - CCRESTRUCT + - CPFNS + - CPCustomWar + createDate: + type: string + description: Дата создания заявки + format: date-time + statusCode: + type: string + description: Статус + example: CREATED + technology: + type: string + description: Технология выбраного кредитного продукта + example: FACTORY + enum: + - FACTORY + - CONVEYOR + - QUICK + - LEASING + - CREDIT_1H + - FACTORING + description: Данные о заявке на реструктуризацию From 80f64cea4397f969a7b3d8a91be50f6e96a03d97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Mon, 30 Nov 2020 15:18:58 +0700 Subject: [PATCH 2/8] Added scoped name --- README.md | 3 + package.json | 198 +++++++++++++++++++++++++-------------------------- 2 files changed, 102 insertions(+), 99 deletions(-) diff --git a/README.md b/README.md index cf1dc48e6..53819c880 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,9 @@ [![Code Climate][climate-image]][climate-url] [![Downloads][downloads-image]][downloads-url] +## It's a fork. Original repository: +[Link](https://github.com/ferdikoomen/openapi-typescript-codegen) + > Node.js library that generates Typescript clients based on the OpenAPI specification. ## Why? diff --git a/package.json b/package.json index b38d247ba..5da16917c 100644 --- a/package.json +++ b/package.json @@ -1,101 +1,101 @@ { - "name": "openapi-typescript-codegen-with-custom-client", - "version": "0.0.1", - "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", - "author": "Sundved", - "homepage": "https://github.com/Sundved/openapi-typescript-codegen", - "repository": { - "type": "git", - "url": "git+https://github.com/Sundved/openapi-typescript-codegen.git" - }, - "bugs": { - "url": "https://github.com/Sundved/openapi-typescript-codegen/issues" - }, - "license": "MIT", - "keywords": [ - "openapi", - "swagger", - "codegen", - "generator", - "client", - "typescript", - "yaml", - "json", - "fetch", - "xhr", - "node" - ], - "maintainers": [ - { - "name": "Sundved", - "email": "sundved@gmail.com" - } - ], - "main": "dist/index.js", - "module": "dist/index.js", - "types": "types/index.d.ts", - "bin": { - "openapi": "bin/index.js" - }, - "files": [ - "bin/index.js", - "dist/index.js", - "types/index.d.ts" - ], - "scripts": { - "clean": "rimraf ./dist ./test/generated ./test/e2e/generated ./samples/generated ./coverage ./node_modules/.cache", - "build": "rollup --config --environment NODE_ENV:development", - "build:watch": "rollup --config --environment NODE_ENV:development --watch", - "release": "rollup --config --environment NODE_ENV:production", - "run": "node ./test/index.js", - "test": "jest --selectProjects UNIT", - "test:update": "jest --selectProjects UNIT --updateSnapshot", - "test:watch": "jest --selectProjects UNIT --watch", - "test:coverage": "jest --selectProjects UNIT --coverage", - "test:e2e": "jest --selectProjects E2E --runInBand", - "eslint": "eslint \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\"", - "eslint:fix": "eslint \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --fix", - "prettier": "prettier \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --check", - "prettier:fix": "prettier \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --write", - "prepublish": "yarn run clean && yarn run release" - }, - "dependencies": { - "camelcase": "^6.2.0", - "commander": "^6.2.0", - "handlebars": "^4.7.6", - "js-yaml": "^3.14.0", - "mkdirp": "^1.0.4", - "rimraf": "^3.0.2" - }, - "devDependencies": { - "@babel/cli": "7.12.8", - "@babel/core": "7.12.9", - "@babel/preset-env": "7.12.1", - "@babel/preset-typescript": "7.12.7", - "@rollup/plugin-commonjs": "16.0.0", - "@rollup/plugin-node-resolve": "10.0.0", - "@types/express": "4.17.9", - "@types/jest": "26.0.15", - "@types/js-yaml": "3.12.5", - "@types/node": "14.14.10", - "@types/node-fetch": "2.5.7", - "@typescript-eslint/eslint-plugin": "4.8.1", - "@typescript-eslint/parser": "4.8.2", - "eslint": "7.14.0", - "eslint-config-prettier": "6.15.0", - "eslint-plugin-prettier": "3.1.4", - "eslint-plugin-simple-import-sort": "6.0.1", - "express": "4.17.1", - "form-data": "3.0.0", - "glob": "7.1.6", - "jest": "26.6.3", - "jest-cli": "26.6.3", - "node-fetch": "2.6.1", - "prettier": "2.2.1", - "puppeteer": "5.4.1", - "rollup": "2.34.0", - "rollup-plugin-terser": "7.0.2", - "rollup-plugin-typescript2": "0.29.0", - "typescript": "4.1.2" - } + "name": "@sundved/openapi-typescript-codegen", + "version": "0.0.1", + "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", + "author": "Sundved", + "homepage": "https://github.com/Sundved/openapi-typescript-codegen", + "repository": { + "type": "git", + "url": "git+https://github.com/Sundved/openapi-typescript-codegen.git" + }, + "bugs": { + "url": "https://github.com/Sundved/openapi-typescript-codegen/issues" + }, + "license": "MIT", + "keywords": [ + "openapi", + "swagger", + "codegen", + "generator", + "client", + "typescript", + "yaml", + "json", + "fetch", + "xhr", + "node" + ], + "maintainers": [ + "Sundved " + ], + "main": "dist/index.js", + "module": "dist/index.js", + "types": "types/index.d.ts", + "bin": { + "openapi": "bin/index.js" + }, + "files": [ + "bin/index.js", + "dist/index.js", + "types/index.d.ts" + ], + "scripts": { + "clean": "rimraf ./dist ./test/generated ./test/e2e/generated ./samples/generated ./coverage ./node_modules/.cache", + "build": "rollup --config --environment NODE_ENV:development", + "build:watch": "rollup --config --environment NODE_ENV:development --watch", + "release": "rollup --config --environment NODE_ENV:production", + "run": "node ./test/index.js", + "test": "jest --selectProjects UNIT", + "test:update": "jest --selectProjects UNIT --updateSnapshot", + "test:watch": "jest --selectProjects UNIT --watch", + "test:coverage": "jest --selectProjects UNIT --coverage", + "test:e2e": "jest --selectProjects E2E --runInBand", + "eslint": "eslint \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\"", + "eslint:fix": "eslint \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --fix", + "prettier": "prettier \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --check", + "prettier:fix": "prettier \"./src/**/*.ts\" \"./bin/index.js\" \"./types/index.d.ts\" --write", + "prepublish": "yarn run clean && yarn run release" + }, + "dependencies": { + "camelcase": "^6.2.0", + "commander": "^6.2.0", + "handlebars": "^4.7.6", + "js-yaml": "^3.14.0", + "mkdirp": "^1.0.4", + "rimraf": "^3.0.2" + }, + "devDependencies": { + "@babel/cli": "7.12.8", + "@babel/core": "7.12.9", + "@babel/preset-env": "7.12.1", + "@babel/preset-typescript": "7.12.7", + "@rollup/plugin-commonjs": "16.0.0", + "@rollup/plugin-node-resolve": "10.0.0", + "@types/express": "4.17.9", + "@types/jest": "26.0.15", + "@types/js-yaml": "3.12.5", + "@types/node": "14.14.10", + "@types/node-fetch": "2.5.7", + "@typescript-eslint/eslint-plugin": "4.8.1", + "@typescript-eslint/parser": "4.8.2", + "eslint": "7.14.0", + "eslint-config-prettier": "6.15.0", + "eslint-plugin-prettier": "3.1.4", + "eslint-plugin-simple-import-sort": "6.0.1", + "express": "4.17.1", + "form-data": "3.0.0", + "glob": "7.1.6", + "jest": "26.6.3", + "jest-cli": "26.6.3", + "node-fetch": "2.6.1", + "prettier": "2.2.1", + "puppeteer": "5.4.1", + "rollup": "2.34.0", + "rollup-plugin-terser": "7.0.2", + "rollup-plugin-typescript2": "0.29.0", + "typescript": "4.1.2" + }, + "directories": { + "test": "test" + } } From 22687b36ab13068c8301bc56fc7f7dc3ad6a2366 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Mon, 30 Nov 2020 16:11:03 +0700 Subject: [PATCH 3/8] Fixed bug --- package.json | 2 +- src/templates/core/httpClient/request.hbs | 2 + src/templates/core/httpClient/sendRequest.hbs | 2 - src/utils/writeClient.ts | 4 +- src/utils/writeClientCore.ts | 4 +- src/utils/writeClientServices.ts | 12 +- test/spec/creditContract.yaml | 591 ------------------ 7 files changed, 9 insertions(+), 608 deletions(-) delete mode 100644 test/spec/creditContract.yaml diff --git a/package.json b/package.json index 5da16917c..87b5a6aaa 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sundved/openapi-typescript-codegen", - "version": "0.0.1", + "version": "0.0.2", "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", "author": "Sundved", "homepage": "https://github.com/Sundved/openapi-typescript-codegen", diff --git a/src/templates/core/httpClient/request.hbs b/src/templates/core/httpClient/request.hbs index 92232017f..e6fc5e2fc 100644 --- a/src/templates/core/httpClient/request.hbs +++ b/src/templates/core/httpClient/request.hbs @@ -1,4 +1,6 @@ {{>header}} + +import { DELETE, GET, POST, PUT } from '{{{httpClientLibrary}}}'; import type { ApiRequestOptions } from './ApiRequestOptions'; import { OpenAPI } from './OpenAPI'; diff --git a/src/templates/core/httpClient/sendRequest.hbs b/src/templates/core/httpClient/sendRequest.hbs index 9195f2804..94e30e3a4 100644 --- a/src/templates/core/httpClient/sendRequest.hbs +++ b/src/templates/core/httpClient/sendRequest.hbs @@ -1,5 +1,3 @@ -import {DELETE, GET, POST, PUT} from '{{>httpClientLibrary}}'; - async function sendRequest(options: ApiRequestOptions, url: string): Promise { switch (options.method) { diff --git a/src/utils/writeClient.ts b/src/utils/writeClient.ts index 1e14aa7e7..eda177452 100644 --- a/src/utils/writeClient.ts +++ b/src/utils/writeClient.ts @@ -51,13 +51,13 @@ export async function writeClient( if (exportCore) { await rmdir(outputPathCore); await mkdir(outputPathCore); - await writeClientCore(client, templates, outputPathCore, httpClient); + await writeClientCore(client, templates, outputPathCore, httpClient, httpClientLibrary); } if (exportServices) { await rmdir(outputPathServices); await mkdir(outputPathServices); - await writeClientServices(client.services, templates, outputPathServices, httpClient, useUnionTypes, useOptions, httpClientLibrary); + await writeClientServices(client.services, templates, outputPathServices, httpClient, useUnionTypes, useOptions); } if (exportSchemas) { diff --git a/src/utils/writeClientCore.ts b/src/utils/writeClientCore.ts index 1022d6d6d..4b46bbc04 100644 --- a/src/utils/writeClientCore.ts +++ b/src/utils/writeClientCore.ts @@ -11,10 +11,12 @@ import { Templates } from './registerHandlebarTemplates'; * @param templates The loaded handlebar templates * @param outputPath Directory to write the generated files to * @param httpClient The selected httpClient (fetch, xhr or node) + * @param httpClientLibrary Library for httpClient */ -export async function writeClientCore(client: Client, templates: Templates, outputPath: string, httpClient: HttpClient): Promise { +export async function writeClientCore(client: Client, templates: Templates, outputPath: string, httpClient: HttpClient, httpClientLibrary: string): Promise { const context = { httpClient, + httpClientLibrary, server: client.server, version: client.version, }; diff --git a/src/utils/writeClientServices.ts b/src/utils/writeClientServices.ts index 8d0c7eea6..6387356d8 100644 --- a/src/utils/writeClientServices.ts +++ b/src/utils/writeClientServices.ts @@ -16,17 +16,8 @@ const VERSION_TEMPLATE_STRING = 'OpenAPI.VERSION'; * @param httpClient The selected httpClient (fetch, xhr or node) * @param useUnionTypes Use union types instead of enums * @param useOptions Use options or arguments functions - * @param httpClientLibrary Library for httpClient */ -export async function writeClientServices( - services: Service[], - templates: Templates, - outputPath: string, - httpClient: HttpClient, - useUnionTypes: boolean, - useOptions: boolean, - httpClientLibrary: string -): Promise { +export async function writeClientServices(services: Service[], templates: Templates, outputPath: string, httpClient: HttpClient, useUnionTypes: boolean, useOptions: boolean): Promise { for (const service of services) { const file = path.resolve(outputPath, `${service.name}.ts`); const useVersion = service.operations.some(operation => operation.path.includes(VERSION_TEMPLATE_STRING)); @@ -36,7 +27,6 @@ export async function writeClientServices( useUnionTypes, useVersion, useOptions, - httpClientLibrary, }); await writeFile(file, format(templateResult)); } diff --git a/test/spec/creditContract.yaml b/test/spec/creditContract.yaml deleted file mode 100644 index 94938a534..000000000 --- a/test/spec/creditContract.yaml +++ /dev/null @@ -1,591 +0,0 @@ -openapi: 3.0.1 -info: - title: Api Documentation - description: Api Documentation - termsOfService: urn:tos - contact: {} - license: - name: Apache 2.0 - url: http://www.apache.org/licenses/LICENSE-2.0 - version: "1.0" -servers: - - url: //localhost:8080/ -tags: - - name: /credit/contract - description: Кредитные договоры -paths: - /credit/contract/view: - post: - tags: - - /credit/contract - summary: Получение списка документов 'Информация о кредитных договорах' по заданным - фильтрам - operationId: getCreditContracts - requestBody: - description: Объект для параметров фильтрации документов 'Информация о кредитных - договорах' - content: - application/json: - schema: - $ref: '#/components/schemas/CreditContractViewFilter' - required: true - responses: - 200: - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/CreditContractListResponse' - 201: - description: Created - content: {} - 401: - description: Unauthorized - content: {} - 403: - description: Forbidden - content: {} - 404: - description: Not Found - content: {} - deprecated: false - x-codegen-request-body-name: filter - /credit/contract/{id}: - get: - tags: - - /credit/contract - summary: Получение документа 'Информация о кредитных договорах' по ID для страницы - деталей документа и редактирования существующего - operationId: getCreditContractById - parameters: - - name: id - in: path - description: ID документа 'Информация о кредитных договорах' - required: true - schema: - type: string - format: uuid - responses: - 200: - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/ExtendedCreditContract' - 401: - description: Unauthorized - content: {} - 403: - description: Forbidden - content: {} - 404: - description: Not Found - content: {} - deprecated: false -components: - schemas: - Amount: - title: Amount - type: object - properties: - amount: - type: number - description: Сумма - example: 100.5 - currencyCode: - type: string - description: Числовой код валюты - example: "643" - currencyDescription: - type: string - description: Описание валюты (РОССИЙСКИЙ РУБЛЬ, ДОЛЛАР США, ЕВРО) - example: РОССИЙСКИЙ РУБЛЬ - currencyName: - type: string - description: Буквенный ISO-код валюты(USD/EUR/RUB) - example: RUB - description: Сумма - Branch: - title: Branch - type: object - properties: - code: - type: string - description: Код отделения - name: - type: string - description: Наименование подразделения, в котором обслуживается клиент. - description: Подразделение банка - CreditContractListResponse: - title: CreditContractListResponse - type: object - properties: - items: - type: array - description: Коллекция элементов - items: - $ref: '#/components/schemas/CreditContractView' - pagination: - $ref: '#/components/schemas/Pagination' - description: Обертка для списка с постраничной разбивкой - CreditContractView: - title: CreditContractView - type: object - properties: - acceptSuspensiveCondition: - type: boolean - description: Признак выполнения отлагательных условий - example: true - accountNumber: - type: string - description: Основной расчетный счет по кредитному договору - availableAmount: - $ref: '#/components/schemas/Amount' - contractAmount: - $ref: '#/components/schemas/Amount' - contractName: - type: string - description: Наименование кредитного договора - example: 1948. Кредит 'Доверие'; ЮЛ/ИП. Аннуитет. - contractNumber: - type: string - description: Номер документа - example: "12345" - credProdCode: - type: string - description: Код кредитного продукта - example: "2216" - creditDate: - type: string - description: Дата начала действия договора (выдачи средств) - format: date-time - creditDurationDays: - type: integer - description: Срок действия кредита в днях - format: int32 - example: 10 - creditLineAvailableAmount: - $ref: '#/components/schemas/Amount' - creditLineFinishDate: - type: string - description: 'Кредитная линия: Дата окончания выборки' - format: date-time - creditSegment: - type: string - description: Сегмент - example: "2" - debtAmount: - $ref: '#/components/schemas/Amount' - delayPeriodDays: - type: integer - description: Количество дней просрочки по кредитному договору - format: int32 - example: 10 - docDate: - type: string - description: Дата заключения договора - format: date-time - docType: - type: string - description: Тип документа - example: CreditContract - earlyRepaymentEnable: - type: boolean - description: Признак доступного досрочного погашения - example: true - endDate: - type: string - description: Дата окончания действия договора - example: "20171011" - hasReservationPayroll: - type: boolean - description: Признак наличия у организации зарплатного договора с резервированием - example: true - interestRate: - type: number - description: Актуальная ставка по кредиту - example: 1.1 - isClosed: - type: boolean - description: Признак закрытия - example: false - isCredit7Minutes: - type: boolean - description: Признак кредитного договора на кредит за 7 минут - example: false - isReglamentAllowed: - type: boolean - description: Признак разрешенного регламента для операции электронной выдачи - example: true - limitHistory: - type: array - description: График изменения лимита - items: - $ref: '#/components/schemas/LimitHistory' - monthlyPaymentDate: - type: string - description: Дата ежемесячного платежа - example: "20171011" - moratoriumDateEnd: - type: string - description: Дата окончания моратория - format: date-time - overdarftAvailableAmount: - $ref: '#/components/schemas/Amount' - overdraftLimitIndicator: - type: string - description: 'Овердрафт: индикатор изменения доступного лимита' - enum: - - REDUCED - - NOT_CHANGED - - INCREASED - productType: - type: string - description: Вид кредитного продукта - example: Кредит - restructAvailability: - type: string - description: Признак доступной реструктуризации по договору - example: YES - enum: - - YES - - NO - - STATE_AID - scheduledPaymentAmount: - $ref: '#/components/schemas/Amount' - scheduledPaymentDate: - type: string - description: Дата платежа (следующего) - format: date-time - updateDate: - type: string - description: Дата последнего обновления данных по кредитному контракту - format: date-time - description: Информация о кредитных договорах - CreditContractViewFilter: - title: CreditContractViewFilter - type: object - properties: - acceptSuspensiveCondition: - type: boolean - description: Признак выполнения отлагательных условий - example: true - dateFrom: - type: string - description: Дата начала - format: date-time - dateTo: - type: string - description: Дата окончания - format: date-time - isClosed: - type: boolean - description: Признак закрытия - example: false - isReglamentAllowed: - type: boolean - description: Признак разрешенного регламента для операции электронной выдачи - example: false - isTargetedCredit: - type: boolean - description: Признак целевого кредитования - example: false - number: - type: string - description: Номер документа - example: "1" - orderBy: - type: string - description: Сортировка - example: 'Формат: +fieldName или -fieldName' - pagination: - $ref: '#/components/schemas/Pagination' - productTypes: - type: array - description: Список видов кредитных продуктов - example: - - кредитная линия - - овердрафт - items: - type: string - segments: - type: array - description: Список сегментов - example: {} - items: - type: string - statusCodes: - type: array - description: Список статусов - example: {} - items: - type: string - description: Фильтр для отбора документов 'Информация о кредитных договорах' - ExtendedCreditContract: - title: ExtendedCreditContract - type: object - properties: - acceptSuspensiveCondition: - type: boolean - description: Признак выполнения отлагательных условий - example: true - accountNumber: - type: string - description: Основной расчетный счет по кредитному договору - availableAmount: - $ref: '#/components/schemas/Amount' - branch: - $ref: '#/components/schemas/Branch' - contractAmount: - $ref: '#/components/schemas/Amount' - contractId: - type: string - description: Идентификатор кредитного договора в ЕКС - example: "4688069399315" - contractName: - type: string - description: Наименование кредитного договора - example: 1948. Кредит 'Доверие'; ЮЛ/ИП. Аннуитет. - contractNumber: - type: string - description: Номер кредитного договора в ЕКС - example: 031/9031/022-340 - crConType: - type: string - description: Строковое описание типа кредита - example: 931 Корпоративное кредитование - возобновляемая кр линия с дифференцированными - ставками - credProdCode: - type: string - description: Код кредитного продукта - example: "1948" - creditDate: - type: string - description: Дата начала действия договора (выдачи средств) - format: date-time - creditDurationDays: - type: integer - description: Просрочка в днях - format: int32 - creditDurationMonths: - type: integer - description: Просрочка в месяцах - format: int32 - creditLineAvailableAmount: - $ref: '#/components/schemas/Amount' - creditLineFinishDate: - type: string - description: 'Кредитная линия: Дата окончания выборки' - format: date-time - creditSegment: - type: string - description: Сегмент - example: "2" - debtAmount: - $ref: '#/components/schemas/Amount' - debtorStatus: - type: string - description: Статус клиента - example: DEBTOR - delayPeriodDays: - type: integer - description: Количество дней просрочки по кредитному договору - format: int32 - example: 7 - docDate: - type: string - description: Дата заключения договора - format: date-time - docType: - type: string - description: Тип документа - example: CreditContract - earlyRepaymentEnable: - type: boolean - description: Признак доступного досрочного погашения - example: true - endDate: - type: string - description: Дата окончания действия договора - format: date-time - hasReservationPayroll: - type: boolean - description: Признак наличия у организации зарплатного договора с резервированием - example: true - interestRate: - type: number - description: Актуальная ставка по кредиту - example: 10.58 - isClosed: - type: boolean - description: Признак закрытия - example: false - isCredit7Minutes: - type: boolean - description: Признак кредитного договора на кредит за 7 минут - example: false - isReglamentAllowed: - type: boolean - description: Признак разрешенного регламента для операции электронной выдачи - example: true - isVklds: - type: boolean - description: Признак типа кредита ВКЛДС (Возобновляемая кр линия с дифференцированными - ставками) - example: false - limitDate: - type: string - description: Дата окончания периода доступности лимитных средств - format: date-time - limitHistory: - type: array - description: График изменения лимита - items: - $ref: '#/components/schemas/LimitHistory' - maxTrancheDuration: - type: integer - description: Максимальный срок транша (число дней) - format: int32 - example: 91 - moratoriumDateEnd: - type: string - description: Дата окончания моратория - format: date-time - orgName: - type: string - description: Наименование организации получателя кредита - example: ИП17 - orgTaxNumber: - type: string - description: ИНН организации получателя кредита - example: "4601234567" - overdarftAvailableAmount: - $ref: '#/components/schemas/Amount' - overdraftLimitIndicator: - type: string - description: 'Овердрафт: индикатор изменения доступного лимита' - enum: - - REDUCED - - NOT_CHANGED - - INCREASED - productType: - type: string - description: Вид кредитного продукта - example: кредитная линия - restructAvailability: - type: string - description: Признак доступной реструктуризации по договору - example: YES - enum: - - YES - - NO - - STATE_AID - restructRequestInfo: - $ref: '#/components/schemas/RestructRequestInfo' - scheduledPaymentAmount: - $ref: '#/components/schemas/Amount' - scheduledPaymentDate: - type: string - description: Дата следующего платежа - format: date-time - settlementAccounts: - type: array - description: Расчетные счета клиента для использования в рамках кредитного - договора - items: - type: string - trancheCount: - type: integer - description: Число траншей - format: int32 - example: 10 - updateDate: - type: string - description: Дата последнего обновления данных по кредитному контракту - format: date-time - description: Основная информация о кредитном договоре - LimitHistory: - title: LimitHistory - type: object - properties: - dateBegin: - type: string - description: Дата начала лимита - format: date-time - dateEnd: - type: string - description: Дата окончания лимита - format: date-time - period: - type: integer - description: Срок (в днях) - format: int32 - example: 91 - sum: - $ref: '#/components/schemas/Amount' - description: График изменения лимита - Pagination: - title: Pagination - type: object - properties: - count: - type: integer - description: Количество возвращаемых записей - format: int32 - hasNextPage: - type: boolean - description: Признак наличия следующей страницы - offset: - type: integer - description: Смещение от начала - format: int32 - description: Нумерация - RestructRequestInfo: - title: RestructRequestInfo - type: object - properties: - analysisType: - type: string - description: Вид анализа заявки - example: EXPRESS0 - enum: - - EXPRESS0 - - CF - - EXPRESS1 - - EXPRESS2 - - MANREPORT - - QUICKDECIS - - LEASINGFACT - - LEASINGFACTEXT - - CFRISKS - - R1D - - MFO - - KREDO - - CFSMART - - CCSMART - - CBC - - FACTORING - - RESTRUCT - - CCRESTRUCT - - CPFNS - - CPCustomWar - createDate: - type: string - description: Дата создания заявки - format: date-time - statusCode: - type: string - description: Статус - example: CREATED - technology: - type: string - description: Технология выбраного кредитного продукта - example: FACTORY - enum: - - FACTORY - - CONVEYOR - - QUICK - - LEASING - - CREDIT_1H - - FACTORING - description: Данные о заявке на реструктуризацию From 028063e577ad3cce7225b3bfa003091455573f64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Dec 2020 14:21:16 +0700 Subject: [PATCH 4/8] New version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 87b5a6aaa..90455fd92 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sundved/openapi-typescript-codegen", - "version": "0.0.2", + "version": "0.0.3", "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", "author": "Sundved", "homepage": "https://github.com/Sundved/openapi-typescript-codegen", From 960779b0794dd6d46903ec981b8db541af120749 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Dec 2020 15:34:42 +0700 Subject: [PATCH 5/8] Fixed bug with template --- package.json | 2 +- src/templates/core/httpClient/getRequestBody.hbs | 13 +++++++++++++ src/templates/core/httpClient/request.hbs | 12 ++++++++++++ src/utils/registerHandlebarTemplates.ts | 2 ++ 4 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 src/templates/core/httpClient/getRequestBody.hbs diff --git a/package.json b/package.json index 90455fd92..be6b4168d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sundved/openapi-typescript-codegen", - "version": "0.0.3", + "version": "0.0.4", "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", "author": "Sundved", "homepage": "https://github.com/Sundved/openapi-typescript-codegen", diff --git a/src/templates/core/httpClient/getRequestBody.hbs b/src/templates/core/httpClient/getRequestBody.hbs new file mode 100644 index 000000000..0977770cc --- /dev/null +++ b/src/templates/core/httpClient/getRequestBody.hbs @@ -0,0 +1,13 @@ +function getRequestBody(options: ApiRequestOptions): BodyInit | undefined { + if (options.formData) { + return getFormData(options.formData); + } + if (options.body) { + if (isString(options.body) || isBinary(options.body)) { + return options.body; + } else { + return JSON.stringify(options.body); + } + } + return undefined; +} diff --git a/src/templates/core/httpClient/request.hbs b/src/templates/core/httpClient/request.hbs index e6fc5e2fc..5b2f1bad3 100644 --- a/src/templates/core/httpClient/request.hbs +++ b/src/templates/core/httpClient/request.hbs @@ -7,12 +7,24 @@ import { OpenAPI } from './OpenAPI'; {{>functions/isDefined}} +{{>functions/isBinary}} + + +{{>functions/isString}} + + +{{>functions/getFormData}} + + {{>functions/getQueryString}} {{>functions/getUrl}} +{{>httpClient/getRequestBody}} + + {{>httpClient/sendRequest}} diff --git a/src/utils/registerHandlebarTemplates.ts b/src/utils/registerHandlebarTemplates.ts index 3a1c2be31..70fc2b7f1 100644 --- a/src/utils/registerHandlebarTemplates.ts +++ b/src/utils/registerHandlebarTemplates.ts @@ -20,6 +20,7 @@ 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 httpClientGetRequestBody from '../templates/core/httpClient/getRequestBody.hbs'; import httpClientRequest from '../templates/core/httpClient/request.hbs'; import httpClientSendRequest from '../templates/core/httpClient/sendRequest.hbs'; import nodeGetHeaders from '../templates/core/node/getHeaders.hbs'; @@ -168,6 +169,7 @@ export function registerHandlebarTemplates(): Templates { Handlebars.registerPartial('xhr/request', Handlebars.template(xhrRequest)); // Specific files for the httpClient client implementation + Handlebars.registerPartial('httpClient/getRequestBody', Handlebars.template(httpClientGetRequestBody)); Handlebars.registerPartial('httpClient/sendRequest', Handlebars.template(httpClientSendRequest)); Handlebars.registerPartial('httpClient/request', Handlebars.template(httpClientRequest)); From 0dbb8a786c5f043ef6e27341dbd15d5c1757c37d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Dec 2020 15:40:40 +0700 Subject: [PATCH 6/8] Fixed bug with template --- package.json | 2 +- src/templates/core/httpClient/getRequestBody.hbs | 2 +- src/templates/core/httpClient/request.hbs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index be6b4168d..5318d17c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sundved/openapi-typescript-codegen", - "version": "0.0.4", + "version": "0.0.5", "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", "author": "Sundved", "homepage": "https://github.com/Sundved/openapi-typescript-codegen", diff --git a/src/templates/core/httpClient/getRequestBody.hbs b/src/templates/core/httpClient/getRequestBody.hbs index 0977770cc..09df2d0be 100644 --- a/src/templates/core/httpClient/getRequestBody.hbs +++ b/src/templates/core/httpClient/getRequestBody.hbs @@ -3,7 +3,7 @@ function getRequestBody(options: ApiRequestOptions): BodyInit | undefined { return getFormData(options.formData); } if (options.body) { - if (isString(options.body) || isBinary(options.body)) { + if (isString(options.body) || isBlob(options.body)) { return options.body; } else { return JSON.stringify(options.body); diff --git a/src/templates/core/httpClient/request.hbs b/src/templates/core/httpClient/request.hbs index 5b2f1bad3..c3ef82bd2 100644 --- a/src/templates/core/httpClient/request.hbs +++ b/src/templates/core/httpClient/request.hbs @@ -7,7 +7,7 @@ import { OpenAPI } from './OpenAPI'; {{>functions/isDefined}} -{{>functions/isBinary}} +{{>functions/isBlob}} {{>functions/isString}} From b26557958f93b4a000734f89b5b029ee82d75e82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Dec 2020 16:57:48 +0700 Subject: [PATCH 7/8] fix of ts bug --- package.json | 2 +- src/templates/core/ApiRequestOptions.hbs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 5318d17c1..78aabb2e8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sundved/openapi-typescript-codegen", - "version": "0.0.5", + "version": "0.0.6", "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", "author": "Sundved", "homepage": "https://github.com/Sundved/openapi-typescript-codegen", diff --git a/src/templates/core/ApiRequestOptions.hbs b/src/templates/core/ApiRequestOptions.hbs index dc33aac89..fe2f6863f 100644 --- a/src/templates/core/ApiRequestOptions.hbs +++ b/src/templates/core/ApiRequestOptions.hbs @@ -9,5 +9,5 @@ export type ApiRequestOptions = { readonly formData?: Record; readonly body?: any; readonly responseHeader?: string; - readonly errors?: Record; + readonly errors?: Record; } From 204c9aaa05038c458600446fb55d0d70647739cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D0=BF=D0=B0=D1=81=D0=BD=D0=BE=D0=B9=20=D0=90?= =?UTF-8?q?=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20=D0=A1=D0=B5?= =?UTF-8?q?=D1=80=D0=B3=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Dec 2020 18:56:04 +0700 Subject: [PATCH 8/8] Fix of parse response body --- package.json | 2 +- src/templates/core/httpClient/sendRequest.hbs | 16 +++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 78aabb2e8..1db19092e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@sundved/openapi-typescript-codegen", - "version": "0.0.6", + "version": "0.0.7", "description": "Fork of library that generates Typescript clients based on the OpenAPI specification.", "author": "Sundved", "homepage": "https://github.com/Sundved/openapi-typescript-codegen", diff --git a/src/templates/core/httpClient/sendRequest.hbs b/src/templates/core/httpClient/sendRequest.hbs index 94e30e3a4..9311346c0 100644 --- a/src/templates/core/httpClient/sendRequest.hbs +++ b/src/templates/core/httpClient/sendRequest.hbs @@ -1,13 +1,19 @@ async function sendRequest(options: ApiRequestOptions, url: string): Promise { - + let body; switch (options.method) { case 'GET': - return GET(url); + body = await GET(url); + break; case 'POST': - return POST(url, getRequestBody(options)); + body = await POST(url, getRequestBody(options)); + break; case 'PUT': - return PUT(url, getRequestBody(options)); + body = await PUT(url, getRequestBody(options)); + break; case 'DELETE': - return DELETE(url, getRequestBody(options)); + body = await DELETE(url, getRequestBody(options)); + break; } + + return {body}; }