Skip to content

Commit

Permalink
feat: enable template to be installed an used as a library
Browse files Browse the repository at this point in the history
  • Loading branch information
kaushik-rishi committed Sep 21, 2023
1 parent eb89354 commit c0c75d6
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 23 deletions.
1 change: 1 addition & 0 deletions template/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "{{ asyncapi.info().title() | kebabCase }}",
"description": "{{ asyncapi.info().description() | oneLine }}",
"version": "{{ asyncapi.info().version() }}",
"main": "./src/api",
"scripts": {
"start": "node src/api/index.js"
},
Expand Down
35 changes: 26 additions & 9 deletions template/src/api/handlers/$$channel$$.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
{%- if channel.hasPublish() and channel.publish().ext('x-lambda') %}const fetch = require('node-fetch');{%- endif %}
const handler = module.exports = {};

const middlewares = [];
{% if channel.hasPublish() %}
const {{ channel.publish().id() }}Middlewares = [];

/**
* Registers a middleware function to be executed during request processing.
* Registers a middleware function for the {{ channel.publish().id() }} operation to be executed during request processing.
*
* Middleware functions have access to options object that you can use to access the message content and other helper functions
*
* @param {function} middlewareFn - The middleware function to be registered.
* @throws {TypeError} If middlewareFn is not a function.
*/
handler.registerMiddleware = (middlewareFn) => {
handler.{{ channel.publish().id() }} = (middlewareFn) => {
if (typeof middlewareFn !== 'function') {
throw new TypeError('middlewareFn must be a function');
}
middlewares.push(middlewareFn);
{{ channel.publish().id() }}Middlewares.push(middlewareFn);
}

{% if channel.hasPublish() %}
/**
* {{ channel.publish().summary() }}
*
Expand All @@ -35,7 +35,7 @@ handler.registerMiddleware = (middlewareFn) => {
{%- endfor %}
{%- endif %}
*/
handler.{{ channel.publish().id() }} = async ({message}) => {
handler._{{ channel.publish().id() }} = async ({message}) => {
{%- if channel.publish().ext('x-lambda') %}
{%- set lambda = channel.publish().ext('x-lambda') %}
fetch('{{ lambda.url }}', {
Expand All @@ -49,7 +49,7 @@ handler.{{ channel.publish().id() }} = async ({message}) => {
.then(json => console.log(json))
.catch(err => { throw err; });
{%- else %}
for (const middleware of middlewares) {
for (const middleware of {{ channel.publish().id() }}Middlewares) {
await middleware(message);
}
{%- endif %}
Expand All @@ -58,6 +58,23 @@ handler.{{ channel.publish().id() }} = async ({message}) => {
{%- endif %}

{%- if channel.hasSubscribe() %}
const {{ channel.subscribe().id() }}Middlewares = [];

/**
* Registers a middleware function for the {{ channel.subscribe().id() }} operation to be executed during request processing.
*
* Middleware functions have access to options object that you can use to access the message content and other helper functions
*
* @param {function} middlewareFn - The middleware function to be registered.
* @throws {TypeError} If middlewareFn is not a function.
*/
handler.{{ channel.subscribe().id() }} = (middlewareFn) => {
if (typeof middlewareFn !== 'function') {
throw new TypeError('middlewareFn must be a function');
}
{{ channel.subscribe().id() }}Middlewares.push(middlewareFn);
}

/**
* {{ channel.subscribe().summary() }}
*
Expand All @@ -74,8 +91,8 @@ handler.{{ channel.publish().id() }} = async ({message}) => {
{%- endfor %}
{%- endif %}
*/
handler.{{ channel.subscribe().id() }} = async ({message}) => {
for (const middleware of middlewares) {
handler._{{ channel.subscribe().id() }} = async ({message}) => {
for (const middleware of {{ channel.subscribe().id() }}Middlewares) {
await middleware(message);
}
};
Expand Down
41 changes: 31 additions & 10 deletions template/src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,35 @@ app.useOutbound(errorLogger);
app.useOutbound(logger);
app.useOutbound(json2string);

app
.listen()
.then((adapters) => {
console.log(cyan.underline(`${config.app.name} ${config.app.version}`), gray('is ready!'), '\n');
adapters.forEach(adapter => {
console.log('🔗 ', adapter.name(), gray('is connected!'));
});
})
.catch(console.error);
function init() {
app
.listen()
.then((adapters) => {
console.log(cyan.underline(`${config.app.name} ${config.app.version}`), gray('is ready!'), '\n');
adapters.forEach(adapter => {
console.log('🔗 ', adapter.name(), gray('is connected!'));
});
})
.catch(console.error);
}

const handlers = {
{%- for channelName, channel in asyncapi.channels() -%}
{% if channel.hasPublish() %}
{{ channel.publish().id() }}: require('./handlers/{{ channelName | convertToFilename }}').{{ channel.publish().id() }},
{%- endif -%}
{% if channel.hasSubscribe() %}
{{ channel.subscribe().id() }}: require('./handlers/{{ channelName | convertToFilename }}').{{ channel.subscribe().id() }},
{% endif %}
{%- endfor -%}
};

const client = {
app,
init,
...handlers
};

module.exports = app;
module.exports = {
client
};
8 changes: 4 additions & 4 deletions template/src/api/routes/$$channel$$.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ router.use('{{ channelName | toHermesTopic }}', async (message, next) => {
} catch { };
{% endfor -%}
if (nValidated === 1) {
await {{ channelName | camelCase }}Handler.{{ channel.publish().id() }}({message});
await {{ channelName | camelCase }}Handler._{{ channel.publish().id() }}({message});
next()
} else {
throw new Error(`${nValidated} of {{ channel.publish().messages().length }} message schemas matched when exactly 1 should match`);
}
{% else %}
await validateMessage(message.payload,'{{ channelName }}','{{ channel.publish().message().name() }}','publish');
await {{ channelName | camelCase }}Handler.{{ channel.publish().id() }}({message});
await {{ channelName | camelCase }}Handler._{{ channel.publish().id() }}({message});
next();
{% endif %}
} catch (e) {
Expand All @@ -61,14 +61,14 @@ router.useOutbound('{{ channelName | toHermesTopic }}', async (message, next) =>
nValidated = await validateMessage(message.payload,'{{ channelName }}','{{ channel.subscribe().message(i).name() }}','subscribe', nValidated);
{% endfor -%}
if (nValidated === 1) {
await {{ channelName | camelCase }}Handler.{{ channel.subscribe().id() }}({message});
await {{ channelName | camelCase }}Handler._{{ channel.subscribe().id() }}({message});
next()
} else {
throw new Error(`${nValidated} of {{ channel.subscribe().messages().length }} message schemas matched when exactly 1 should match`);
}
{% else %}
await validateMessage(message.payload,'{{ channelName }}','{{ channel.subscribe().message().name() }}','subscribe');
await {{ channelName | camelCase }}Handler.{{ channel.subscribe().id() }}({message});
await {{ channelName | camelCase }}Handler._{{ channel.subscribe().id() }}({message});
next();
{% endif %}
} catch (e) {
Expand Down

0 comments on commit c0c75d6

Please sign in to comment.