diff --git a/.github/workflows/bump.yml b/.github/workflows/bump.yml new file mode 100644 index 0000000..68daa7c --- /dev/null +++ b/.github/workflows/bump.yml @@ -0,0 +1,34 @@ +# This action is centrally managed in https://github.com/asyncapi/.github/ +# Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo + +# Purpose of this action is to update npm package in libraries that use it. It is like dependabot for asyncapi npm modules only. +# It runs in a repo after merge of release commit and searches for other packages that use released package. Every found package gets updated with lates version + +name: Bump package version in dependent repos - if Node project + +on: + # It cannot run on release event as when release is created then version is not yet bumped in package.json + # This means we cannot extract easily latest version and have a risk that package is not yet on npm + push: + branches: + - master + +jobs: + bump-in-dependent-projects: + name: Bump this package in repositories that depend on it + if: startsWith(github.event.commits[0].message, 'chore(release):') + runs-on: ubuntu-latest + steps: + - name: Checkout repo + uses: actions/checkout@v2 + - name: Check if Node.js project and has package.json + id: packagejson + run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false" + - if: steps.packagejson.outputs.exists == 'true' + name: Bumping latest version of this package in other repositories + uses: derberg/npm-dependency-manager-for-your-github-org@v4 + with: + github_token: ${{ secrets.GH_TOKEN }} + committer_username: asyncapi-bot + committer_email: info@asyncapi.io + repos_to_ignore: html-template # this is temporary until react component releases 1.0, then it can be removed diff --git a/.github/workflows/if-nodejs-pr-testing.yml b/.github/workflows/if-nodejs-pr-testing.yml new file mode 100644 index 0000000..1dcccd3 --- /dev/null +++ b/.github/workflows/if-nodejs-pr-testing.yml @@ -0,0 +1,61 @@ +# This action is centrally managed in https://github.com/asyncapi/.github/ +# Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo + +# It does magic only if there is package.json file in the root of the project +name: PR testing - if Node project + +on: + pull_request: + types: [opened, reopened, synchronize, ready_for_review] + +jobs: + test-nodejs-pr: + name: Test NodeJS PR - ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - if: "github.event.pull_request.draft == false &&!((github.actor == 'asyncapi-bot' && startsWith(github.event.pull_request.title, 'ci: update global workflows')) || (github.actor == 'asyncapi-bot' && startsWith(github.event.pull_request.title, 'chore(release):')) || (github.actor == 'allcontributors' && startsWith(github.event.pull_request.title, 'docs: add')))" + id: should_run + name: Should Run + run: echo "::set-output name=shouldrun::true" + - if: steps.should_run.outputs.shouldrun == 'true' + name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows + run: | + git config --global core.autocrlf false + git config --global core.eol lf + - if: steps.should_run.outputs.shouldrun == 'true' + name: Checkout repository + uses: actions/checkout@v2 + - if: steps.should_run.outputs.shouldrun == 'true' + name: Check if Node.js project and has package.json + id: packagejson + run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false" + shell: bash + - if: steps.packagejson.outputs.exists == 'true' + name: Setup Node.js + uses: actions/setup-node@v2 + with: + node-version: 14 + cache: 'npm' + cache-dependency-path: '**/package-lock.json' + - if: steps.packagejson.outputs.exists == 'true' + name: Install dependencies + id: first-installation + run: npm install --loglevel verbose + continue-on-error: true + - if: steps.first-installation.outputs.status == 'failure' && steps.packagejson.outputs.exists == 'true' + name: Clear NPM cache and install deps again + run: | + npm cache clean --force + npm install --loglevel verbose + - if: steps.packagejson.outputs.exists == 'true' + name: Test + run: npm test + - if: steps.packagejson.outputs.exists == 'true' + name: Run linter + run: npm run lint + - if: steps.packagejson.outputs.exists == 'true' + name: Run release assets generation to make sure PR does not break it + run: npm run generate:assets diff --git a/.github/workflows/if-nodejs-release.yml b/.github/workflows/if-nodejs-release.yml new file mode 100644 index 0000000..16cc885 --- /dev/null +++ b/.github/workflows/if-nodejs-release.yml @@ -0,0 +1,104 @@ +# This action is centrally managed in https://github.com/asyncapi/.github/ +# Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo + +# It does magic only if there is package.json file in the root of the project +name: Release - if Node project + +on: + push: + branches: + - master + # below lines are not enough to have release supported for these branches + # make sure configuration of `semantic-release` package mentiones these branches + - next + - next-major + - beta + - alpha + - '**-release' # custom + +jobs: + + test-nodejs: + name: Test NodeJS release on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows + run: | + git config --global core.autocrlf false + git config --global core.eol lf + - name: Checkout repository + uses: actions/checkout@v2 + - name: Check if Node.js project and has package.json + id: packagejson + run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false" + shell: bash + - if: steps.packagejson.outputs.exists == 'true' + name: Setup Node.js + uses: actions/setup-node@v2 + with: + node-version: 14 + cache: 'npm' + cache-dependency-path: '**/package-lock.json' + - if: steps.packagejson.outputs.exists == 'true' + name: Install dependencies + run: npm install + - if: steps.packagejson.outputs.exists == 'true' + name: Run test + run: npm test + - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel + name: Report workflow run status to Slack + uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,action,workflow + text: 'Release workflow failed in testing job' + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} + + release: + needs: [test-nodejs] + name: Publish to any of NPM, Github, and Docker Hub + runs-on: ubuntu-latest + steps: + - name: Set git to use LF #to once and for all finish neverending fight between Unix and Windows + run: | + git config --global core.autocrlf false + git config --global core.eol lf + - name: Checkout repository + uses: actions/checkout@v2 + - name: Check if Node.js project and has package.json + id: packagejson + run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false" + - if: steps.packagejson.outputs.exists == 'true' + name: Setup Node.js + uses: actions/setup-node@v1 + with: + node-version: 14 + - if: steps.packagejson.outputs.exists == 'true' + name: Install dependencies + run: npm install + - if: steps.packagejson.outputs.exists == 'true' + name: Publish to any of NPM, Github, and Docker Hub + id: release + env: + GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }} + DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} + GIT_AUTHOR_NAME: asyncapi-bot + GIT_AUTHOR_EMAIL: info@asyncapi.io + GIT_COMMITTER_NAME: asyncapi-bot + GIT_COMMITTER_EMAIL: info@asyncapi.io + run: npm run release + - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel + name: Report workflow run status to Slack + uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,action,workflow + text: 'Release workflow failed in release job' + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} \ No newline at end of file diff --git a/.github/workflows/if-nodejs-version-bump.yml b/.github/workflows/if-nodejs-version-bump.yml new file mode 100644 index 0000000..5e7aa14 --- /dev/null +++ b/.github/workflows/if-nodejs-version-bump.yml @@ -0,0 +1,65 @@ +# This action is centrally managed in https://github.com/asyncapi/.github/ +# Don't make changes to this file in this repo as they will be overwritten with changes made to the same file in above mentioned repo + +# It does magic only if there is package.json file in the root of the project +name: Version bump - if Node.js project + +on: + release: + types: + - published + +jobs: + version_bump: + name: Generate assets and bump NodeJS + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v2 + with: + # target branch of release. More info https://docs.github.com/en/rest/reference/repos#releases + # in case release is created from release branch then we need to checkout from given branch + # if @semantic-release/github is used to publish, the minimum version is 7.2.0 for proper working + ref: ${{ github.event.release.target_commitish }} + - name: Check if Node.js project and has package.json + id: packagejson + run: test -e ./package.json && echo "::set-output name=exists::true" || echo "::set-output name=exists::false" + - if: steps.packagejson.outputs.exists == 'true' + name: Setup Node.js + uses: actions/setup-node@v2 + with: + node-version: 14 + cache: 'npm' + cache-dependency-path: '**/package-lock.json' + - if: steps.packagejson.outputs.exists == 'true' + name: Install dependencies + run: npm install + - if: steps.packagejson.outputs.exists == 'true' + name: Assets generation + run: npm run generate:assets + - if: steps.packagejson.outputs.exists == 'true' + name: Bump version in package.json + # There is no need to substract "v" from the tag as version script handles it + # When adding "bump:version" script in package.json, make sure no tags are added by default (--no-git-tag-version) as they are already added by release workflow + # When adding "bump:version" script in package.json, make sure --allow-same-version is set in case someone forgot and updated package.json manually and we want to avoide this action to fail and raise confusion + run: VERSION=${{github.event.release.tag_name}} npm run bump:version + - if: steps.packagejson.outputs.exists == 'true' + name: Create Pull Request with updated asset files including package.json + uses: peter-evans/create-pull-request@v3 + with: + token: ${{ secrets.GH_TOKEN }} + commit-message: 'chore(release): ${{github.event.release.tag_name}}' + committer: asyncapi-bot + author: asyncapi-bot + title: 'chore(release): ${{github.event.release.tag_name}}' + body: 'Version bump in package.json for release [${{github.event.release.tag_name}}](${{github.event.release.html_url}})' + branch: version-bump/${{github.event.release.tag_name}} + - if: failure() # Only, on failure, send a message on the 94_bot-failing-ci slack channel + name: Report workflow run status to Slack + uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,action,workflow + text: 'Unable to bump the version in package.json after the release' + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_CI_FAIL_NOTIFY }} \ No newline at end of file diff --git a/components/Consumers.js b/components/Consumers.js index 64eb115..8c88383 100644 --- a/components/Consumers.js +++ b/components/Consumers.js @@ -1,7 +1,7 @@ import { toPascalCase } from '../utils/common'; export function Consumers({ channels }) { - if (channels?.length == 0) { + if (channels.length === 0) { return null; } diff --git a/components/Publishers.js b/components/Publishers.js index 4f4d359..26862ad 100644 --- a/components/Publishers.js +++ b/components/Publishers.js @@ -1,7 +1,7 @@ import { toPascalCase } from '../utils/common'; export function Publishers({ channels }) { - if (channels?.length == 0) { + if (channels.length === 0) { return null; } diff --git a/components/Worker.js b/components/Worker.js index 37416b8..3bef4db 100644 --- a/components/Worker.js +++ b/components/Worker.js @@ -11,8 +11,8 @@ namespace ${params.namespace} { /// /// Generated worker for ${asyncapi.info().title()}, ${asyncapi - .info() - .version()} + .info() + .version()} /// public class Worker : BackgroundService { diff --git a/components/templates/amqpservice.interface.js b/components/templates/amqpservice.interface.js index a4ab6f1..bc3d1fd 100644 --- a/components/templates/amqpservice.interface.js +++ b/components/templates/amqpservice.interface.js @@ -8,23 +8,23 @@ namespace ${params.namespace}.Services.Interfaces; public interface IAmqpService : IDisposable { ${publishers - .map( - (publisher) => ` + .map( + (publisher) => ` /// /// Operations from async api specification /// /// The message to be handled by this amqp operation void ${toPascalCase(publisher.operationId)}(${ - publisher.messageType - } message); + publisher.messageType +} message); ` - ) - .join('')} + ) + .join('')} ${consumers - .map( - (consumer) => ` + .map( + (consumer) => ` /// /// Operations from async api specification /// @@ -32,8 +32,8 @@ public interface IAmqpService : IDisposable void ${toPascalCase(consumer.operationId)}(); ` - ) - .join('')} + ) + .join('')} }`; export function IAmqpService({ asyncapi, params }) { diff --git a/components/templates/amqpservice.js b/components/templates/amqpservice.js index 514d214..907d69e 100644 --- a/components/templates/amqpservice.js +++ b/components/templates/amqpservice.js @@ -31,8 +31,8 @@ namespace ${params.namespace}.Services; /// /// Generated consumer for ${asyncapi.info().title()}, ${asyncapi - .info() - .version()} + .info() + .version()} /// public class AmqpService : IAmqpService { @@ -60,21 +60,21 @@ public class AmqpService : IAmqpService } ${publishers - .map( - (publisher) => `/// + .map( + (publisher) => `/// /// Operations from async api specification /// /// The message to be handled by this amqp operation public void ${toPascalCase(publisher.operationId)}(${ - publisher.messageType - } message) + publisher.messageType +} message) { var exchange = "${publisher.exchange}"; var routingKey = "${publisher.routingKey}"; var channel = _channelPool.GetChannel("${toPascalCase( - publisher.operationId - )}"); + publisher.operationId + )}"); var exchangeProps = new Dictionary { {"CC", "${publisher.cc}"}, @@ -99,8 +99,8 @@ public class AmqpService : IAmqpService props.Expiration = "${publisher.expiration}"; _logger.Verbose("Sending message {@${ - publisher.messageType - }} with correlation id {CorrelationId}", + publisher.messageType +}} with correlation id {CorrelationId}", message, props.CorrelationId); @@ -114,17 +114,17 @@ public class AmqpService : IAmqpService } ` - ) - .join('')} + ) + .join('')} ${consumers - .map( - (consumer) => `public void ${toPascalCase(consumer.operationId)}() + .map( + (consumer) => `public void ${toPascalCase(consumer.operationId)}() { var queue = "${consumer.queue}"; // queue from specification var channel = _channelPool.GetChannel("${toPascalCase( - consumer.operationId - )}"); + consumer.operationId + )}"); // TODO: declare passive? channel.QueueDeclare(queue); @@ -138,11 +138,11 @@ public class AmqpService : IAmqpService { var body = ea.Body.ToArray(); var message = JsonSerializer.Deserialize<${ - consumer.messageType - }>(Encoding.UTF8.GetString(body)); + consumer.messageType +}>(Encoding.UTF8.GetString(body)); _logger.Verbose("${toPascalCase( - consumer.messageType - )} received, {@${toPascalCase(consumer.messageType)}}", message); + consumer.messageType + )} received, {@${toPascalCase(consumer.messageType)}}", message); try { @@ -153,8 +153,8 @@ public class AmqpService : IAmqpService catch (Exception e) { _logger.Error(e, "Something went wrong trying to process message {@${toPascalCase( - consumer.messageType - )}},", message); + consumer.messageType + )}},", message); channel.BasicReject(ea.DeliveryTag, false); } }; @@ -164,8 +164,8 @@ public class AmqpService : IAmqpService consumer: consumer); } ` - ) - .join('')} + ) + .join('')} public void Dispose() { diff --git a/components/templates/channelpool.js b/components/templates/channelpool.js index 7ccaa73..5a63b9f 100644 --- a/components/templates/channelpool.js +++ b/components/templates/channelpool.js @@ -53,20 +53,20 @@ public class ChannelPool : IChannelPool // creating producer channels ${publishers.map( - (publisher) => `_channels.Add( + (publisher) => `_channels.Add( "${toPascalCase(publisher.operationId)}", CreateChannel(connection));` - )} + )} // creating consumer channels ${consumers.map( - (consumer) => `_channels.Add( + (consumer) => `_channels.Add( "${toPascalCase(consumer.operationId)}", CreateChannel( connection, ${consumer.prefetchCount}, ${consumer.confirm}));` - )} + )} } diff --git a/package.json b/package.json index 9f5576b..ced8438 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,9 @@ "release": "semantic-release", "get-version": "echo $npm_package_version", "gen-readme-toc": "markdown-toc -i README.md", - "lint": "eslint --max-warnings 0 --fix --config .eslintrc ." + "lint": "eslint --max-warnings 0 --fix --config .eslintrc .", + "generate:assets": "", + "generate:examples": "" }, "keywords": [ "asyncapi", diff --git a/template/src/Services/Interfaces/iamqpservice.js b/template/src/Services/Interfaces/iamqpservice.js index ffaee61..8eb166f 100644 --- a/template/src/Services/Interfaces/iamqpservice.js +++ b/template/src/Services/Interfaces/iamqpservice.js @@ -2,10 +2,6 @@ import { File, render } from '@asyncapi/generator-react-sdk'; import { IAmqpService } from '../../../../components/templates/amqpservice.interface'; export default function ({ asyncapi, params }) { - // if (!asyncapi.hasComponents()) { - // return null; - // } - return ( {render()} diff --git a/template/src/Services/Interfaces/ichannelpool.js b/template/src/Services/Interfaces/ichannelpool.js index 2379f6c..c71f2b2 100644 --- a/template/src/Services/Interfaces/ichannelpool.js +++ b/template/src/Services/Interfaces/ichannelpool.js @@ -2,10 +2,6 @@ import { File, render } from '@asyncapi/generator-react-sdk'; import { IChannelPool } from '../../../../components/templates/channelpool.interface'; export default function ({ asyncapi, params }) { - // if (!asyncapi.hasComponents()) { - // return null; - // } - return ( {render()} diff --git a/template/src/Services/amqpservice.js b/template/src/Services/amqpservice.js index fd1df61..a0aad0f 100644 --- a/template/src/Services/amqpservice.js +++ b/template/src/Services/amqpservice.js @@ -2,10 +2,6 @@ import { File, render } from '@asyncapi/generator-react-sdk'; import { AmqpService } from '../../../components/templates/amqpservice'; export default function ({ asyncapi, params }) { - // if (!asyncapi.hasComponents()) { - // return null; - // } - return ( {render()} diff --git a/template/src/Services/channelpool.js b/template/src/Services/channelpool.js index 1da9fad..df5faa2 100644 --- a/template/src/Services/channelpool.js +++ b/template/src/Services/channelpool.js @@ -2,10 +2,6 @@ import { File, render } from '@asyncapi/generator-react-sdk'; import { ChannelPool } from '../../../components/templates/channelpool'; export default function ({ asyncapi, params }) { - // if (!asyncapi.hasComponents()) { - // return null; - // } - return ( {render()} diff --git a/template/src/appconfig.js b/template/src/appconfig.js index e4bb2d7..3b178e1 100644 --- a/template/src/appconfig.js +++ b/template/src/appconfig.js @@ -18,7 +18,7 @@ export default function({ asyncapi, params }) { const server = Object.entries(asyncapi.servers()) .map(([serverName, server]) => { - if(serverName === params.server){ + if (serverName === params.server) { return server.url(); } }) @@ -27,8 +27,8 @@ export default function({ asyncapi, params }) { // Notice that root component is the `File` component. return ( - { - `{ + { + `{ "Serilog": { "MinimumLevel": { "Default": "Verbose", @@ -69,7 +69,7 @@ export default function({ asyncapi, params }) { "Host": "${server}" } }` - } + } ); } diff --git a/template/src/docker.js b/template/src/docker.js index e752d8b..90efb28 100644 --- a/template/src/docker.js +++ b/template/src/docker.js @@ -7,7 +7,7 @@ export default function({ asyncapi, params }) { return ( - {`FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base + {`FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /app @@ -31,7 +31,7 @@ WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "${params.namespace}.dll"]` -} - -); + } + + ); } diff --git a/template/src/program.js b/template/src/program.js index e48b742..1bfa1b2 100644 --- a/template/src/program.js +++ b/template/src/program.js @@ -7,7 +7,7 @@ export default function({ asyncapi, params }) { return ( - {`using Masking.Serilog; + {`using Masking.Serilog; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -37,7 +37,7 @@ namespace ${params.namespace} }); } }` -} - -); + } + + ); } diff --git a/template/src/project.js b/template/src/project.js index a4733eb..566395a 100644 --- a/template/src/project.js +++ b/template/src/project.js @@ -7,7 +7,7 @@ export default function({ asyncapi, params }) { return ( - {` + {` net6.0 @@ -23,7 +23,7 @@ export default function({ asyncapi, params }) { ` -} - -); + } + + ); } \ No newline at end of file diff --git a/template/src/startup.js b/template/src/startup.js index 697a5f6..1ff849a 100644 --- a/template/src/startup.js +++ b/template/src/startup.js @@ -7,7 +7,7 @@ export default function({ asyncapi, params }) { return ( - {`using Microsoft.AspNetCore.Builder; + {`using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -39,7 +39,7 @@ namespace ${params.namespace} } } }` -} - -); + } + + ); } diff --git a/test/common.test.spec.js b/test/common.test.spec.js deleted file mode 100644 index 0018ef3..0000000 --- a/test/common.test.spec.js +++ /dev/null @@ -1,29 +0,0 @@ -import AsyncAPIDocument from '@asyncapi/parser/lib/models/asyncapi'; -import { addBasicProperty } from '../utils/common'; - -describe('Common utilities tests', () => { - it('should return valid basic property on not null binding input', () => { - const asyncapi = new AsyncAPIDocument({ - asyncapi: '2.2.0', - defaultContentType: 'application/json', - channels: { - temperature: { - subscribe: { - bindings: { - amqp: { - expiration: 0, - cc: [], - priority: 0, - deliveryMode: 0, - bcc: [], - ack: true, - }, - }, - }, - }, - }, - }); - - expect(addBasicProperty()).toEqual('test'); - }); -}); diff --git a/test/consumers.test.spec.js b/test/consumers.test.spec.js index 69c8ee2..8667865 100644 --- a/test/consumers.test.spec.js +++ b/test/consumers.test.spec.js @@ -1,7 +1,7 @@ import { render } from '@asyncapi/generator-react-sdk'; import AsyncAPIDocument from '@asyncapi/parser/lib/models/asyncapi'; import { Consumers } from '../components/Consumers'; -import { cleanString } from '../utils/common'; +import { cleanString, getChannels } from '../utils/common'; describe('Consumers component', () => { it('should render consumer implementation', () => { @@ -48,24 +48,13 @@ describe('Consumers component', () => { }, }); - const expected = `// Handler for 'Subscribe to a temperature change from a specific sensor.' - _channel.QueueDeclare(\"temperatures\"); - _channel.QueueBind(queue: \"temperatures\", - exchange: \"temperature\", - routingKey: \"{sensorId}.temperature\"); - var onSpecificSensorTemperatureReceived = new EventingBasicConsumer(_channel); - onSpecificSensorTemperatureReceived.Received += (model, ea) => + const expected = `protected override Task ExecuteAsync(CancellationToken stoppingToken) { - var body = ea.Body.ToArray(); - var message = JsonSerializer.Deserialize(Encoding.UTF8.GetString(body)); - _logger.Verbose(\"Temperature received, {@Temperature}\", message); - // TODO - handle message - }; - _channel.BasicConsume(queue: \"temperatures\", - autoAck: true, - consumer: onSpecificSensorTemperatureReceived);`; + _amqpService.OnSpecificSensorTemperatureReceived(); + return Task.CompletedTask; + }`; - const result = render(); + const result = render(); expect(cleanString(result)).toEqual(cleanString(expected)); }); diff --git a/test/producers.test.spec.js b/test/producers.test.spec.js index f29b587..286655a 100644 --- a/test/producers.test.spec.js +++ b/test/producers.test.spec.js @@ -1,5 +1,5 @@ describe('Producer component tests', () => { it('should render producer implementation', () => { - expect(true).toEqual(true); + expect(true).toEqual(true); // TODO: test implementation }); }); diff --git a/utils/common.js b/utils/common.js index 2aa37f5..f40e313 100644 --- a/utils/common.js +++ b/utils/common.js @@ -112,22 +112,22 @@ export function getMessageType(message) { */ export function toCType(jsonSchemaType, property) { switch (jsonSchemaType.toLowerCase()) { - case 'string': - return 'String'; - case 'integer': - return 'int'; - case 'number': - return 'decimal'; - case 'boolean': - return 'bool'; - case 'object': - if (property) { - return `${property.uid()}Schema`; - } - return 'object'; + case 'string': + return 'String'; + case 'integer': + return 'int'; + case 'number': + return 'decimal'; + case 'boolean': + return 'bool'; + case 'object': + if (property) { + return `${property.uid()}Schema`; + } + return 'object'; - default: - return 'object'; + default: + return 'object'; } } @@ -139,16 +139,16 @@ export function toCType(jsonSchemaType, property) { */ export function castToCType(jsonSchemaType, variableToCast) { switch (jsonSchemaType.toLowerCase()) { - case 'string': - return `$"{${variableToCast}}"`; - case 'integer': - return `int.Parse(${variableToCast})`; - case 'number': - return `decimal.Parse(${variableToCast}, System.Globalization.CultureInfo.InvariantCulture)`; - case 'boolean': - return `bool.Parse(${variableToCast})`; - default: - throw new Error(`Parameter type not supported - ${jsonSchemaType}`); + case 'string': + return `$"{${variableToCast}}"`; + case 'integer': + return `int.Parse(${variableToCast})`; + case 'number': + return `decimal.Parse(${variableToCast}, System.Globalization.CultureInfo.InvariantCulture)`; + case 'boolean': + return `bool.Parse(${variableToCast})`; + default: + throw new Error(`Parameter type not supported - ${jsonSchemaType}`); } } @@ -194,7 +194,7 @@ export function parseParameters(parameters) { } export function cleanString(str) { - return str.replace(/ |\r\n|\n|\r/gm, '').trim(); + return str.replace(/ {2}|\r\n|\n|\r/gm, '').trim(); } export function getChannels(asyncapi) { @@ -205,10 +205,9 @@ export function getChannels(asyncapi) { const operation = channel.publish(); const channelBinding = channel.binding('amqp'); const operationBinding = operation.binding('amqp'); - const parameters = realizeParametersForChannel(channel.parameters()); // this should generate a consumer - const channelData = { + return { isPublish: true, routingKey: channelName, operationId: operation.id(), @@ -229,17 +228,14 @@ export function getChannels(asyncapi) { alternateExchange: channelBinding.exchange['x-alternate-exchange'], messageType: toPascalCase(operation._json.message.name), // TODO: handle multiple messages on a operation }; - - return channelData; } if (channel.hasSubscribe() && channel.hasBinding('amqp')) { const operation = channel.subscribe(); const channelBinding = channel.binding('amqp'); - const parameters = realizeParametersForChannel(channel.parameters()); // this should generate a publisher - const channelData = { + return { isPublish: false, routingKey: channelName, operationId: operation.id(), @@ -251,8 +247,6 @@ export function getChannels(asyncapi) { exchangeType: channelBinding.exchange.type, messageType: toPascalCase(operation._json.message.name), // TODO: handle multiple messages on a operation }; - - return channelData; } }) .filter((publisher) => publisher); @@ -265,7 +259,6 @@ export function getPublishers(asyncapi) { if (channel.hasPublish() && channel.hasBinding('amqp')) { const operation = channel.publish(); const binding = channel.binding('amqp'); - const parameters = realizeParametersForChannel(channel.parameters()); const publisher = { routingKey: channelName,