BACKEND DONE FOR ALL APPS
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
export interface ParsedMessage {
|
||||
operationCode: string;
|
||||
metaInfo?: { [key: string]: any };
|
||||
fileContent?: Buffer;
|
||||
}
|
||||
|
||||
export class MessageHandler {
|
||||
// Format the message with operationCode, guid, metaInfo, and fileContent (Base64 for fileContent)
|
||||
static formatMessage(
|
||||
operationCode: string,
|
||||
metaInfo?: { [key: string]: any },
|
||||
fileContent?: Buffer
|
||||
): string {
|
||||
let message = `${operationCode}\n`; // First part: operationCode and guid
|
||||
|
||||
if (metaInfo && Object.keys(metaInfo).length > 0) {
|
||||
message += `${JSON.stringify(metaInfo)}\n`; // Add metaInfo
|
||||
}
|
||||
|
||||
if (fileContent && fileContent.length > 0) {
|
||||
message += fileContent.toString('base64'); // Convert buffer to Base64 for fileContent
|
||||
}
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
// Parse the incoming message (convert Base64 back to Buffer if fileContent is present)
|
||||
static parseMessage(msg: string): ParsedMessage {
|
||||
const parts = msg.split('\n'); // Split by \n (operationCode, metaInfo, and fileContent are on separate lines)
|
||||
|
||||
// First part should always be the operation code
|
||||
const operationCode = parts[0]?.trim();
|
||||
if (!operationCode) {
|
||||
throw new Error('Missing operation code in the message');
|
||||
}
|
||||
|
||||
let metaInfo: { [key: string]: any } | undefined = undefined;
|
||||
let fileContent: Buffer | undefined = undefined;
|
||||
|
||||
// Parse the metaInfo (JSON object) if present
|
||||
if (parts[1]) {
|
||||
try {
|
||||
metaInfo = JSON.parse(parts[1].trim());
|
||||
} catch (err) {
|
||||
console.error('Invalid metaInfo JSON format:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Convert Base64 string back to Buffer for fileContent if present
|
||||
if (parts[2]) {
|
||||
fileContent = Buffer.from(parts[2].trim(), 'base64');
|
||||
}
|
||||
|
||||
return {
|
||||
operationCode,
|
||||
metaInfo,
|
||||
fileContent,
|
||||
};
|
||||
}
|
||||
|
||||
// Validate if the parsed message contains an operation code
|
||||
static validateMessage(parsedMessage: ParsedMessage | null): boolean {
|
||||
return !!parsedMessage?.operationCode;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user