Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: switch to new parser API #349

Merged
merged 16 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ rules:
func-style: 0
max-nested-callbacks: 0
camelcase: 0

react/no-array-index-key: 0

# Warnings
no-debugger: 1
no-empty: 1
Expand Down
2 changes: 1 addition & 1 deletion .sonarcloud.properties
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Disable specific file since it would introduce more complexity to reduce it - mainly code complexity and complex template literals
sonar.exclusions=components/Schema.js,helpers/schema.js
sonar.exclusions=components/Schema.js,helpers/schema.js,components/Operations.js,components/Security.js
# Disable duplicate code in tests since it would introduce more complexity to reduce it.
sonar.cpd.exclusions=test/**
19 changes: 9 additions & 10 deletions components/Bindings.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,18 @@ import { FormatHelpers } from '../helpers/format';

export function Bindings({ name = 'Binding specific information', item }) {
const bindings = item.bindings();
if (!bindings || !Object.keys(bindings).length) {
if (bindings.isEmpty()) {
return null;
}

const renderBindings = Object.entries(bindings).map(
([bindingName, binding]) => {
const schema = SchemaHelpers.jsonToSchema(binding);
const schemaName = `${FormatHelpers.inlineCode(bindingName)} ${name}`;
return (
<Schema schemaName={schemaName} schema={schema} key={bindingName} />
);
},
);
const renderBindings = bindings.all().map(binding => {
const protocol = binding.protocol();
const schema = SchemaHelpers.jsonToSchema(binding);
const schemaName = `${FormatHelpers.inlineCode(protocol)} ${name}`;
return (
<Schema schemaName={schemaName} schema={schema} key={protocol} />
);
});

return (
<>
Expand Down
4 changes: 2 additions & 2 deletions components/Extensions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { Schema } from './Schema';
import { SchemaHelpers } from '../helpers/schema';

export const Extensions = ({ name = 'Extensions', item }) => {
const extensions = SchemaHelpers.getCustomExtensions(item);
if (!extensions || !Object.keys(extensions).length) {
const extensions = SchemaHelpers.getCustomExtensions(item) || {};
if (Object.keys(extensions || {}).length === 0) {
return null;
}

Expand Down
5 changes: 3 additions & 2 deletions components/FrontMatter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import * as fs from 'fs';
import * as yaml from 'yaml';

export function FrontMatter({ asyncapi, params }) {
const info = asyncapi.info();
const frontMatter = yaml.parse(fs.readFileSync(params.frontMatter, 'utf8'));
let frontMatterStr = yaml.stringify(frontMatter);
frontMatterStr = frontMatterStr.split('{{title}}').join(asyncapi.info().title());
frontMatterStr = frontMatterStr.split('{{version}}').join(params.version || asyncapi.info().version());
frontMatterStr = frontMatterStr.split('{{title}}').join(info.title());
frontMatterStr = frontMatterStr.split('{{version}}').join(params.version || info.version());
return <Text newLines={2}>{`---\n${frontMatterStr}---`}</Text>;
}
19 changes: 9 additions & 10 deletions components/Info.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import { Header, Link, Image, List, NewLine } from './common';
export function Info({ asyncapi, params = {} }) {
const info = asyncapi.info();

const specId = asyncapi.id();
const externalDocs = asyncapi.externalDocs();
const license = info.license();
const termsOfService = info.termsOfService();
const defaultContentType = asyncapi.defaultContentType();
const specId = info.id();
const termsOfService = info.termsOfService();
const license = info.license();
const contact = info.contact();
const externalDocs = info.externalDocs();
const extensions = info.extensions();

const infoList = [];
if (specId) {
Expand Down Expand Up @@ -86,9 +87,9 @@ export function Info({ asyncapi, params = {} }) {
{info.title()} {params.version || info.version()} documentation
</Header>

{info.hasExt('x-logo') && (
{extensions.has('x-logo') && (
<Text>
<Image src={info.ext('x-logo')} desc={`${info.title()} logo`} />
<Image src={extensions.get('x-logo').value()} desc={`${info.title()} logo`} />
</Text>
)}

Expand All @@ -104,7 +105,7 @@ export function Info({ asyncapi, params = {} }) {
<Link
href={externalDocs.url()}
>
{externalDocs.hasDescription() ? externalDocs.description() : 'Find more info here.'}
{externalDocs.description() || 'Find more info here.'}
</Link>
</Text>
)}
Expand All @@ -115,9 +116,7 @@ export function Info({ asyncapi, params = {} }) {
</Text>
)}

{asyncapi.hasTags() && (
<Tags name="Specification tags" tags={asyncapi.tags()} />
)}
<Tags name="Specification tags" item={info} />
</Text>
);
}
40 changes: 25 additions & 15 deletions components/Message.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { IndentationTypes, Text } from '@asyncapi/generator-react-sdk';
import { generateExample, getPayloadExamples, getHeadersExamples } from '@asyncapi/generator-filters';

import { Bindings } from './Bindings';
import { Extensions } from './Extensions';
import { Schema } from './Schema';
import { Tags } from './Tags';
import { Header, ListItem, Link, BlockQuote, CodeBlock, NewLine } from './common';

import { MessageHelpers } from '../helpers/message';

export function Message({ message }) { // NOSONAR
if (!message) {
return null;
}

// check typeof as fallback for older version than `2.4.0`
const messageId = typeof message.id === 'function' && message.id();
const messageId = typeof message.messageId === 'function' && message.messageId();
const headers = message.headers();
const payload = message.payload();
const correlationId = message.correlationId();
Expand All @@ -25,8 +26,9 @@ export function Message({ message }) { // NOSONAR
if (message.title()) {
header += ` ${message.title()}`;
}
if (message.uid()) {
header += ` \`${message.uid()}\``;
const id = message.messageId() || message.name() || message.id();
if (id) {
header += ` \`${id}\``;
}

return (
Expand Down Expand Up @@ -81,7 +83,7 @@ export function Message({ message }) { // NOSONAR
<Link
href={externalDocs.url()}
>
{externalDocs.hasDescription() ? externalDocs.description() : 'Find more info here.'}
{externalDocs.description() || 'Find more info here.'}
</Link>
</Text>
)}
Expand All @@ -108,56 +110,64 @@ export function Message({ message }) { // NOSONAR
/>
<Extensions name="Message extensions" item={message} />

{message.hasTags() && (
<Tags name="Message tags" tags={message.tags()} />
)}
<Tags name="Message tags" item={message} />
</>
);
}

function Examples({ type = 'headers', message }) {
if (type === 'headers') {
const ex = getHeadersExamples(message);
const ex = MessageHelpers.getHeadersExamples(message);
if (ex) {
return (
<>
<BlockQuote>Examples of headers</BlockQuote>
<Example examples={ex} />
<ExamplesRenderer examples={ex} />
</>
);
}

const headers = message.headers();
if (!headers) {
return null;
}

return (
<>
<BlockQuote>Examples of headers _(generated)_</BlockQuote>
<Text newLines={2}>
<CodeBlock language='json'>{generateExample(message.headers().json())}</CodeBlock>
<CodeBlock language='json'>{MessageHelpers.generateExample(headers.json())}</CodeBlock>
</Text>
</>
);
}

const examples = getPayloadExamples(message);
const examples = MessageHelpers.getPayloadExamples(message);
if (examples) {
return (
<>
<BlockQuote>Examples of payload</BlockQuote>
<Example examples={examples} />
<ExamplesRenderer examples={examples} />
</>
);
}

const payload = message.payload();
if (!payload) {
return null;
}

return (
<>
<BlockQuote>Examples of payload _(generated)_</BlockQuote>
<Text newLines={2}>
<CodeBlock language='json'>{generateExample(message.payload().json())}</CodeBlock>
<CodeBlock language='json'>{MessageHelpers.generateExample(payload.json())}</CodeBlock>
</Text>
</>
);
}

function Example({ examples = [] }) {
function ExamplesRenderer({ examples }) {
if (examples.length === 0) {
return null;
}
Expand Down
90 changes: 45 additions & 45 deletions components/Operations.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Bindings } from './Bindings';
import { Extensions } from './Extensions';
import { Message } from './Message';
import { Schema } from './Schema';
import { Security } from './Servers';
import { Security } from './Security';
import { Tags } from './Tags';
import { Header, ListItem, Link } from './common';

Expand All @@ -13,36 +13,39 @@ import { FormatHelpers } from '../helpers/format';

export function Operations({ asyncapi }) {
const channels = asyncapi.channels();
if (!Object.keys(channels).length) {
if (channels.isEmpty()) {
return null;
}

const operationsList = [];
Object.entries(channels).forEach(([channelName, channel]) => {
if (channel.hasPublish()) {
operationsList.push(
<Operation
key={`pub-${channelName}`}
type='publish'
asyncapi={asyncapi}
operation={channel.publish()}
channelName={channelName}
channel={channel}
/>
);
}
if (channel.hasSubscribe()) {
operationsList.push(
<Operation
key={`sub-${channelName}`}
type='subscribe'
asyncapi={asyncapi}
operation={channel.subscribe()}
channelName={channelName}
channel={channel}
/>
);
}
channels.all().map(channel => {
const channelName = channel.address();
channel.operations().all().forEach(operation => {
if (operation.action() === 'publish') {
jonaslagoni marked this conversation as resolved.
Show resolved Hide resolved
operationsList.push(
<Operation
key={`pub-${channelName}`}
type='publish'
asyncapi={asyncapi}
operation={operation}
channelName={channelName}
channel={channel}
/>
);
}
if (operation.action() === 'subscribe') {
operationsList.push(
<Operation
key={`sub-${channelName}`}
type='subscribe'
asyncapi={asyncapi}
operation={operation}
channelName={channelName}
channel={channel}
/>
);
}
});
});

return (
Expand All @@ -60,12 +63,11 @@ function Operation({ type, asyncapi, operation, channelName, channel }) { // NOS
return null;
}

const operationId = operation.id();
const operationId = operation.operationId();
const externalDocs = operation.externalDocs();
// check typeof as fallback for older version than `2.2.0`
const servers = typeof channel.servers === 'function' && channel.servers();
// check typeof as fallback for older version than `2.4.0`
const security = typeof operation.security === 'function' && operation.security();
const applyToAllServers = asyncapi.servers().all().length === channel.servers().all().length;
const servers = applyToAllServers ? [] : channel.servers().all();
const security = operation.security();
const renderedType = type === 'publish' ? 'PUB' : 'SUB';
const showInfoList = operationId || (servers && servers.length);

Expand All @@ -88,8 +90,9 @@ function Operation({ type, asyncapi, operation, channelName, channel }) { // NOS
<ListItem>
Available only on servers:{' '}
{servers.map(s => {
const slug = FormatHelpers.slugify(s);
return `[${s}](#${slug}-server)`;
const serverId = s.id();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tested with https://raw.githubusercontent.com/asyncapi/asyncapi/2.0.0/examples/2.0.0/streetlights.yml

with current template release, it is now showing up, as I do not have any info on a channel level that given channel is only or production or somewhere else

with this PR, I get text: * Available only on servers: [production](#production-server) which is not true

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically it's true because, without the channel explicitly defining a server, it's every server defined in servers.

Copy link
Member Author

@jonaslagoni jonaslagoni Aug 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the parser-api's doing, because it defaults to all servers, because the channel defines none 🙂

Copy link
Member Author

@jonaslagoni jonaslagoni Aug 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@derberg question is, do you want it to be the same as before or with this new display?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

but there is just one server, so sentence Available only on servers: production is only confusing, like wait are there any other servers available?. It's like with a warning on a plastic bag to not put it on your head, like why would I even try 😄

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They do it in the US 😆

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, I know 🤣 but markdown-template is not used only in the US 😄

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, changed the implementation to only show the servers the application is operating on when it is NOT all servers 🙂

const slug = FormatHelpers.slugify(serverId);
return `[${serverId}](#${slug}-server)`;
}).join(', ')}
</ListItem>
)}
Expand All @@ -112,18 +115,16 @@ function Operation({ type, asyncapi, operation, channelName, channel }) { // NOS
<Link
href={externalDocs.url()}
>
{externalDocs.hasDescription() ? externalDocs.description() : 'Find more info here.'}
{externalDocs.description() || 'Find more info here.'}
</Link>
</Text>
)}

{operation.hasTags() && (
<Tags name="Operation tags" tags={operation.tags()} />
)}
<Tags name="Operation tags" item={operation} />

<OperationParameters channel={channel} />

<Security security={security} asyncapi={asyncapi} header='Additional security requirements' />
<Security security={security} header='Additional security requirements' />

<Bindings
name="Channel specific information"
Expand All @@ -143,7 +144,7 @@ function Operation({ type, asyncapi, operation, channelName, channel }) { // NOS
}

function OperationParameters({ channel }) {
const parameters = SchemaHelpers.parametersToSchema(channel.parameters());
const parameters = SchemaHelpers.parametersToSchema(channel.parameters().all());
if (!parameters) {
return null;
}
Expand All @@ -157,11 +158,10 @@ function OperationParameters({ channel }) {
}

function OperationMessages({ operation }) {
const hasMessages = operation.hasMultipleMessages() || !!operation.message(0);
if (!hasMessages) {
const messages = operation.messages().all();
if (messages.length === 0) {
return null;
}
const messages = operation.messages();

return (
<>
Expand All @@ -170,8 +170,8 @@ function OperationMessages({ operation }) {
Accepts **one of** the following messages:
</Text>
)}
{messages.map(msg => (
<Message title={`Message \`${msg.uid()}\``} message={msg} key={msg.uid()} />
{messages.map((msg, idx) => (
<Message message={msg} key={`message-${idx}`} />
))}
</>
);
Expand Down
Loading