auth.ts (1824B)
1 import { AuthRepository } from "#core/application/authn/auth_repository.ts"; 2 import { 3 EntityLocked, 4 EntityNotFound, 5 } from "#core/application/repository_error.ts"; 6 import { Auth } from "#core/domain/auth.ts"; 7 import { Email } from "#core/domain/email.ts"; 8 import { Token } from "#core/domain/token.ts"; 9 import { UUID } from "#core/domain/uuid.ts"; 10 import { 11 AuthDto, 12 mapFromAuth, 13 mapToAuth, 14 } from "#infrastructure/memory/mapper/auth.ts"; 15 16 export class MemoryAuthRepositoryAdapter implements AuthRepository { 17 constructor(private readonly entities: Map<string, AuthDto>) { 18 } 19 20 find(id: UUID): Auth { 21 const entity = this.entities.get(id.toString()); 22 if (entity !== undefined) { 23 return mapToAuth(entity); 24 } 25 throw new EntityNotFound(id.toString()); 26 } 27 28 findByEmail(email: Email): Auth { 29 const entity = Array.from(this.entities.values()).find((i) => 30 i.email === email.toString() 31 ); 32 if (entity !== undefined) { 33 return mapToAuth(entity); 34 } 35 throw new EntityNotFound(email.toString()); 36 } 37 38 findBySessionToken(sessionToken: Token): Auth { 39 const entity = Array.from(this.entities.values()).find((i) => 40 i.sessionToken === sessionToken.toString() && 41 +i.sessionExpire > Date.now() 42 ); 43 if (entity !== undefined) { 44 return mapToAuth(entity); 45 } 46 throw new EntityNotFound(sessionToken.toString()); 47 } 48 49 store(entity: Auth): void { 50 const dto = mapFromAuth(entity); 51 const latest = Math.max( 52 this.entities.get(dto.uuid)?.version ?? 0, 53 Array.from(this.entities.values()).find((i) => 54 i.email === entity.email.address.toString() 55 )?.version ?? 0, 56 ); 57 if (latest > dto.version) { 58 throw new EntityLocked(); 59 } 60 entity.version = ++dto.version; 61 this.entities.set(dto.uuid, dto); 62 } 63 }