Skip to content

Commit

Permalink
migrate from using file templates to rendering a list of File components
Browse files Browse the repository at this point in the history
  • Loading branch information
kaushik-rishi committed Mar 19, 2024
1 parent eb08df7 commit b833483
Show file tree
Hide file tree
Showing 3 changed files with 203 additions and 154 deletions.
145 changes: 0 additions & 145 deletions template/src/api/handlers/$$channel$$.js

This file was deleted.

184 changes: 184 additions & 0 deletions template/src/api/handlers/handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
import { docline } from "@asyncapi/generator-filters/src/customFilters";
import {
convertOpertionIdToMiddlewareFn,
convertToFilename,
} from "../../../../helpers/index";
import { File } from "@asyncapi/generator-react-sdk";

function publishHandler(channel) {
if (!channel.hasPublish()) {
return "";
}

const lambdaChannel = channel.publish().ext("x-lambda");
const publishOperationId = channel.publish().id();
const publishMessage = channel.publish().message(0);

const exportedHandler = `
/**
* Registers a middleware function for the ${publishOperationId} 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.${convertOpertionIdToMiddlewareFn(
channel.publish().id()
)} = (middlewareFn) => {
if (typeof middlewareFn !== 'function') {
throw new TypeError('middlewareFn must be a function');
}
${publishOperationId}Middlewares.push(middlewareFn);
}
`;

const privateHandlerLogic = `
/**
* ${channel.publish().summary() || ""}
*
* @param {object} options
* @param {object} options.message
${
publishMessage.headers()
? Object.entries(publishMessage.headers().properties())
.map(([fieldName, field]) => {
return docline(field, fieldName, "options.message.headers");
})
.join("\n")
: ""
}
*
${
publishMessage.payload()
? Object.entries(publishMessage.payload().properties())
.map(([fieldName, field]) => {
return docline(field, fieldName, "options.message.headers");
})
.join("\n")
: ""
}
*/
handler._${publishOperationId} = async ({message}) => {
${
lambdaChannel
? `
fetch('${lambdaChannel.url}}', {
method: '${lambdaChannel.method || "POST"}',
body: JSON.stringify(${lambda.body}),
${lambda.headers ? `headers: ${lambda.headers}` : ""}
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => { throw err; });`
: `for (const middleware of ${publishOperationId}Middlewares) {
await middleware(message);
}`
}
};
`;

return `
${lambdaChannel ? "const fetch = require('node-fetch');" : ""}
const ${publishOperationId}Middlewares = [];
${exportedHandler}
${privateHandlerLogic}
`;
}

function subscribeHandler(channel) {
if (!channel.hasSubscribe()) {
return "";
}

const subscribeOperationId = channel.subscribe().id();
const subscribeMessage = channel.subscribe().message(0);

const exportedHandler = `
/**
* Registers a middleware function for the ${subscribeOperationId} 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.${convertOpertionIdToMiddlewareFn(
channel.subscribe().id()
)} = (middlewareFn) => {
if (typeof middlewareFn !== 'function') {
throw new TypeError('middlewareFn must be a function');
}
${subscribeOperationId}Middlewares.push(middlewareFn);
}
`;

const privateHandlerLogic = `
/**
* ${channel.subscribe().summary() || ""}
*
* @param {object} options
* @param {object} options.message
${
subscribeMessage.headers()
? Object.entries(subscribeMessage.headers().properties())
.map(([fieldName, field]) => {
return docline(field, fieldName, "options.message.headers");
})
.join("\n")
: ""
}
*
${
subscribeMessage.payload()
? Object.entries(subscribeMessage.payload().properties())
.map(([fieldName, field]) => {
return docline(field, fieldName, "options.message.headers");
})
.join("\n")
: ""
}
*/
handler._${subscribeOperationId} = async ({message}) => {
for (const middleware of ${subscribeOperationId}Middlewares) {
await middleware(message);
}
};
`;

return `
const ${subscribeOperationId}Middlewares = [];
${exportedHandler}
${privateHandlerLogic}
`;
}

export default function handlerRender({
asyncapi,
}) {
const general = `
const handler = module.exports = {};
`;

const channels = asyncapi.channels();

return Object.entries(channels).map(([channelName, channel]) => {
let hasPublish = channel.publish();
let hasSubscribe = channel.hasSubscribe();

return (
<File name={`${convertToFilename(channelName)}.js`}>
{`
${general}
${hasPublish ? publishHandler(channel) : ""}
${hasSubscribe ? subscribeHandler(channel) : ""}
`}
</File>
);
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,10 @@ function subscribeHandler(channel, channelName) {
`;
}

export default function routeRender({channel, channelName, params}) {
function routeCode(channel, channelName) {
let hasPublish = channel.publish();
let hasSubscribe = channel.hasSubscribe();

const generalImport = `
const Router = require('hermesjs/lib/router');
const { validateMessage } = require('../../lib/message-validator');
Expand All @@ -116,11 +116,21 @@ export default function routeRender({channel, channelName, params}) {
module.exports = router;
`;

return <File>
{`
${generalImport}
${hasPublish ? publishHandler(channel, channelName): ""}
${hasSubscribe ? subscribeHandler(channel, channelName): ""}
`}
</File>;
return (
<File name={`${convertToFilename(channelName)}.js`}>
{`
${generalImport}
${hasPublish ? publishHandler(channel, channelName): ""}
${hasSubscribe ? subscribeHandler(channel, channelName): ""}
`}
</File>
);
}

export default function routeRender({asyncapi}) {
const channels = asyncapi.channels();

return Object.entries(channels).map(([channelName, channel]) => {
return routeCode(channel, channelName);
});
}

0 comments on commit b833483

Please sign in to comment.