Files
Autonomous-Bug-Explorer/dist/modules/auth/infrastructure/repositories/KyselyApiKeyRepository.js

76 lines
2.6 KiB
JavaScript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.KyselyApiKeyRepository = void 0;
const ApiKey_1 = require("../../domain/entities/ApiKey");
const UniqueId_1 = require("../../../../shared/domain/UniqueId");
class KyselyApiKeyRepository {
constructor(db) {
this.db = db;
}
async save(apiKey) {
await this.db
.insertInto('api_keys')
.values({
id: apiKey.id.toString(),
user_id: apiKey.userId,
org_id: apiKey.orgId,
name: apiKey.name,
key_hash: apiKey.keyHash,
key_prefix: apiKey.keyPrefix,
permissions: JSON.stringify(apiKey.permissions),
expires_at: apiKey.expiresAt ? apiKey.expiresAt.getTime() : null,
last_used_at: apiKey.lastUsedAt ? apiKey.lastUsedAt.getTime() : null,
created_at: apiKey.createdAt.getTime(),
})
.execute();
}
async findById(id) {
const row = await this.db
.selectFrom('api_keys')
.selectAll()
.where('id', '=', id)
.executeTakeFirst();
return row ? this.toDomain(row) : undefined;
}
async findByHash(keyHash) {
const row = await this.db
.selectFrom('api_keys')
.selectAll()
.where('key_hash', '=', keyHash)
.executeTakeFirst();
return row ? this.toDomain(row) : undefined;
}
async listByUser(userId) {
const rows = await this.db
.selectFrom('api_keys')
.selectAll()
.where('user_id', '=', userId)
.execute();
return rows.map((r) => this.toDomain(r));
}
async delete(id) {
await this.db.deleteFrom('api_keys').where('id', '=', id).execute();
}
async updateLastUsed(id, lastUsedAt) {
await this.db
.updateTable('api_keys')
.set({ last_used_at: lastUsedAt.getTime() })
.where('id', '=', id)
.execute();
}
toDomain(row) {
return ApiKey_1.ApiKey.reconstitute({
userId: row.user_id,
orgId: row.org_id,
name: row.name,
keyHash: row.key_hash,
keyPrefix: row.key_prefix,
permissions: JSON.parse(row.permissions),
expiresAt: row.expires_at ? new Date(row.expires_at) : undefined,
lastUsedAt: row.last_used_at ? new Date(row.last_used_at) : undefined,
createdAt: new Date(row.created_at),
}, UniqueId_1.UniqueId.from(row.id));
}
}
exports.KyselyApiKeyRepository = KyselyApiKeyRepository;