<commit_before>import { MongoConnection } from '@mikro-orm/mongodb';
import { MongoClient } from 'mongodb';

let client: MongoClient | null = null;

export class MongoSharedConnection extends MongoConnection {
	async connect(): Promise<void> {
		if (client == null) {
			client = await MongoClient.connect(this.config.getClientUrl(), this.getConnectionOptions());
		}
		this.client = client;
		this.db = this.client.db(this.config.get('dbName'));
	}

	async close(force?: boolean): Promise<void> {
		if (client) {
			await client?.close(force);
			client = null;
		}
	}
}<commit_msg>close shared mongo client after last conn close<commit_after>import { MongoConnection } from '@mikro-orm/mongodb';
import { MongoClient } from 'mongodb';

// the shared mongo client
let sharedClient: MongoClient | undefined;

// keep a list of references to all open mikro-orm mongo connections
const connections: Array<MongoSharedConnection> = [];

export class MongoSharedConnection extends MongoConnection {
	async connect(): Promise<void> {
		if (!sharedClient) {
			sharedClient = await MongoClient.connect(this.config.getClientUrl(), this.getConnectionOptions());
		}
		connections.push(this);
		this.client = sharedClient;
		this.db = this.client.db(this.config.get('dbName'));
	}

	async close(force?: boolean): Promise<void> {
		// remove from list of references
		connections.splice(connections.indexOf(this), 1);
		if (connections.length === 0) {
			// close client when there are no more references
			await sharedClient?.close(force);
			sharedClient = undefined;
		}
	}
}
{'fraction_non_alphanumeric': 0.12627551020408162, 'fraction_numerical': 0.0012755102040816326, 'mean_word_length': 4.705454545454545, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5529597', 'n_tokens_mistral': 509, 'n_tokens_neox': 456, 'n_words': 124}