import * as fs from 'fs'; import { SchemaResponse } from '../models/schemas/types'; import { catalogEvents } from '../config/events'; export const updateImportFile = (list: SchemaResponse[]) => { let eventsWithOutImport: string[] = [] let eventsWithImport: string[] = [] let response = '' list.forEach( item => { if(catalogEvents[item.name]){ eventsWithImport.push(item.name) } else { eventsWithOutImport.push(item.name) } }); const importHeaderSection = getHeaderImportSection(eventsWithImport.join().split(',')) const importsUnknow = getBodyDefaultEvent( eventsWithOutImport.join().split(',') ); const importSectionGenerated = getBodyCustomEvent( eventsWithImport.join().split(',') ); const importSection = getImportSection( eventsWithImport.join().split(','), eventsWithOutImport.join().split(',') ); response = `${importHeaderSection}\n\n${importsUnknow}\n${importSectionGenerated}\n${importSection}`; saveFile('index.ts', response) } const saveFile = (file: string, body: string) => { const pathDestination = __dirname.replace('dist', 'src/models/'); const stream = fs.createWriteStream(`${pathDestination}${file}`); stream.once('open', function() { stream.write(body); stream.end(); }); } const getHeaderImportSection = (list: string []) => { return list .map(item => `import { ${item.charAt(0).toUpperCase()}${item.slice(1)} } from './events/${item}';`) .join('\n'); } const getBodyDefaultEvent = (list: string []) => { return list .map( item => `export type ${getMethodName(item)} = { ${item}: unknown; };\n` ) .join('\n'); } const getBodyCustomEvent = (list: string[]) => { return list .map( item => `export type ${getMethodName(item)} = { ${item}: ${item.charAt(0).toUpperCase()}${item.slice(1)}; };\n` ) .join('\n'); }; const getImportSection = (listWith: string[], listWithOut: string[]) => { let response = 'export type EventInputType =\n'; const importDefault = listWithOut .map(item => `| ${getMethodName(item)}`) .join('\n'); const importCustom = listWith .map(item => `| ${getMethodName(item)}`) .join('\n'); return `${response}${importDefault}\n${importCustom};`; }; const getMethodName = (name: string) => `${name.charAt(0).toUpperCase()}${name.slice(1)}Model`;