Skip to content

Commit

Permalink
chore: cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
brent-hoover committed Jun 16, 2024
1 parent d45d956 commit ee404b1
Show file tree
Hide file tree
Showing 8 changed files with 17 additions and 53 deletions.
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { shouldBypassAuth } from './utils/should-bypass-auth';
import { bootstrap } from './plugins/auth-plugin/bootstrap';
import sanitizeLog from './sanitize-log';

const loggerCtx = 'index';
const loggerCtx = { context: 'index' };

async function startServer() {
try {
Expand Down Expand Up @@ -88,10 +88,10 @@ async function startServer() {

const port = env.PORT;
app.listen(port, () => {
logger.info(`Server is running at http://localhost:${port}${server.graphqlPath}`, { context: 'server' });
logger.info(`Server is running at http://localhost:${port}${server.graphqlPath}`, { context: 'index' });
});
} catch (error) {
logger.error('Failed to start server:', error);
logger.error('Failed to start server:', error, loggerCtx);
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Request, Response, NextFunction } from 'express';
import jwt, { type JwtPayload } from 'jsonwebtoken';
import logger from '../config/logger.ts';

const loggerCtx = 'auth-middleware';
const loggerCtx = { context: 'auth-middleware' };

export const authenticate = (req: Request, res: Response, next: NextFunction) => {
const authHeader = req.headers.authorization;
Expand All @@ -13,7 +13,7 @@ export const authenticate = (req: Request, res: Response, next: NextFunction) =>

const token = authHeader.split(' ')[1];
if (!token) {
logger.error('Token missing');
logger.error('Token missing', loggerCtx);
return res.status(401).send('Token missing');
}

Expand All @@ -27,7 +27,7 @@ export const authenticate = (req: Request, res: Response, next: NextFunction) =>
req.user = decoded; // Attach the user to the request object
next();
} catch (err) {
console.log('Invalid token:', err);
logger.error('Invalid token:', err, loggerCtx);
return res.status(401).send('Invalid token');
}
};
9 changes: 6 additions & 3 deletions src/plugins/auth-plugin/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import { UserModel } from './models/user';
import { getEnforcer } from '../../rbac';
import logger from '../../config/logger';

const loggerCtx = { context: 'auth-plugin-bootstrap' };
const email = '[email protected]';

export const bootstrap = async () => {
const userCount = await UserModel.countDocuments({});
if (userCount === 0) {
const superuser = new UserModel({
email: '[email protected]',
email: email,
password: await bcrypt.hash('superpassword', 10), // Use a secure password
name: 'Super User',
role: 'superadmin',
Expand All @@ -33,8 +36,8 @@ export const bootstrap = async () => {
}
}

logger.info('Superuser created with email: [email protected]');
logger.info(`Superuser created with email: ${email}`);
} else {
logger.info('Users already exist. No superuser created.');
logger.info('Users already exist. No superuser created.', loggerCtx);
}
};
6 changes: 1 addition & 5 deletions src/plugins/cart-plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,16 @@ import { CartResolver } from './resolvers/cart-resolver';

export default {
name: 'cart-plugin',
type: 'ecommerce',
type: 'cart',
resolvers: [CartResolver],
register(container: typeof Container, context: GlobalContext) {
const CartModel = getModelForClass(Cart);
context.models['Cart'] = { schema: CartModel.schema, model: CartModel };
container.set('CartModel', CartModel);
container.set(CartResolver, new CartResolver()); // Register CartResolver explicitly
context.extendResolvers('Cart', [CartResolver]);

// Logging the methods of CartResolver
const resolverMethods = Object.getOwnPropertyNames(CartResolver.prototype).filter(
(method) => method !== 'constructor',
);
console.log('Registered Cart resolvers:', context.resolvers['Cart']);
console.log('Methods in CartResolver:', resolverMethods);
},
};
1 change: 0 additions & 1 deletion src/plugins/cart-plugin/resolvers/inputs/item-input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,4 @@ export class ItemInput {
@Field(() => Float)
@prop({ required: true })
public price!: number;

}
5 changes: 1 addition & 4 deletions src/plugins/discount-plugin/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { Schema } from 'mongoose';
import { type GlobalContext } from '../global-context';
import logger from '../../config/logger';

export default {
name: 'discount-plugin',
type: 'ecommerce',
type: 'cart',
initialize(context: GlobalContext) {
context.extendModel('Cart', (schema: Schema) => {
schema.add({
discount: { type: Number, required: false },
});
logger.info('Extended Cart model with discount');
});

context.wrapResolver(
Expand All @@ -25,7 +23,6 @@ export default {
return result;
},
);
logger.info('Wrapped addItemToCart resolver');
},
};

Expand Down
30 changes: 2 additions & 28 deletions src/plugins/plugin-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import { type GlobalContext } from './global-context';
import { type Plugin } from './plugin-interface';
import pluginsList from './plugins-list';

const loggerCtx = 'plugin-loader';
const loggerCtx = { context: 'plugin-loader' };

class PluginLoader {
private plugins: Plugin[] = [];
private context: GlobalContext = {
context: GlobalContext = {
models: {},
resolvers: {},
extendModel: (name: string, extension: (schema: Schema) => void) => {
Expand Down Expand Up @@ -45,8 +45,6 @@ class PluginLoader {

loadPlugins() {
const pluginsDir = join(__dirname, '.');

// Explicitly load cart-plugin and discount-plugin first
pluginsList.forEach((pluginName) => {
const pluginPath = join(pluginsDir, pluginName);
if (statSync(pluginPath).isDirectory()) {
Expand All @@ -66,29 +64,6 @@ class PluginLoader {
}
}
});

// Load other plugins in default order
const otherPluginDirs = readdirSync(pluginsDir).filter((file) => {
const stat = statSync(join(pluginsDir, file));
return stat.isDirectory() && !specificPlugins.includes(file);
});

otherPluginDirs.forEach((dir) => {
try {
const plugin: Plugin = require(`./${dir}`).default;
if (!plugin) {
throw new Error(`Plugin in directory ${dir} does not have a default export`);
}
logger.info(`Loaded plugin: ${plugin.name} of type ${plugin.type}`, loggerCtx);
this.plugins.push(plugin);
if (plugin.register) {
plugin.register(Container, this.context);
logger.info(`Registered plugin: ${plugin.name}`, loggerCtx);
}
} catch (error) {
logger.error(`Failed to load plugin from directory ${dir}:`, error);
}
});
}

initializePlugins() {
Expand All @@ -110,7 +85,6 @@ class PluginLoader {
throw new Error('No resolvers found. Please ensure at least one resolver is provided.');
}


try {
return await buildSchema({
resolvers: allResolvers as unknown as NonEmptyArray<Function>,
Expand Down
7 changes: 1 addition & 6 deletions src/plugins/plugins-list.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,2 @@
let pluginList;
export default pluginList = [
'auth-plugin',
'cart-plugin',
'discount-plugin',
'sample-plugin'
]
export default pluginList = ['auth-plugin', 'cart-plugin', 'discount-plugin', 'sample-plugin'];

0 comments on commit ee404b1

Please sign in to comment.