1
0
forked from Yara724/api

Fixed smsApiKey index error and err handling in ESG

This commit is contained in:
SepehrYahyaee
2026-06-21 12:18:08 +03:30
parent 570fa865de
commit d0e7694374
6 changed files with 56 additions and 28 deletions

View File

@@ -1,15 +1,49 @@
import { Injectable } from "@nestjs/common";
import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { FilterQuery, Model, UpdateQuery } from "mongoose";
import { ClientModel, ClientDocument } from "../schema/client.schema";
@Injectable()
export class ClientDbService {
export class ClientDbService implements OnModuleInit {
private readonly logger = new Logger(ClientDbService.name);
constructor(
@InjectModel(ClientModel.name)
private readonly clientModel: Model<ClientModel>,
) {}
async onModuleInit(): Promise<void> {
await this.dropLegacyPropertyUniqueIndex();
}
/**
* `property` was once declared `unique: true` in the schema. Production keeps
* `autoIndex: false`, so the stale unique index remained and rejected a second
* client with a missing/null SMS key (E11000 duplicate key).
*/
private async dropLegacyPropertyUniqueIndex(): Promise<void> {
try {
const indexes = await this.clientModel.collection.indexes();
for (const index of indexes) {
if (!index.unique || !index.name || index.name === "_id_") continue;
const keys = Object.keys(index.key ?? {});
const isLegacyPropertyIndex =
keys.length === 1 &&
(keys[0] === "property" || keys[0] === "property.smsApiKey");
if (!isLegacyPropertyIndex) continue;
await this.clientModel.collection.dropIndex(index.name);
this.logger.warn(
`Dropped legacy unique index on clients.${keys[0]}: ${index.name}`,
);
}
} catch (err) {
this.logger.error("Failed to drop legacy client property index", err);
}
}
async create(client: ClientModel): Promise<ClientModel> {
return await this.clientModel.create(client);
}