Skip to content

Commit

Permalink
Migration completed
Browse files Browse the repository at this point in the history
  • Loading branch information
ItshMoh committed Sep 21, 2024
1 parent 313b74d commit 7a3934a
Show file tree
Hide file tree
Showing 5 changed files with 136 additions and 94 deletions.
48 changes: 0 additions & 48 deletions components/model-class.js

This file was deleted.

6 changes: 0 additions & 6 deletions hooks/post-process.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,5 @@ module.exports = {
}
}
}

// If there are no schemas, we expect to find an anonymous one embedded in a payload. If we do have schemas we assume we don't need this.
// This will turn out to be a bug if we ever have a file with schemas, but which also has an anonymous schema embedded in an operation.
if (hasSchema) {
fs.unlinkSync(path.resolve(generator.targetDir, 'payload.py'));
}
}
}
52 changes: 52 additions & 0 deletions partials/model-class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const _ = require('lodash');
const getTypeInfo = require('../helpers/all').getTypeInfo;
const indent1 = require('../helpers/all').indent1;
const indent2 = require('../helpers/all').indent2;
const indent3 = require('../helpers/all').indent3;
const indent4 = require('../helpers/all').indent4;

function modelClass(name, properties, required, indentLevel = 1) {
const className = _.upperFirst(name);

let classDefinition = `${indent1(indentLevel)}class ${className}(Entity):\n`;

Object.entries(properties).forEach(([propName, prop]) => {
const typeInfo = getTypeInfo([propName, prop]);

if (typeInfo.recursive) {
classDefinition += modelClass(
typeInfo.innerType, typeInfo.properties, prop.required(), indentLevel + 1
);
} else if (typeInfo.generalType === 'enum') {
classDefinition += `${indent2(indentLevel)}class ${typeInfo.type}(str, Enum):\n`;
typeInfo.enum.forEach((value) => {
classDefinition += `${indent3(indentLevel)}${value} = '${value}'\n`;
});
classDefinition += `${indent2(indentLevel)}\n`;
}
});

classDefinition += `${indent2(indentLevel)}def __init__(self,\n`;

Object.entries(properties).forEach(([propName, prop], index) => {
const typeInfo = getTypeInfo([propName, prop]);
const separator = index === 0 ? '' : ',\n';
classDefinition += `${separator}${indent4(indentLevel)}${typeInfo.pythonName}: ${typeInfo.pythonType}`;
});

classDefinition += `):\n`;

Object.entries(properties).forEach(([propName, prop]) => {
const typeInfo = getTypeInfo([propName, prop]);
classDefinition += `${indent3(indentLevel)}self.${typeInfo.pythonName} = ${typeInfo.pythonName}\n`;
});

if (Object.keys(properties).length === 0) {
classDefinition += `${indent3(indentLevel)}pass\n`;
}

classDefinition += `${indent1(indentLevel)}\n`;
return classDefinition;
}

module.exports = { modelClass }
89 changes: 49 additions & 40 deletions template/main.py.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const { File } = require('@asyncapi/generator-react-sdk');
const _ = require('lodash');
const { getRealSubscriber } = require('../helpers/all.js')
const {getFunctionNameByChannel } = require('../helpers/all.js')
const {getPayloadClass }= require('../helpers/all.js')
const { functionName } = require('../helpers/all.js')
const { payloadClass }= require('../helpers/all.js')
const {getFirstPublisherMessenger } = require('../helpers/all.js')
const {getMessengers } = require('../helpers/all.js')

