Repository
The pattern, by hand
1. Port — the contract + DI token
import { Result } from '@soapjs/soap';
import { Character } from '../../domain/character.entity';
export abstract class CharacterRepository {
static readonly Token = 'CharacterRepository';
abstract add(...characters: Character[]): Promise<Result<Character[]>>;
abstract findById(id: string): Promise<Result<Character | null>>;
abstract findAll(filters?: CharacterFilters): Promise<Result<Character[]>>;
}2. Adapter — the implementation
import { ReadWriteRepository, FindParams, Where } from '@soapjs/soap';
export class CharacterRepositoryMongo
extends ReadWriteRepository<Character, CharacterDocument>
implements CharacterRepository {
async findById(id: string): Promise<Result<Character | null>> {
const r = await this.find(FindParams.create({ where: new Where().valueOf('_id').isEq(id), limit: 1 }));
return r.isFailure() ? Result.withFailure(r.failure) : Result.withSuccess(r.content[0] ?? null);
}
async findAll(filters: CharacterFilters = {}): Promise<Result<Character[]>> {
const where = new Where();
if (filters.universe) where.valueOf('universe').isEq(filters.universe);
return this.find(FindParams.create({ where, sort: { name: 1 } }));
}
}3. Wire it in the composition root
Querying
CQRS read/write split
Last updated