Skip to content

Commit

Permalink
refactor(backend): Change plugin.module.ts while create/delete plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
aXenDeveloper committed Oct 20, 2024
1 parent 3c15e82 commit 2fc2d6d
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 75 deletions.
8 changes: 1 addition & 7 deletions apps/backend/src/plugins/plugins.module.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
// ! DO NOT TOUCH THIS FILE!!! IT IS GENERATED BY VITNODE-CLI

import { Module } from '@nestjs/common';

import { WelcomeModule } from './welcome/welcome.module';
// ! === IMPORT ===

@Module({
imports: [
WelcomeModule,
// ! === MODULE ===
],
imports: [WelcomeModule],
})
export class PluginsModule {}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { join } from 'path';

import { ABSOLUTE_PATHS_BACKEND } from '../../../..';
import { ChangeFilesAdminPluginsService } from '../helpers/files/change/change.service';
import { UpdateModuleFileAdminPluginsService } from '../helpers/files/change/update-module-file.service';
import { CreateFilesAdminPluginsService } from '../helpers/files/create/create-files.service';
import { ShowAdminPlugins } from '../show/show.dto';
import { CreateAdminPluginsArgs } from './create.dto';
Expand All @@ -17,6 +18,7 @@ export class CreateAdminPluginsService {
private readonly databaseService: InternalDatabaseService,
private readonly createFilesService: CreateFilesAdminPluginsService,
private readonly changeFilesService: ChangeFilesAdminPluginsService,
private readonly updateModuleFileService: UpdateModuleFileAdminPluginsService,
) {}

