From f9ccb5022253a3bb686ccfd27ecd9ad6bc4744b5 Mon Sep 17 00:00:00 2001 From: William Valentin Date: Tue, 23 Sep 2025 11:23:45 -0700 Subject: [PATCH] feat(db): index users by email --- .../database/ProductionDatabaseStrategy.ts | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/services/database/ProductionDatabaseStrategy.ts b/services/database/ProductionDatabaseStrategy.ts index 2758736..89619cb 100644 --- a/services/database/ProductionDatabaseStrategy.ts +++ b/services/database/ProductionDatabaseStrategy.ts @@ -47,6 +47,9 @@ export class ProductionDatabaseStrategy implements DatabaseStrategy { for (const dbName of databases) { try { await this.createDatabaseIfNotExists(dbName); + if (dbName === 'users') { + await this.ensureUserEmailIndex(); + } } catch (error) { logger.db.error( `Failed to initialize database ${dbName}`, @@ -56,6 +59,40 @@ export class ProductionDatabaseStrategy implements DatabaseStrategy { } } + private async ensureUserEmailIndex(): Promise { + try { + const indexes = await this.makeRequest<{ + indexes: Array<{ + name: string; + def: { fields: Array> }; + }>; + }>('GET', '/users/_index'); + + const hasEmailIndex = indexes.indexes.some(index => { + if (index.name === 'email-index') { + return true; + } + return index.def.fields.some( + field => Object.keys(field)[0] === 'email' + ); + }); + + if (hasEmailIndex) { + return; + } + + await this.makeRequest('POST', '/users/_index', { + index: { fields: ['email'] }, + name: 'email-index', + type: 'json', + }); + + logger.db.query('Created email index for users database'); + } catch (error) { + logger.db.error('Failed to ensure user email index', error as Error); + } + } + private async createDatabaseIfNotExists(dbName: string): Promise { try { // Check if database exists @@ -225,13 +262,14 @@ export class ProductionDatabaseStrategy implements DatabaseStrategy { async findUserByEmail(email: string): Promise { const response = await this.makeRequest<{ - rows: Array<{ doc: User }>; + docs: User[]; + warning?: string; }>('POST', '/users/_find', { selector: { email }, limit: 1, }); - return response.rows[0]?.doc || null; + return response.docs[0] || null; } async deleteUser(id: string): Promise {