feat(db): index users by email
This commit is contained in:
@@ -47,6 +47,9 @@ export class ProductionDatabaseStrategy implements DatabaseStrategy {
|
|||||||
for (const dbName of databases) {
|
for (const dbName of databases) {
|
||||||
try {
|
try {
|
||||||
await this.createDatabaseIfNotExists(dbName);
|
await this.createDatabaseIfNotExists(dbName);
|
||||||
|
if (dbName === 'users') {
|
||||||
|
await this.ensureUserEmailIndex();
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.db.error(
|
logger.db.error(
|
||||||
`Failed to initialize database ${dbName}`,
|
`Failed to initialize database ${dbName}`,
|
||||||
@@ -56,6 +59,40 @@ export class ProductionDatabaseStrategy implements DatabaseStrategy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async ensureUserEmailIndex(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const indexes = await this.makeRequest<{
|
||||||
|
indexes: Array<{
|
||||||
|
name: string;
|
||||||
|
def: { fields: Array<Record<string, string>> };
|
||||||
|
}>;
|
||||||
|
}>('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<void> {
|
private async createDatabaseIfNotExists(dbName: string): Promise<void> {
|
||||||
try {
|
try {
|
||||||
// Check if database exists
|
// Check if database exists
|
||||||
@@ -225,13 +262,14 @@ export class ProductionDatabaseStrategy implements DatabaseStrategy {
|
|||||||
|
|
||||||
async findUserByEmail(email: string): Promise<User | null> {
|
async findUserByEmail(email: string): Promise<User | null> {
|
||||||
const response = await this.makeRequest<{
|
const response = await this.makeRequest<{
|
||||||
rows: Array<{ doc: User }>;
|
docs: User[];
|
||||||
|
warning?: string;
|
||||||
}>('POST', '/users/_find', {
|
}>('POST', '/users/_find', {
|
||||||
selector: { email },
|
selector: { email },
|
||||||
limit: 1,
|
limit: 1,
|
||||||
});
|
});
|
||||||
|
|
||||||
return response.rows[0]?.doc || null;
|
return response.docs[0] || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteUser(id: string): Promise<boolean> {
|
async deleteUser(id: string): Promise<boolean> {
|
||||||
|
|||||||
Reference in New Issue
Block a user