// In your plugin's repositories/user-preferences-repository.ts
import { eq } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { UUID } from '@elizaos/core';
import { userPreferencesTable } from '../schema.ts';
export interface UserPreferences {
id: UUID;
userId: UUID;
preferences: Record<string, any>;
createdAt: Date;
updatedAt: Date;
}
export class UserPreferencesRepository {
constructor(private readonly db: ReturnType<typeof drizzle>) {}
/**
* Create or update user preferences
*/
async upsert(userId: UUID, preferences: Record<string, any>): Promise<UserPreferences> {
// Check if preferences exist
const existing = await this.findByUserId(userId);
if (existing) {
// Update existing
const [updated] = await this.db
.update(userPreferencesTable)
.set({
preferences,
updatedAt: new Date(),
})
.where(eq(userPreferencesTable.userId, userId))
.returning();
return this.mapToUserPreferences(updated);
} else {
// Create new
const [created] = await this.db
.insert(userPreferencesTable)
.values({
userId,
preferences,
createdAt: new Date(),
updatedAt: new Date(),
})
.returning();
return this.mapToUserPreferences(created);
}
}
/**
* Find preferences by user ID
*/
async findByUserId(userId: UUID): Promise<UserPreferences | null> {
const result = await this.db
.select()
.from(userPreferencesTable)
.where(eq(userPreferencesTable.userId, userId))
.limit(1);
return result.length > 0 ? this.mapToUserPreferences(result[0]) : null;
}
/**
* Delete preferences by user ID
*/
async deleteByUserId(userId: UUID): Promise<boolean> {
const result = await this.db
.delete(userPreferencesTable)
.where(eq(userPreferencesTable.userId, userId))
.returning();
return result.length > 0;
}
/**
* Find all preferences (with pagination)
*/
async findAll(offset = 0, limit = 100): Promise<UserPreferences[]> {
const results = await this.db
.select()
.from(userPreferencesTable)
.offset(offset)
.limit(limit);
return results.map(this.mapToUserPreferences);
}
/**
* Map database row to domain type
*/
private mapToUserPreferences(row: any): UserPreferences {
return {
id: row.id as UUID,
userId: row.userId || row.user_id,
preferences: row.preferences || {},
createdAt: row.createdAt || row.created_at,
updatedAt: row.updatedAt || row.updated_at,
};
}
}