-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathEvent.ts
More file actions
107 lines (92 loc) · 2.3 KB
/
Event.ts
File metadata and controls
107 lines (92 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import Ajv from 'ajv';
import type {
PutEventsRequestEntry,
PutEventsResultEntry,
} from '@aws-sdk/client-eventbridge';
import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import type { EventBridgeEvent } from 'aws-lambda';
import { Bus } from './Bus';
const ajv = new Ajv();
export class Event<N extends string, S extends JSONSchema> {
private _name: N;
private _source: string;
private _bus: Bus;
private _schema: S;
private _validate: Ajv.ValidateFunction;
private _pattern: { 'detail-type': [N]; source: string[] };
constructor({
name,
source,
bus,
schema,
}: {
name: N;
source: string;
bus: Bus;
schema: S;
}) {
this._name = name;
this._source = source;
this._bus = bus;
this._schema = schema;
this._validate = ajv.compile(schema);
this._pattern = { source: [source], 'detail-type': [name] };
}
get name(): N {
return this._name;
}
get source(): string {
return this._source;
}
get bus(): Bus {
return this._bus;
}
get schema(): S {
return this._schema;
}
get pattern(): { 'detail-type': [N]; source: string[] } {
return this._pattern;
}
get publishedEventSchema(): {
type: 'object';
properties: {
source: { const: string };
'detail-type': { const: N };
detail: S;
};
required: ['source', 'detail-type', 'detail'];
} {
return {
type: 'object',
properties: {
source: { const: this._source },
'detail-type': { const: this._name },
detail: this._schema,
},
required: ['source', 'detail-type', 'detail'],
};
}
create(event: FromSchema<S>): PutEventsRequestEntry {
if (!this._validate(event)) {
throw new Error(
'Event does not satisfy schema' + JSON.stringify(this._validate.errors),
);
}
return {
Source: this._source,
DetailType: this._name,
Detail: JSON.stringify(event),
};
}
async publish(event: FromSchema<S>): Promise<{
FailedEntryCount?: number;
Entries?: (PutEventsRequestEntry & PutEventsResultEntry)[];
}> {
return this._bus.put([this.create(event)]);
}
}
type GenericEvent = Event<string, JSONSchema>;
export type PublishedEvent<Event extends GenericEvent> = EventBridgeEvent<
Event['name'],
FromSchema<Event['schema']>
>;