Skip to content

Commit

Permalink
fix: fix issue where app was loading twice when in dev/dual mode
Browse files Browse the repository at this point in the history
  • Loading branch information
brent-hoover committed Jun 17, 2024
1 parent 7376a61 commit 745afe9
Show file tree
Hide file tree
Showing 7 changed files with 58 additions and 45 deletions.
32 changes: 10 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,21 @@
import 'reflect-metadata';
import express, { type Application, type Request, type Response, type NextFunction } from 'express';
import { ApolloServer } from 'apollo-server-express';
import { connectToDatabase } from './config/database';
import env from './config/config';
import logger from './config/logger';
import { initEnforcer, getEnforcer } from './rbac';
import { authenticate } from './middleware/auth';
import PluginLoader from './plugins/plugin-loader';
import { isIntrospectionQuery } from './utils/introspection-check';
import { shouldBypassAuth } from './utils/should-bypass-auth';
import { bootstrap } from './plugins/auth-plugin/bootstrap';
import sanitizeLog from './sanitize-log';
import { initializeSharedResources } from './shared';
import { startWorker } from './worker';
import { getEnforcer } from './rbac.ts';
import type PluginLoader from './plugins/plugin-loader.ts';

const loggerCtx = { context: 'index' };

async function startServer() {
async function startServer(pluginLoader: PluginLoader) {
try {
await connectToDatabase();
await initEnforcer(); // Initialize Casbin
await bootstrap(); // Bootstrap the application with a superuser

const pluginLoader = new PluginLoader();
pluginLoader.loadPlugins();

// Register models before initializing plugins
pluginLoader.registerModels();

// Initialize plugins (extend models and resolvers)
pluginLoader.initializePlugins();

const schema = await pluginLoader.createSchema();

const server = new ApolloServer({
Expand Down Expand Up @@ -97,16 +83,18 @@ async function startServer() {
}

async function startApp() {
const pluginLoader = await initializeSharedResources();

switch (env.MODE) {
case 'server':
await startServer();
await startServer(pluginLoader);
break;
case 'worker':
await startWorker();
await startWorker(pluginLoader);
break;
case 'dev':
await startServer();
await startWorker();
await startServer(pluginLoader);
await startWorker(pluginLoader, true); // Pass a flag to indicate dev mode
break;
default:
logger.error('Unknown mode specified. Please set MODE to "server", "worker", or "dev".', loggerCtx);
Expand Down
5 changes: 4 additions & 1 deletion src/plugins/auth-plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { AuthResolver } from './resolvers/auth-resolver';
import type { Plugin } from '../plugin-interface';
import FunctionRegistry from '../function-registry';
import { type GlobalContext } from '../global-context';
import logger from '../../config/logger.ts';

const loggerCtx = { context: 'auth-plugin/register' };

const authPlugin: Plugin = {
name: 'auth-plugin',
Expand All @@ -13,7 +16,7 @@ const authPlugin: Plugin = {

// Perform any additional registration if necessary
const functionRegistry = FunctionRegistry.getInstance();
functionRegistry.registerFunction('user', () => console.log('User function called'));
functionRegistry.registerFunction('user', () => logger.debug('User function called', loggerCtx));
},
};

Expand Down
8 changes: 6 additions & 2 deletions src/plugins/sample-plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,12 @@ import { SampleResolver } from './resolvers/sample-resolver';
import { SampleService } from './services/sample-service';
import KafkaEventService from '../../event/kafka-event-service';
import { Queue, Job } from 'bullmq';
import logger from '../../config/logger.ts';

const loggerCtx = { context: 'sample-plugin/index' };

const sampleJobProcessor = async (job: Job) => {
console.log(`Processing job ${job.id}`);
logger.info(`Processing job ${job.id}`, loggerCtx);
// Add job processing logic here
};

Expand Down Expand Up @@ -44,7 +47,8 @@ export default {

// Set up event handlers using the centralized event service
eventService.subscribeToEvent('sampleCreated', (sample) => {
console.log('Sample created:', sample);
logger.debug('Received sampleCreated event:', sample)
logger.info(`Sample created: ${sample}`, loggerCtx);
// Additional handling logic here
});

Expand Down
2 changes: 2 additions & 0 deletions src/plugins/sample-plugin/services/sample-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Service } from 'typedi';
import { Sample, SampleModel } from '../models/sample';
import KafkaEventService from '../../../event/kafka-event-service';
import { Queue } from 'bullmq';
import logger from '../../../config/logger.ts';

@Service()
export class SampleService {
Expand All @@ -17,6 +18,7 @@ export class SampleService {
async createSample(name: string): Promise<Sample> {
const sample = new SampleModel({ name });
const savedSample = await sample.save();
logger.debug('emitting sampleCreated event:', savedSample);
await this.eventService.emitEvent('sampleCreated', savedSample); // Emit event using the centralized service

// Add job to the sampleQueue
Expand Down
25 changes: 25 additions & 0 deletions src/shared.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// src/shared.ts
import { connectToDatabase } from './config/database';
import { initEnforcer } from './rbac';
import { bootstrap } from './plugins/auth-plugin/bootstrap';
import PluginLoader from './plugins/plugin-loader';
import logger from './config/logger';

const loggerCtx = { context: 'shared' };

export async function initializeSharedResources() {
await connectToDatabase();
await initEnforcer(); // Initialize Casbin
await bootstrap(); // Bootstrap the application with a superuser

const pluginLoader = new PluginLoader();
pluginLoader.loadPlugins();

// Register models before initializing plugins
pluginLoader.registerModels();

// Initialize plugins (extend models and resolvers)
pluginLoader.initializePlugins();

return pluginLoader;
}
25 changes: 7 additions & 18 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,16 @@
import { connectToDatabase } from './config/database';

import logger from './config/logger';
import { initEnforcer } from './rbac';
import { bootstrap } from './plugins/auth-plugin/bootstrap';
import PluginLoader from './plugins/plugin-loader';
import { initializeSharedResources } from './shared';
import type PluginLoader from './plugins/plugin-loader';

const loggerCtx = { context: 'worker' };

export async function startWorker() {
export async function startWorker(pluginLoader: PluginLoader, isDevMode = false) {
try {
await connectToDatabase();
await initEnforcer(); // Initialize Casbin
await bootstrap(); // Bootstrap the application with a superuser

const pluginLoader = new PluginLoader();
pluginLoader.loadPlugins();

// Register models before initializing plugins
pluginLoader.registerModels();

// Initialize plugins (extend models and resolvers)
pluginLoader.initializePlugins();
if (!isDevMode) {
pluginLoader = await initializeSharedResources();
}

// Initialize queues
pluginLoader.initializeQueues();

logger.info('Worker started and ready to process jobs', loggerCtx);
Expand Down
6 changes: 4 additions & 2 deletions test/test-db-setup.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import logger from '../src/config/logger';

let mongoServer: MongoMemoryServer;
const loggerCtx = { context: 'test-db-setup' };

async function connectDB() {
mongoServer = await MongoMemoryServer.create();
Expand All @@ -11,13 +13,13 @@ async function connectDB() {
serverSelectionTimeoutMS: 5000, // 5 seconds timeout for MongoDB server selection
});
mongoose.set('bufferCommands', false);
console.log('MongoDB connected');
logger.info('MongoDB connected');
}

async function closeDB() {
await mongoose.disconnect();
await mongoServer.stop();
console.log('MongoDB disconnected');
logger.info('MongoDB disconnected', loggerCtx);
}

export { connectDB, closeDB };

0 comments on commit 745afe9

Please sign in to comment.