Skip to content

Commit

Permalink
refactor: mongoose connection related code
Browse files Browse the repository at this point in the history
  • Loading branch information
dulguun0225 committed Feb 28, 2024
1 parent a096ce9 commit 34b238a
Show file tree
Hide file tree
Showing 79 changed files with 68 additions and 399 deletions.
15 changes: 9 additions & 6 deletions packages/api-utils/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { isEnabled } from '@erxes/api-utils/src/serviceDiscovery';
import * as messageBroker from './messageBroker';
import type { InterMessage } from './messageBroker';
import { coreModelOrganizations, getCoreConnection } from './saas/saas';
import { connect } from './mongo-connection';

export const getEnv = ({
name,
Expand Down Expand Up @@ -367,23 +368,25 @@ export const createGenerateModels = <IModels>(
) => {
const VERSION = getEnv({ name: 'VERSION' });

connect();

if (VERSION && VERSION !== 'saas') {
let models: IModels | null = null;
return async (hostnameOrSubdomain: string): Promise<IModels> => {
return async function genereteModels(
hostnameOrSubdomain: string,
): Promise<IModels> {
if (models) {
return models;
}

const MONGO_URL = getEnv({ name: 'MONGO_URL' });

await mongoose.connect(MONGO_URL, connectionOptions);

models = await loadClasses(mongoose.connection, hostnameOrSubdomain);

return models;
};
} else {
return async (hostnameOrSubdomain: string = ''): Promise<IModels> => {
return async function genereteModels(
hostnameOrSubdomain: string = '',
): Promise<IModels> {
let subdomain: string = hostnameOrSubdomain;

// means hostname
Expand Down
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
import * as dotenv from 'dotenv';
import * as mongoose from 'mongoose';
import { debugInfo, debugError } from './debuggers';
import { getEnv } from './utils';

dotenv.config();

// mongoose.Promise = global.Promise;

const MONGO_URL = getEnv({ name: 'MONGO_URL' });
const { MONGO_URL } = process.env;

export const connectionOptions: mongoose.ConnectionOptions = {
useNewUrlParser: true,
useCreateIndex: true,
// autoReconnect: true,
family: 4,
useFindAndModify: false
useFindAndModify: false,
};

mongoose.connection
Expand All @@ -26,16 +23,20 @@ mongoose.connection

process.exit(1);
})
.on('error', error => {
.on('error', (error) => {
debugError(`Database connection error: ${MONGO_URL} ${error}`);

process.exit(1);
});

export const connect = (URL?: string) => {
return mongoose.connect(URL || MONGO_URL, connectionOptions);
};
export async function connect(): Promise<mongoose.Connection> {
if (!MONGO_URL) {
throw new Error('MONGO_URL is not defined');
}
await mongoose.connect(MONGO_URL, connectionOptions);
return mongoose.connection;
}

export function disconnect() {
export async function disconnect(): Promise<void> {
return mongoose.connection.close();
}
8 changes: 4 additions & 4 deletions packages/api-utils/src/serviceDiscovery.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as dotenv from 'dotenv';
import redis from './redis';
import { getEnv } from './core';
dotenv.config();

const { NODE_ENV, LOAD_BALANCER_ADDRESS, ENABLED_SERVICES_JSON } = process.env;
const { NODE_ENV, LOAD_BALANCER_ADDRESS, ENABLED_SERVICES_JSON, MONGO_URL } =
process.env;

const isDev = NODE_ENV === 'development';

Expand Down Expand Up @@ -55,14 +57,12 @@ export const getService = async (
export const join = async ({
name,
port,
dbConnectionString,
hasSubscriptions = false,
importExportTypes,
meta,
}: {
name: string;
port: string;
dbConnectionString: string;
hasSubscriptions?: boolean;
importExportTypes?: any;
meta?: any;
Expand All @@ -71,7 +71,7 @@ export const join = async ({
keyForConfig(name),

JSON.stringify({
dbConnectionString,
dbConnectionString: MONGO_URL,
hasSubscriptions,
importExportTypes,
meta,
Expand Down
9 changes: 0 additions & 9 deletions packages/api-utils/src/start-plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHt
import * as cookieParser from 'cookie-parser';

import * as http from 'http';

import { connect } from './connection';
import { debugInfo, debugError, initDebuggers } from './debuggers';
import { init as initBroker } from '@erxes/api-utils/src/messageBroker';
import { logConsumers } from '@erxes/api-utils/src/logUtils';
Expand Down Expand Up @@ -251,11 +249,6 @@ export async function startPlugin(configs: any): Promise<express.Express> {
`🚀 ${configs.name} graphql api ready at http://localhost:${PORT}/graphql`,
);

const mongoUrl = MONGO_URL || '';

// connect to mongo database
const db = await connect(mongoUrl);

await initBroker(configs.reconnectRMQ);

if (configs.meta) {
Expand Down Expand Up @@ -633,14 +626,12 @@ export async function startPlugin(configs: any): Promise<express.Express> {
await join({
name: configs.name,
port: PORT || '',
dbConnectionString: mongoUrl,
hasSubscriptions: configs.hasSubscriptions,
importExportTypes: configs.importExportTypes,
meta: configs.meta,
});

configs.onServerInit({
db,
debug: {
info: debugInfo,
error: debugError,
Expand Down
7 changes: 3 additions & 4 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,9 @@ httpServer.listen(PORT, async () => {

await initBroker();

if (VERSION && VERSION === 'saas') {
await mongoose.connect(MONGO_URL, connectionOptions);
}
// if (VERSION && VERSION === 'saas') {
// await mongoose.connect(MONGO_URL, connectionOptions);
// }

init()
.then(() => {
Expand All @@ -333,7 +333,6 @@ httpServer.listen(PORT, async () => {
await join({
name: 'core',
port: PORT,
dbConnectionString: MONGO_URL,
hasSubscriptions: false,
meta: {
logs: { providesActivityLog: true, consumers: logs },
Expand Down
23 changes: 3 additions & 20 deletions packages/gateway/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,28 +23,11 @@ import {
} from './subscription';
import { applyInspectorEndpoints } from '@erxes/api-utils/src/inspect';
import app from '@erxes/api-utils/src/app';
import * as mongoose from 'mongoose';
import { connectionOptions } from '@erxes/api-utils/src/core';

const {
DOMAIN,
WIDGETS_DOMAIN,
CLIENT_PORTAL_DOMAINS,
ALLOWED_ORIGINS,
PORT,
MONGO_URL,
VERSION,
} = process.env;

if (!MONGO_URL) {
throw new Error('MONGO_URL is not defined');
}

(async () => {
if (VERSION && VERSION === 'saas') {
await mongoose.connect(MONGO_URL, connectionOptions);
}
const { DOMAIN, WIDGETS_DOMAIN, CLIENT_PORTAL_DOMAINS, ALLOWED_ORIGINS, PORT } =
process.env;

(async () => {
app.use((req, _res, next) => {
// this is important for security reasons
delete req.headers['user'];
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-assets-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import internalNotes from './internalNotes';
import logUtils from './logUtils';
import * as permissions from './permissions';

export let mainDb;
export let debug;

export default {
Expand Down Expand Up @@ -45,8 +44,6 @@ export default {
},

onServerInit: async (options) => {
mainDb = options.db;

initBroker();

debug = options.debug;
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-automations-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import cronjobs from './cronjobs/automations';
import tags from './tags';
import logs from './logUtils';

export let mainDb;
export let debug;

export default {
Expand Down Expand Up @@ -37,8 +36,6 @@ export default {
return context;
},
onServerInit: async (options) => {
mainDb = options.db;

console.log('on server init .....');

initBroker();
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-block-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { debugInfo } from '@erxes/api-utils/src/debuggers';
import app from '@erxes/api-utils/src/app';
// import { getBalance, sendSms, updateBalance } from './utils';

export let mainDb;
export let debug;

export default {
Expand All @@ -32,8 +31,6 @@ export default {
},

onServerInit: async (options) => {
mainDb = options.db;

app.post(
'/tdb/receive',
routeErrorHandling(async (req, res) => {
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-calls-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import webhookReceiver from './webhook';
import { getSubdomain } from '@erxes/api-utils/src/core';
import { generateModels } from './connectionResolver';

export let mainDb;
export let debug;

export default {
Expand Down Expand Up @@ -46,8 +45,6 @@ export default {
},

onServerInit: async (options) => {
mainDb = options.db;

initBroker();

debug = options.debug;
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-cards-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import reports from './reports';
import app from '@erxes/api-utils/src/app';

import { NOTIFICATION_MODULES } from './constants';
export let mainDb;
export let debug;

export default {
Expand Down Expand Up @@ -82,8 +81,6 @@ export default {
},
middlewares: [(serverTiming as any)()],
onServerInit: async (options) => {
mainDb = options.db;

app.get(
'/file-export',
routeErrorHandling(async (req: any, res) => {
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-cars-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import segments from './segments';
import tags from './tags';

export let debug;
export let mainDb;

export default {
name: 'cars',
Expand All @@ -31,8 +30,6 @@ export default {
},

onServerInit: async (options) => {
mainDb = options.db;

initBroker();

debug = options.debug;
Expand Down
1 change: 0 additions & 1 deletion packages/plugin-cars-api/src/connectionResolver.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as mongoose from 'mongoose';
import { mainDb } from './configs';
import { IContext as IMainContext } from '@erxes/api-utils/src';
import { ICarCategoryDocument, ICarDocument } from './models/definitions/cars';
import {
Expand Down
4 changes: 0 additions & 4 deletions packages/plugin-chats-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import { NOTIFICATION_MODULES } from './constants';

export let debug;

export let mainDb;

export default {
name: 'chats',
permissions,
Expand Down Expand Up @@ -37,8 +35,6 @@ export default {
},

onServerInit: async (options) => {
mainDb = options.db;

initBroker();

debug = options.debug;
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-clientportal-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { initBroker } from './messageBroker';
import cpUserMiddleware from './middlewares/cpUserMiddleware';
import * as permissions from './permissions';

export let mainDb;
export let debug;

export default {
Expand Down Expand Up @@ -59,8 +58,6 @@ export default {
},
middlewares: [cookieParser(), cpUserMiddleware],
onServerInit: async (options) => {
mainDb = options.db;

initBroker();

debug = options.debug;
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-contacts-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import documents from './documents';
import { EMAIL_VALIDATION_STATUSES, NOTIFICATION_MODULES } from './constants';
import app from '@erxes/api-utils/src/app';

export let mainDb;
export let debug;

export default {
Expand Down Expand Up @@ -71,8 +70,6 @@ export default {
},

onServerInit: async (options) => {
mainDb = options.db;

app.get(
'/file-export',
routeErrorHandling(async (req: any, res) => {
Expand Down
3 changes: 0 additions & 3 deletions packages/plugin-dailyco-api/src/configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import resolvers from './graphql/resolvers';
import { initBroker } from './messageBroker';
import { getSubdomain } from '@erxes/api-utils/src/core';

export let mainDb;
export let debug;

export default {
Expand All @@ -21,8 +20,6 @@ export default {
},

onServerInit: async (options) => {
mainDb = options.db;

debug = options.debug;

initBroker();
Expand Down

0 comments on commit 34b238a

Please sign in to comment.