commit 2 refactor

This commit is contained in:
Boki 2026-10-20 14:35:45 -04:00
parent 588f666943
commit 32e43c9243
310 changed files with 33318 additions and 31189 deletions

View file

@ -1,6 +1,20 @@
import type { Logger } from '@stock-bot/logger';
import type { Document, OptionalUnlessRequiredId } from 'mongodb';
import type {
AggregateOptions,
BulkWriteOptions,
CountDocumentsOptions,
CreateCollectionOptions,
CreateIndexesOptions,
DeleteOptions,
Document,
DropIndexesOptions,
Filter,
FindOptions,
IndexSpecification,
OptionalUnlessRequiredId,
UpdateOptions,
} from 'mongodb';
import { Collection, Db, MongoClient } from 'mongodb';
import type { Logger } from '@stock-bot/logger';
import type {
ConnectionEvents,
DocumentBase,
@ -312,15 +326,18 @@ export class MongoDBClient {
}
}
this.logger.debug(`Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`, {
database: dbName,
collection: collectionName,
totalRecords: documents.length,
inserted: totalInserted,
updated: totalUpdated,
errors: errors.length,
uniqueKeys: keyFields,
});
this.logger.debug(
`Batch upsert completed [${collectionName}-${documents.length}][${operationId}]`,
{
database: dbName,
collection: collectionName,
totalRecords: documents.length,
inserted: totalInserted,
updated: totalUpdated,
errors: errors.length,
uniqueKeys: keyFields,
}
);
return { insertedCount: totalInserted, updatedCount: totalUpdated, errors };
}
@ -366,22 +383,25 @@ export class MongoDBClient {
/**
* Insert multiple documents
*/
async insertMany<T = any>(
async insertMany<T extends Document = Document>(
collectionName: string,
documents: T[],
options?: any,
options?: BulkWriteOptions,
dbName?: string
): Promise<any> {
) {
const collection = this.getCollection(collectionName, dbName);
const now = new Date();
const docsWithTimestamps = documents.map(doc => ({
...doc,
created_at: (doc as any).created_at || now,
created_at: doc.created_at || now,
updated_at: now,
}));
const result = await collection.insertMany(docsWithTimestamps as any, options);
const result = await collection.insertMany(
docsWithTimestamps as OptionalUnlessRequiredId<Document>[],
options
);
return {
insertedCount: result.insertedCount,
insertedIds: result.insertedIds,
@ -391,13 +411,13 @@ export class MongoDBClient {
/**
* Find multiple documents
*/
async find<T = any>(
async find<T extends Document = Document>(
collectionName: string,
filter: any = {},
options?: any,
filter: Filter<Document> = {},
options?: FindOptions,
dbName?: string
): Promise<T[]> {
const collection = this.getCollection(collectionName, dbName);
const collection = this.getCollection<T>(collectionName, dbName);
const cursor = collection.find(filter, options);
return (await cursor.toArray()) as T[];
}
@ -405,13 +425,13 @@ export class MongoDBClient {
/**
* Find a single document
*/
async findOne<T = any>(
async findOne<T extends Document = Document>(
collectionName: string,
filter: any,
options?: any,
filter: Filter<Document>,
options?: FindOptions,
dbName?: string
): Promise<T | null> {
const collection = this.getCollection(collectionName, dbName);
const collection = this.getCollection<T>(collectionName, dbName);
const result = await collection.findOne(filter, options);
return result as T | null;
}
@ -421,11 +441,11 @@ export class MongoDBClient {
*/
async updateOne(
collectionName: string,
filter: any,
update: any,
options?: any,
filter: Filter<Document>,
update: Document,
options?: UpdateOptions,
dbName?: string
): Promise<any> {
) {
const collection = this.getCollection(collectionName, dbName);
// Add updated_at timestamp
@ -449,11 +469,11 @@ export class MongoDBClient {
*/
async updateMany(
collectionName: string,
filter: any,
update: any,
options?: any,
filter: Filter<Document>,
update: Document,
options?: UpdateOptions,
dbName?: string
): Promise<any> {
) {
const collection = this.getCollection(collectionName, dbName);
// Add updated_at timestamp
@ -477,10 +497,10 @@ export class MongoDBClient {
*/
async deleteOne(
collectionName: string,
filter: any,
options?: any,
filter: Filter<Document>,
options?: DeleteOptions,
dbName?: string
): Promise<any> {
) {
const collection = this.getCollection(collectionName, dbName);
const result = await collection.deleteOne(filter, options);
return {
@ -493,10 +513,10 @@ export class MongoDBClient {
*/
async deleteMany(
collectionName: string,
filter: any,
options?: any,
filter: Filter<Document>,
options?: DeleteOptions,
dbName?: string
): Promise<any> {
) {
const collection = this.getCollection(collectionName, dbName);
const result = await collection.deleteMany(filter, options);
return {
@ -509,8 +529,8 @@ export class MongoDBClient {
*/
async countDocuments(
collectionName: string,
filter: any = {},
options?: any,
filter: Filter<Document> = {},
options?: CountDocumentsOptions,
dbName?: string
): Promise<number> {
const collection = this.getCollection(collectionName, dbName);
@ -520,10 +540,10 @@ export class MongoDBClient {
/**
* Perform aggregation operations
*/
async aggregate<T = any>(
async aggregate<T extends Document = Document>(
collectionName: string,
pipeline: any[],
options?: any,
pipeline: Document[],
options?: AggregateOptions,
dbName?: string
): Promise<T[]> {
const collection = this.getCollection(collectionName, dbName);
@ -536,8 +556,8 @@ export class MongoDBClient {
*/
async createIndex(
collectionName: string,
indexSpec: any,
options?: any,
indexSpec: IndexSpecification,
options?: CreateIndexesOptions,
dbName?: string
): Promise<string> {
const collection = this.getCollection(collectionName, dbName);
@ -550,7 +570,7 @@ export class MongoDBClient {
async dropIndex(
collectionName: string,
indexName: string,
options?: any,
options?: DropIndexesOptions,
dbName?: string
): Promise<void> {
const collection = this.getCollection(collectionName, dbName);
@ -560,7 +580,7 @@ export class MongoDBClient {
/**
* List all indexes on a collection
*/
async listIndexes(collectionName: string, dbName?: string): Promise<any[]> {
async listIndexes(collectionName: string, dbName?: string): Promise<Document[]> {
const collection = this.getCollection(collectionName, dbName);
const cursor = collection.listIndexes();
return await cursor.toArray();
@ -576,7 +596,11 @@ export class MongoDBClient {
/**
* Create a new collection
*/
async createCollection(collectionName: string, options?: any, dbName?: string): Promise<void> {
async createCollection(
collectionName: string,
options?: CreateCollectionOptions,
dbName?: string
): Promise<void> {
const db = this.getDatabase(dbName);
await db.createCollection(collectionName, options);
}
@ -592,7 +616,7 @@ export class MongoDBClient {
/**
* List all collections in a database
*/
async listCollections(filter: any = {}, dbName?: string): Promise<any[]> {
async listCollections(filter: Filter<Document> = {}, dbName?: string): Promise<Document[]> {
const db = this.getDatabase(dbName);
const collections = await db.listCollections(filter).toArray();
return collections;

View file

@ -1,165 +0,0 @@
/**
* Simple MongoDB client implementation for testing
*/
export class SimpleMongoDBClient {
private collections = new Map<string, any[]>();
private connected = false;
constructor(private config: any) {}
async connect(): Promise<void> {
this.connected = true;
}
async disconnect(): Promise<void> {
this.connected = false;
}
async find(collection: string, filter: any = {}): Promise<any[]> {
if (!this.connected) {
await this.connect();
}
const docs = this.collections.get(collection) || [];
// Simple filter matching
if (Object.keys(filter).length === 0) {
return docs;
}
return docs.filter(doc => {
for (const [key, value] of Object.entries(filter)) {
if (doc[key] !== value) {
return false;
}
}
return true;
});
}
async findOne(collection: string, filter: any = {}): Promise<any | null> {
const results = await this.find(collection, filter);
return results[0] || null;
}
async insert(collection: string, doc: any): Promise<void> {
if (!this.connected) {
await this.connect();
}
const docs = this.collections.get(collection) || [];
docs.push({ ...doc, _id: Math.random().toString(36) });
this.collections.set(collection, docs);
}
async insertMany(collection: string, documents: any[]): Promise<void> {
for (const doc of documents) {
await this.insert(collection, doc);
}
}
async update(collection: string, filter: any, update: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const docs = await this.find(collection, filter);
if (docs.length === 0) {
return 0;
}
const doc = docs[0];
if (update.$set) {
Object.assign(doc, update.$set);
}
return 1;
}
async updateMany(collection: string, filter: any, update: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const docs = await this.find(collection, filter);
for (const doc of docs) {
if (update.$set) {
Object.assign(doc, update.$set);
}
}
return docs.length;
}
async delete(collection: string, filter: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const allDocs = this.collections.get(collection) || [];
const toDelete = await this.find(collection, filter);
if (toDelete.length === 0) {
return 0;
}
const remaining = allDocs.filter(doc => !toDelete.includes(doc));
this.collections.set(collection, remaining);
return 1;
}
async deleteMany(collection: string, filter: any): Promise<number> {
if (!this.connected) {
await this.connect();
}
const allDocs = this.collections.get(collection) || [];
const toDelete = await this.find(collection, filter);
const remaining = allDocs.filter(doc => !toDelete.includes(doc));
this.collections.set(collection, remaining);
return toDelete.length;
}
async batchUpsert(collection: string, documents: any[], uniqueKeys: string[]): Promise<void> {
if (!this.connected) {
await this.connect();
}
for (const doc of documents) {
const filter: any = {};
for (const key of uniqueKeys) {
filter[key] = doc[key];
}
const existing = await this.findOne(collection, filter);
if (existing) {
await this.update(collection, filter, { $set: doc });
} else {
await this.insert(collection, doc);
}
}
}
async count(collection: string, filter: any = {}): Promise<number> {
const docs = await this.find(collection, filter);
return docs.length;
}
async createIndex(collection: string, index: any, options?: any): Promise<void> {
// No-op for simple implementation
}
async healthCheck(): Promise<{ status: string; isConnected: boolean; error?: string }> {
try {
return {
status: this.connected ? 'healthy' : 'unhealthy',
isConnected: this.connected,
};
} catch (error: any) {
return {
status: 'unhealthy',
isConnected: false,
error: error.message,
};
}
}
}