-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
48 lines (43 loc) · 1.08 KB
/
index.ts
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
import { isObject } from '@suin/is-object'
export type EventData<T = unknown> = {
correlationId: string
data: T
}
/**
* Returns new EventData.
*/
export const newEventData = <T>(eventData: EventData<T>): EventData<T> =>
eventData
/**
* Checks if the given value is compatible with EventData.
*/
export const isEventData = (value: unknown): value is EventData => {
try {
assertEventData(value)
return true
} catch {
return false
}
}
/**
* Returns the given value as EventData if it is valid, otherwise throws an
* Error.
* @throws {Error}
*/
export const parseEventData = (value: unknown): EventData => {
assertEventData(value)
return value
}
/**
* Asserts that the given value is compatible with EventData, otherwise throws
* ane Error.
* @throws {Error}
*/
export function assertEventData(value: unknown): asserts value is EventData {
if (!isObject<EventData>(value)) {
throw new Error('EventData must be a type object')
}
if (typeof value.correlationId !== 'string') {
throw new Error('EventData.correlationId must be a type string')
}
}