Expand All @@ -14,14 +14,10 @@ import time
import messaging
`;

if (asyncapi.components() && asyncapi.components().schemas()) {
Object.entries(asyncapi.components().schemas()).forEach(([schemaName, schema]) => {
const moduleName = _.lowerFirst(schemaName);
code += `from ${moduleName} import ${_.upperFirst(schemaName)}\n`;
});
} else {
code += 'from payload import Payload\n';
}
Object.entries(asyncapi.components().schemas()).map(([schemaName, schema]) => {
const moduleName = _.lowerFirst(schemaName);
code += `from ${moduleName} import ${_.upperFirst(schemaName)}\n`;
});

code += `
# Config has the connection properties.
Expand All @@ -32,7 +28,22 @@ def getConfig():
return config
`;


const channels = asyncapi.channels();

Object.entries(channels).map(([channelName, channel]) => {
const sub = getRealSubscriber([asyncapi.info(), params, channel]);
if (sub) {
const fnName = functionName([channelName, channel]);
const payloadClasses = payloadClass(sub);
const varName = _.lowerFirst(payloadClasses);
code += `def ${fnName}(client, userdata, msg):
jsonString = msg.payload.decode('utf-8')
logging.info('Received json: ' + jsonString)
${_.lowerFirst(payloadClasses)} = ${payloadClasses}.from_json(jsonString)
logging.info('Received message: ' + str(${_.lowerFirst(payloadClasses)}))
`;
}
})

code += `
def main():
Expand All @@ -41,48 +52,46 @@ def main():
config = getConfig()
`;

// const publishMessenger = getFirstPublisherMessenger(params, asyncapi);
// const messengers = getMessengers(params, asyncapi);
const publishMessenger = getFirstPublisherMessenger([params, asyncapi]);
const messengers = getMessengers([params, asyncapi]);

// messengers.forEach(messenger => {
// if (messenger.subscribeTopic) {
// code += ` ${messenger.name} = messaging.Messaging(config, '${messenger.subscribeTopic}', ${messenger.functionName})\n`;
// } else {
// code += ` ${messenger.name} = messaging.Messaging(config)\n`;
// }
messengers.forEach(messenger => {
if (messenger.subscribeTopic) {
code += ` ${messenger.name} = messaging.Messaging(config, '${messenger.subscribeTopic}', ${messenger.functionName})\n`;
} else {
code += ` ${messenger.name} = messaging.Messaging(config)\n`;
}

// if (publishMessenger) {
// code += ` ${messenger.name}.loop_start()\n`;
// } else {
// code += ` ${messenger.name}.loop_forever()\n`;
// }
// });
if (publishMessenger) {
code += ` ${messenger.name}.loop_start()\n`;
} else {
code += ` ${messenger.name}.loop_forever()\n`;
}
});

// if (publishMessenger) {
// code += `
// # Example of how to publish a message. You will have to add arguments to the constructor on the next line:
// payload = ${publishMessenger.payloadClass}()
// payloadJson = payload.to_json()
// while True:
// ${publishMessenger.name}.publish('${publishMessenger.publishTopic}', payloadJson)
// time.sleep(1)
// `;
// }
if (publishMessenger) {
code += `
# Example of how to publish a message. You will have to add arguments to the constructor on the next line:
payload = ${publishMessenger.payloadClass}()
payloadJson = payload.to_json()
while True:
${publishMessenger.name}.publish('${publishMessenger.publishTopic}', payloadJson)
time.sleep(1)
`;
}

code += `if __name__ == '__main__':
main()`

return code;
}

function MainFile({ asyncapi, params }) {
const generatedCode = generatePythonCode(asyncapi, params);
// const allChannels = channels.all()
console.log("HIIII",asyncapi.channels())
console.log("typeof",typeof asyncapi.channels())


return (
<File name="main.py">
{generatedCode}
{/* {`heello from msin`} */}
</File>
);
}
Expand Down
35 changes: 35 additions & 0 deletions template/schema.py.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const { File } = require('@asyncapi/generator-react-sdk');
const { modelClass } = require('../partials/model-class.js')
const getImports = require('../helpers/all.js').getImports
const convertToFileName = require('../helpers/utils.js')

function generateModelCode(schemaName, schema) {
let code = `from enum import Enum
from typing import Sequence
from entity import Entity
`;

const code_imports = getImports(schema);
code += code_imports + '\n';

code += modelClass(schemaName, schema.properties(), schema.required() | [] , 0);

return code;
}

function ModelFile({ asyncapi }) {
const files = [];
const schemas = asyncapi.components().schemas()

Object.entries(schemas).forEach(([schemaName, schema]) => {
const generatedCode = generateModelCode(schemaName, schema);
files.push(
<File name={`${convertToFileName(schemaName)}.py`}>
{generatedCode}
</File>
);
});
return files;
}

module.exports = ModelFile;

0 comments on commit 7a3934a

Please sign in to comment.