async create({
Expand Down Expand Up @@ -52,6 +54,7 @@ export class CreateAdminPluginsService {
version_code: 1,
});
this.changeFilesService.changeFilesWhenCreate({ code });
await this.updateModuleFileService.updatePluginModuleFile(code, 'add');

// Create lang.json file inside the plugin frontend folder
const languages =
Expand Down
15 changes: 0 additions & 15 deletions packages/backend/src/core/admin/plugins/delete/contents.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,5 @@
import { changeCodePluginToCapitalLetters } from '../helpers/change-code-plugin-to-capital-letters';

export const removeModuleFromRootSchema = ({
code,
content,
}: {
code: string;
content: string;
}) => {
const name = changeCodePluginToCapitalLetters(code);

return content
.replace(`\n ${name}Module,`, '')
.replace(`\nimport { ${name}Module } from './${code}/${code}.module';`, '')
.replace(`\nimport { ${name}Module } from "./${code}/${code}.module";`, '');
};

export const removeDatabaseFromService = ({
code,
content,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import { eq } from 'drizzle-orm';
import * as fs from 'fs';

import { ChangeFilesAdminPluginsService } from '../helpers/files/change/change.service';
import { UpdateModuleFileAdminPluginsService } from '../helpers/files/change/update-module-file.service';

@Injectable()
export class DeleteAdminPluginsService {
constructor(
private readonly databaseService: InternalDatabaseService,
private readonly changeFilesService: ChangeFilesAdminPluginsService,
private readonly updateModuleFileService: UpdateModuleFileAdminPluginsService,
) {}

protected deleteFolderWhenExists(path: string) {
Expand All @@ -41,6 +43,7 @@ export class DeleteAdminPluginsService {

// Change files when delete
this.changeFilesService.changeFilesWhenDelete({ code });
await this.updateModuleFileService.updatePluginModuleFile(code, 'delete');

const modulePath = ABSOLUTE_PATHS_BACKEND.plugin({ code }).root;
this.deleteFolderWhenExists(modulePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,8 @@ import { join } from 'path';
import {
removeDatabaseFromService,
removeLangFromTypes,
removeModuleFromRootSchema,
} from '../../../delete/contents';
import {
changeDatabaseService,
changeLangTypes,
changeModuleRootSchema,
} from './contents';
import { changeDatabaseService, changeLangTypes } from './contents';

interface ChangeFilesContentType {
condition: (content: string) => boolean;
Expand Down Expand Up @@ -59,15 +54,6 @@ export class ChangeFilesAdminPluginsService {

changeFilesWhenCreate({ code }: { code: string }): void {
const files: ChangeFilesContentType[] = [
{
path: join(ABSOLUTE_PATHS_BACKEND.plugins, 'plugins.module.ts'),
content: content =>
changeModuleRootSchema({
content,
code,
}),
condition: content => !content.includes(`./${code}/${code}.module`),
},
{
path: join(ABSOLUTE_PATHS_BACKEND.backend, 'database', 'config.ts'),
content: content =>
Expand All @@ -93,15 +79,6 @@ export class ChangeFilesAdminPluginsService {

changeFilesWhenDelete({ code }: { code: string }): void {
const files: ChangeFilesContentType[] = [
{
path: join(ABSOLUTE_PATHS_BACKEND.plugins, 'plugins.module.ts'),
content: content =>
removeModuleFromRootSchema({
content,
code,
}),
condition: () => true,
},
{
path: join(ABSOLUTE_PATHS_BACKEND.backend, 'database', 'config.ts'),
content: content =>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,27 +1,5 @@
import { changeCodePluginToCapitalLetters } from '../../change-code-plugin-to-capital-letters';

export const changeModuleRootSchema = ({
admin,
code,
content,
}: {
admin?: boolean;
code: string;
content: string;
}) => {
const name = `${admin ? 'Admin' : ''}${changeCodePluginToCapitalLetters(code)}`;

return content
.replace(
'// ! === IMPORT ===',
`import { ${name}Module } from './${code}/${code}.module';\n// ! === IMPORT ===`,
)
.replace(
'\n // ! === MODULE ===',
`\n ${name}Module,\n // ! === MODULE ===`,
);
};

export const changeDatabaseService = ({
admin,
code,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { ABSOLUTE_PATHS_BACKEND } from '@/index';
import { Injectable } from '@nestjs/common';
import { existsSync } from 'fs';
import { readFile, writeFile } from 'fs/promises';
import { join } from 'path';

import { changeCodePluginToCapitalLetters } from '../../change-code-plugin-to-capital-letters';

@Injectable()
export class UpdateModuleFileAdminPluginsService {
async updatePluginModuleFile(code: string, action: 'add' | 'delete') {
const filePath = join(ABSOLUTE_PATHS_BACKEND.plugins, 'plugins.module.ts');
if (!existsSync(filePath)) {
throw new Error(`File not found: ${filePath}`);
}

const fileContent = await readFile(filePath, 'utf8');

// Regular expressions to extract import statements and imports array
const importRegex = /import { (\w+) } from ['"](.*)['"];/g;
const importsArrayRegex = /imports:\s*\[([^\]]*)\]/;

const existingImports = new Map<string, string>();
const existingModuleNames = new Set<string>();

// Extract existing import statements
let match: null | RegExpExecArray;
while ((match = importRegex.exec(fileContent)) !== null) {
const moduleName = match[1];
const modulePath = match[2];

if (moduleName === 'Module' && modulePath === '@nestjs/common') {
continue; // Skip the NestJS Module import
}

existingImports.set(moduleName, modulePath);
existingModuleNames.add(moduleName);
}

// Extract existing module names from the imports array
const importsArrayMatch = importsArrayRegex.exec(fileContent);
if (importsArrayMatch?.[1]) {
const modulesList = importsArrayMatch[1]
.split(',')
.map(m => m.trim())
.filter(m => m.length > 0);

modulesList.forEach(moduleName => existingModuleNames.add(moduleName));
}

// Determine the module name and path
const moduleName = `${changeCodePluginToCapitalLetters(code)}Module`;
const modulePath = `./${code}/${code}.module`;

// Add or remove the module based on the action
if (action === 'add') {
existingImports.set(moduleName, modulePath);
existingModuleNames.add(moduleName);
} else if (action === 'delete') {
existingImports.delete(moduleName);
existingModuleNames.delete(moduleName);
} else {
throw new Error(`Invalid action: ${action}`);
}

// Reconstruct import statements
let newFileContent = `import { Module } from '@nestjs/common';\n\n`;

existingImports.forEach((modulePath, moduleName) => {
newFileContent += `import { ${moduleName} } from '${modulePath}';\n`;
});

// Reconstruct the @Module decorator
const allModuleNames = Array.from(existingModuleNames).join(', ');
newFileContent += `\n@Module({\n imports: [${allModuleNames}],\n})\nexport class PluginsModule {}\n`;

// Write the updated content back to the file
await writeFile(filePath, newFileContent, 'utf8');
}
}
2 changes: 2 additions & 0 deletions packages/backend/src/core/admin/plugins/plugins.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { DownloadAdminPluginsService } from './download/download.service';
import { EditAdminPluginsResolver } from './edit/edit.resolver';
import { EditAdminPluginsService } from './edit/edit.service';
import { ChangeFilesAdminPluginsService } from './helpers/files/change/change.service';
import { UpdateModuleFileAdminPluginsService } from './helpers/files/change/update-module-file.service';
import { CreateFilesAdminPluginsService } from './helpers/files/create/create-files.service';
import { AdminNavPluginsModule } from './nav/nav-plugins.module';
import { AdminPermissionsAdminPluginsModule } from './permissions-admin/permissions-admin.module';
Expand All @@ -33,6 +34,7 @@ import { UploadAdminPluginsService } from './upload/upload.service';
UploadAdminPluginsService,
EditAdminPluginsResolver,
EditAdminPluginsService,
UpdateModuleFileAdminPluginsService,
],
imports: [AdminNavPluginsModule, AdminPermissionsAdminPluginsModule],
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
// ! DO NOT TOUCH THIS FILE!!! IT IS GENERATED BY VITNODE-CLI

import { Module } from '@nestjs/common';

import { WelcomeModule } from './welcome/welcome.module';
// ! === IMPORT ===

@Module({
imports: [
WelcomeModule,
// ! === MODULE ===
],
imports: [WelcomeModule],
})
export class PluginsModule {}

0 comments on commit 2fc2d6d

Please sign in to comment.