Skip to content

Commit

Permalink
refactor: resolve sonarcloud bugs (asyncapi#432)
Browse files Browse the repository at this point in the history
  • Loading branch information
Souvikns authored May 16, 2023
1 parent b72aafb commit 8387476
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 57 deletions.
6 changes: 3 additions & 3 deletions src/adapters/http/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class HttpClientAdapter extends Adapter {
const auth: HttpAuthConfig = await this.getAuthConfig(config.client.auth)
headers['Authentication'] = auth?.token
const serverUrl = this.serverUrlExpanded
this.channelNames.forEach(async (channelName) => {
for (const channelName of this.channelNames) {
const channelInfo = this.parsedAsyncAPI.channel(channelName)
const httpChannelBinding = channelInfo.binding('http')
const channelServers = channelInfo.servers()
Expand All @@ -34,7 +34,7 @@ class HttpClientAdapter extends Adapter {
) {
const method = httpChannelBinding.method
const url = `${serverUrl}/${channelName}`
const body:any = message.payload
const body: any = message.payload
const query: { [key: string]: string } | { [key: string]: string[] } = message.query
got({
method,
Expand All @@ -50,7 +50,7 @@ class HttpClientAdapter extends Adapter {
this.emit('error', err)
})
}
})
}
}
private createMessage(channelName: string, payload: any) {
return new GleeMessage({
Expand Down
6 changes: 3 additions & 3 deletions src/adapters/mqtt/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ class MqttAdapter extends Adapter {
const operation = this.parsedAsyncAPI.channel(channel).publish()
const binding = operation.binding('mqtt')
this.client.subscribe(channel, {
qos: binding && binding.qos ? binding.qos : 0,
qos: binding?.qos ? binding.qos : 0,
})
})
}
Expand Down Expand Up @@ -206,8 +206,8 @@ class MqttAdapter extends Adapter {
message.channel,
message.payload,
{
qos: binding && binding.qos ? binding.qos : 2,
retain: binding && binding.retain ? binding.retain : false,
qos: binding?.qos ? binding.qos : 2,
retain: binding?.retain ? binding.retain : false,
},
(err) => {
if (err) {
Expand Down
2 changes: 1 addition & 1 deletion src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ if (command === 'dev') {
} else if (command === 'start') {
import('./start.js')
} else if (command === 'docs') {
docs()
docs().catch(e => logTypeScriptMessage(e))
} else {
console.error(`Unknown command "${args[0]}"`)
}
Expand Down
2 changes: 1 addition & 1 deletion src/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ import generateDocs from './lib/docs.js'
export default async () => {
const config = await initializeConfigs()
const parsedAsyncAPI = await getParsedAsyncAPI()
generateDocs(parsedAsyncAPI, config, null)
await generateDocs(parsedAsyncAPI, config, null)
}
26 changes: 13 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export default async function GleeAppInitializer () {
app.useOutbound(logger)
app.use(errorLogger)
app.useOutbound(errorLogger)
generateDocs(parsedAsyncAPI, config, null)
await generateDocs(parsedAsyncAPI, config, null)

channelNames.forEach((channelName) => {
const channel = parsedAsyncAPI.channel(channelName)
Expand All @@ -85,62 +85,62 @@ export default async function GleeAppInitializer () {
}
})

app.on('adapter:connect', (e: EnrichedEvent) => {
app.on('adapter:connect', async (e: EnrichedEvent) => {
logLineWithIcon(':zap:', `Connected to server ${e.serverName}.`, {
highlightedWords: [e.serverName],
})
runLifecycleEvents('onConnect', {
await runLifecycleEvents('onConnect', {
glee: app,
serverName: e.serverName,
connection: e.connection,
})
})

app.on('adapter:reconnect', (e: EnrichedEvent) => {
app.on('adapter:reconnect', async (e: EnrichedEvent) => {
logLineWithIcon('↪', `Reconnected to server ${e.serverName}.`, {
highlightedWords: [e.serverName],
iconColor: '#0f0',
})
runLifecycleEvents('onReconnect', {
await runLifecycleEvents('onReconnect', {
glee: app,
serverName: e.serverName,
connection: e.connection,
})
})

app.on('adapter:close', (e: EnrichedEvent) => {
app.on('adapter:close', async (e: EnrichedEvent) => {
logLineWithIcon('x', `Closed connection with server ${e.serverName}.`, {
highlightedWords: [e.serverName],
iconColor: '#f00',
disableEmojis: true,
})
runLifecycleEvents('onDisconnect', {
await runLifecycleEvents('onDisconnect', {
glee: app,
serverName: e.serverName,
connection: e.connection,
})
})

app.on('adapter:server:ready', (e: EnrichedEvent) => {
app.on('adapter:server:ready', async (e: EnrichedEvent) => {
logLineWithIcon(':zap:', `Server ${e.serverName} is ready to accept connections.`, {
highlightedWords: [e.serverName],
})
runLifecycleEvents('onServerReady', {
await runLifecycleEvents('onServerReady', {
glee: app,
serverName: e.serverName,
})
})

app.on('adapter:server:connection:open', (e: EnrichedEvent) => {
runLifecycleEvents('onServerConnectionOpen', {
app.on('adapter:server:connection:open', async (e: EnrichedEvent) => {
await runLifecycleEvents('onServerConnectionOpen', {
glee: app,
serverName: e.serverName,
connection: e.connection,
})
})

app.on('adapter:server:connection:close', (e: EnrichedEvent) => {
runLifecycleEvents('onServerConnectionClose', {
app.on('adapter:server:connection:close', async (e: EnrichedEvent) => {
await runLifecycleEvents('onServerConnectionClose', {
glee: app,
serverName: e.serverName,
connection: e.connection,
Expand Down
36 changes: 18 additions & 18 deletions src/lib/docs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,23 @@ import Generator from '@asyncapi/generator'

export default async (spec, config, resDir) => {
const configData = config.docs
if(configData?.enabled === false) return
logInfoMessage(`Generating docs for your parsed specification...`)
const resolvedData = spec.json()
const generator = new Generator(
configData && configData.template
? configData.template
: '@asyncapi/markdown-template',
path.resolve(
resDir ? resDir : './',
configData && configData.folder ? configData.folder : 'docs'
)
if (configData?.enabled === false) return
logInfoMessage(`Generating docs for your parsed specification...`)
const resolvedData = spec.json()
const generator = new Generator(
configData?.template
? configData.template
: '@asyncapi/markdown-template',
path.resolve(
resDir ? resDir : './',
configData?.folder ? configData.folder : 'docs'
)
try {
await generator.generateFromString(JSON.stringify(resolvedData))
logInfoMessage('Successfully generated docs')
} catch (error) {
logError(error)
return error
}
)
try {
await generator.generateFromString(JSON.stringify(resolvedData))
logInfoMessage('Successfully generated docs')
} catch (error) {
logError(error)
return error
}
}
32 changes: 18 additions & 14 deletions src/lib/glee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,10 @@ export default class Glee extends EventEmitter {
*
* @param {Object} [options={}]
*/
constructor (options:GleeConfig = {}) {
super()
constructor(options: GleeConfig = {}) {
super({ captureRejections: true })

this.on('error', console.error)

this._options = options
this._router = new GleeRouter()
Expand All @@ -57,6 +59,8 @@ export default class Glee extends EventEmitter {
return this._clusterAdapter
}



/**
* Adds a connection adapter.
*
Expand All @@ -66,7 +70,7 @@ export default class Glee extends EventEmitter {
* @param {AsyncAPIDocument} parsedAsyncAPI The AsyncAPI document.
*/
addAdapter(Adapter: typeof GleeAdapter, { serverName, server, parsedAsyncAPI }: { serverName: string, server: Server, parsedAsyncAPI: AsyncAPIDocument }) {
this._adapters.push({Adapter, serverName, server, parsedAsyncAPI})
this._adapters.push({ Adapter, serverName, server, parsedAsyncAPI })
}

/**
Expand Down Expand Up @@ -128,7 +132,7 @@ export default class Glee extends EventEmitter {
promises.push(a.instance.connect())
})

if ( this._clusterAdapter ) {
if (this._clusterAdapter) {
this._clusterAdapter.instance = new this._clusterAdapter.Adapter(this)
promises.push(this._clusterAdapter.instance.connect())
}
Expand All @@ -139,7 +143,7 @@ export default class Glee extends EventEmitter {
/**
* Alias for `connect`.
*/
async listen (): Promise<any[]> {
async listen(): Promise<any[]> {
return this.connect()
}

Expand All @@ -150,7 +154,7 @@ export default class Glee extends EventEmitter {
* @param {String} serverName The name of the server this message is coming from.
* @param {GleeConnection} [connection] The connection used when receiving the message. Its type is unknown and must be handled by the adapters.
*/
injectMessage (message: GleeMessage, serverName: string, connection: GleeConnection) {
injectMessage(message: GleeMessage, serverName: string, connection: GleeConnection) {
message.serverName = serverName
message.connection = connection
message.setInbound()
Expand All @@ -168,7 +172,7 @@ export default class Glee extends EventEmitter {
* @param {Any} error The error.
* @param {String} [channel] The channel of the error.
*/
injectError (error: Error, channel?: string) {
injectError(error: Error, channel?: string) {
this._processError(
this._router.getErrorMiddlewares(),
error,
Expand All @@ -181,8 +185,8 @@ export default class Glee extends EventEmitter {
*
* @param {GleeMessage} message
*/
syncCluster (message: GleeMessage): void {
if ( this._clusterAdapter && !message.cluster ) {
syncCluster(message: GleeMessage): void {
if (this._clusterAdapter && !message.cluster) {
this._clusterAdapter.instance.send(message).catch((e: Error) => {
this._processError(this._router.getErrorMiddlewares(), e, message)
})
Expand All @@ -197,7 +201,7 @@ export default class Glee extends EventEmitter {
* @param {GleeMessage} message The message to pass to the middlewares.
* @private
*/
private _processMessage (middlewares: ChannelMiddlewareTuple[], errorMiddlewares: ChannelErrorMiddlewareTuple[], message: GleeMessage): void {
private _processMessage(middlewares: ChannelMiddlewareTuple[], errorMiddlewares: ChannelErrorMiddlewareTuple[], message: GleeMessage): void {
const mws =
middlewares
.filter(mw => matchChannel(mw.channel, message.channel))
Expand Down Expand Up @@ -254,18 +258,18 @@ export default class Glee extends EventEmitter {
* @param {GleeMessage} message The message to pass to the middlewares.
* @private
*/
private _processError (errorMiddlewares: ChannelErrorMiddlewareTuple[], error: Error, message: GleeMessage): void {
private _processError(errorMiddlewares: ChannelErrorMiddlewareTuple[], error: Error, message: GleeMessage): void {
const emws = errorMiddlewares.filter(emw => matchChannel(emw.channel, message.channel))
if (!emws.length) return

this._execErrorMiddleware(emws, 0, error, message)
}

private _execErrorMiddleware (emws: ChannelErrorMiddlewareTuple[], index: number, error: Error, message: GleeMessage) {
private _execErrorMiddleware(emws: ChannelErrorMiddlewareTuple[], index: number, error: Error, message: GleeMessage) {
const emwsLength = emws.length
emws[(index + emwsLength) % emwsLength].fn(error, message, (err: Error) => {
if (!emws[index+1]) return
this._execErrorMiddleware.call(null, emws, index+1, err, message)
if (!emws[index + 1]) return
this._execErrorMiddleware.call(null, emws, index + 1, err, message)
})
}
}
11 changes: 7 additions & 4 deletions src/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface IValidateDataReturn {
* @param {String} path The path.
* @param {String} channel The channel.
*/
export const getParams = (path: string, channel: string): {[key: string]: string} | null => {
export const getParams = (path: string, channel: string): { [key: string]: string } | null => {
if (path === undefined) return {}

const keys = []
Expand Down Expand Up @@ -108,7 +108,7 @@ export const arrayHasDuplicates = (array: any[]) => {
return (new Set(array)).size !== array.length
}

export const gleeMessageToFunctionEvent = (message: GleeMessage, glee:Glee): GleeFunctionEvent => {
export const gleeMessageToFunctionEvent = (message: GleeMessage, glee: Glee): GleeFunctionEvent => {
return {
payload: message.payload,
query: message.query,
Expand All @@ -122,13 +122,16 @@ export const gleeMessageToFunctionEvent = (message: GleeMessage, glee:Glee): Gle

export const isRemoteServer = (parsedAsyncAPI: AsyncAPIDocument, serverName: string): boolean => {
const remoteServers = parsedAsyncAPI.extension('x-remoteServers')
return remoteServers && remoteServers.includes(serverName)
if (remoteServers) {
return remoteServers.includes(serverName)
}
return false
}

export const resolveFunctions = async (object: any) => {
for (const key in object) {
if (typeof object[String(key)] === 'object' && !Array.isArray(object[String(key)])) {
resolveFunctions(object[String(key)])
await resolveFunctions(object[String(key)])
} else if (typeof object[String(key)] === 'function' && key !== 'auth') {
object[String(key)] = await object[String(key)]()
}
Expand Down

0 comments on commit 8387476

Please sign in to comment.