Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: bootstrap support #7072

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/backend/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"test:coverage": "c8 ava --concurrency 1 --serial",
"postinstall": "prisma generate",
"data-migration": "node --loader ts-node/esm/transpile-only.mjs ./src/data/index.ts",
"make-action": "node --loader ts-node/esm/transpile-only.mjs ./src/core/bootstrap/bin/index.ts create",
"predeploy": "yarn prisma migrate deploy && node --import ./scripts/register.js ./dist/data/index.js run"
},
"dependencies": {
Expand Down
2 changes: 2 additions & 0 deletions packages/backend/server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { get } from 'lodash-es';

import { AppController } from './app.controller';
import { AuthModule } from './core/auth';
import { BootstrapModule } from './core/bootstrap';
import { ADD_ENABLED_FEATURES, ServerConfigModule } from './core/config';
import { DocModule } from './core/doc';
import { FeatureModule } from './core/features';
Expand Down Expand Up @@ -129,6 +130,7 @@ function buildAppModule() {
// graphql server only
.useIf(
config => config.flavor.graphql,
BootstrapModule,
ServerConfigModule,
GqlModule,
StorageModule,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { PrismaClient } from '@prisma/client';

import { refreshPrompts } from './utils/prompts';

export class UpgradePrompts1716659387824 {
// do the action
static async run(db: PrismaClient) {
await refreshPrompts(db);
}
}
24 changes: 24 additions & 0 deletions packages/backend/server/src/core/bootstrap/bin/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Module } from '@nestjs/common';

import { AppModule as BusinessAppModule } from '../../../app.module';
import { ConfigModule } from '../../../fundamentals/config';
import { CreateCommand, NameQuestion } from './create';

@Module({
imports: [
ConfigModule.forRoot({
doc: {
manager: {
enableUpdateAutoMerging: false,
},
},
metrics: {
enabled: false,
customerIo: {},
},
}),
BusinessAppModule,
],
providers: [NameQuestion, CreateCommand],
})
export class CliAppModule {}
71 changes: 71 additions & 0 deletions packages/backend/server/src/core/bootstrap/bin/create.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';

import { Logger } from '@nestjs/common';
import { camelCase, kebabCase, upperFirst } from 'lodash-es';
import {
Command,
CommandRunner,
InquirerService,
Question,
QuestionSet,
} from 'nest-commander';

@QuestionSet({ name: 'name-questions' })
export class NameQuestion {
@Question({
name: 'name',
message: 'Name of the data action script:',
})
parseName(val: string) {
return val.trim();
}
}

@Command({
name: 'create',
arguments: '[name]',
description: 'create a bootstrap action script',
})
export class CreateCommand extends CommandRunner {
logger = new Logger(CreateCommand.name);
constructor(private readonly inquirer: InquirerService) {
super();
}

override async run(inputs: string[]): Promise<void> {
let name = inputs[0];

if (!name) {
name = (
await this.inquirer.ask<{ name: string }>('name-questions', undefined)
).name;
}

const timestamp = Date.now();
const content = this.createScript(upperFirst(camelCase(name)) + timestamp);
const fileName = `${timestamp}-${kebabCase(name)}.ts`;
const filePath = join(
fileURLToPath(import.meta.url),
'../../actions',
fileName
);

this.logger.log(`Creating ${fileName}...`);
writeFileSync(filePath, content);
this.logger.log('Action file created at', filePath);
this.logger.log('Done');
}

private createScript(name: string) {
return `
import { PrismaClient } from '@prisma/client';

export class ${name} {
// do the action
static async run(db: PrismaClient) {}
}
`;
}
}
15 changes: 15 additions & 0 deletions packages/backend/server/src/core/bootstrap/bin/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import '../../../prelude';

import { Logger } from '@nestjs/common';
import { CommandFactory } from 'nest-commander';

async function bootstrap() {
const { CliAppModule } = await import('./app');
await CommandFactory.run(CliAppModule, new Logger()).catch(e => {
console.error(e);
process.exit(1);
});
process.exit(0);
}

await bootstrap();
9 changes: 9 additions & 0 deletions packages/backend/server/src/core/bootstrap/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';

import { BootstrapService } from './service';

@Module({
providers: [BootstrapService],
exports: [BootstrapService],
})
export class BootstrapModule {}
72 changes: 72 additions & 0 deletions packages/backend/server/src/core/bootstrap/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { readdirSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { PrismaClient } from '@prisma/client';

interface Action {
file: string;
name: string;
run: (db: PrismaClient, injector: ModuleRef) => Promise<void>;
}

@Injectable()
export class BootstrapService implements OnModuleInit {
private readonly logger = new Logger(BootstrapService.name);

constructor(
private readonly db: PrismaClient,
private readonly injector: ModuleRef
) {}

async onModuleInit() {
const actions = await this.collectActions();

for (const action of actions) {
await this.runAction(action);
}
}

private async collectActions(): Promise<Action[]> {
const folder = join(fileURLToPath(import.meta.url), '../actions');

const actionFiles = readdirSync(folder)
.filter(desc =>
desc.endsWith(import.meta.url.endsWith('.ts') ? '.ts' : '.js')
)
.map(desc => join(folder, desc));

actionFiles.sort((a, b) => a.localeCompare(b));

const actions: Action[] = (
await Promise.all(
actionFiles.map(async file => {
const path = pathToFileURL(file);
return import(path.href).then(mod => {
const { name, run } = mod[Object.keys(mod)[0]];
if (!name || !run || typeof run !== 'function') {
this.logger.warn(`Uncompleted action: ${path.pathname}`);
return null;
}
return { file, name, run };
});
})
)
).filter((v): v is Action => !!v);

return actions;
}

private async runAction(action: Action) {
this.logger.log(`Running ${action.name}...`);

try {
await action.run(this.db, this.injector);
} catch (e) {
this.logger.error(`Failed to run action ${action.name}: `, e);
process.exit(1);
}
}
}

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

This file was deleted.

Loading
Loading