|
| 1 | +import { |
| 2 | + Aggregate, |
| 3 | + Id, |
| 4 | + CreationEvent, |
| 5 | + TransformationEvent, |
| 6 | +} from '@/lib/eventSourcing/event'; |
| 7 | + |
| 8 | +import * as s from '@/lib/json/schema'; |
| 9 | + |
| 10 | +class User implements Aggregate<User> { |
| 11 | + constructor( |
| 12 | + readonly aggregateId: Id<User>, |
| 13 | + readonly aggregateVersion: number, |
| 14 | + readonly name: string, |
| 15 | + ) {} |
| 16 | +} |
| 17 | + |
| 18 | +export class CreateUser implements CreationEvent<CreateUser, User> { |
| 19 | + static type: 'CreateUserr' = 'CreateUserr'; |
| 20 | + static schemaArgs = s.object({ |
| 21 | + type: s.stringLiteral(CreateUser.type), |
| 22 | + aggregateId: Id.schema(), |
| 23 | + name: s.string, |
| 24 | + }); |
| 25 | + static schema = CreateUser.schemaArgs.dimap( |
| 26 | + (v) => new CreateUser(v), |
| 27 | + (v) => v.values, |
| 28 | + ); |
| 29 | + |
| 30 | + schema = CreateUser.schema; |
| 31 | + constructor(readonly values: s.Infer<typeof CreateUser.schemaArgs>) {} |
| 32 | + createAggregate() { |
| 33 | + return new User(new Id('wat'), 0, this.values.name); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +export class AddName implements TransformationEvent<AddName, User> { |
| 38 | + static type: 'AddName' = 'AddName'; |
| 39 | + constructor(readonly values: s.Infer<typeof AddName.schemaArgs>) {} |
| 40 | + |
| 41 | + static schemaArgs = s.object({ |
| 42 | + type: s.stringLiteral(AddName.type), |
| 43 | + aggregateId: Id.schema(), |
| 44 | + name: s.string, |
| 45 | + }); |
| 46 | + |
| 47 | + static schema = AddName.schemaArgs.dimap( |
| 48 | + (v) => new AddName(v), |
| 49 | + (v) => v.values, |
| 50 | + ); |
| 51 | + readonly schema = AddName.schema; |
| 52 | + |
| 53 | + transformAggregate(agg: User): User { |
| 54 | + const u = new User( |
| 55 | + agg.aggregateId, |
| 56 | + agg.aggregateVersion + 1, |
| 57 | + this.values.name, |
| 58 | + ); |
| 59 | + return u; |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +export class RemoveName implements TransformationEvent<RemoveName, User> { |
| 64 | + static type: 'RemoveName' = 'RemoveName'; |
| 65 | + constructor(readonly values: s.Infer<typeof RemoveName.schemaArgs>) {} |
| 66 | + |
| 67 | + static schemaArgs = s.object({ |
| 68 | + type: s.stringLiteral(RemoveName.type), |
| 69 | + aggregateId: Id.schema(), |
| 70 | + name: s.string, |
| 71 | + }); |
| 72 | + |
| 73 | + static schema = RemoveName.schemaArgs.dimap( |
| 74 | + (v) => new RemoveName(v), |
| 75 | + (v) => v.values, |
| 76 | + ); |
| 77 | + readonly schema = RemoveName.schema; |
| 78 | + |
| 79 | + transformAggregate(agg: User): User { |
| 80 | + const u = new User( |
| 81 | + agg.aggregateId, |
| 82 | + agg.aggregateVersion + 1, |
| 83 | + this.values.name, |
| 84 | + ); |
| 85 | + return u; |
| 86 | + } |
| 87 | +} |
0 commit comments