-
Notifications
You must be signed in to change notification settings - Fork 0
/
createFunction.ts
67 lines (60 loc) · 1.99 KB
/
createFunction.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { IncomingWebhook } from '@slack/webhook'
import { EmailData, isEmailData } from '@suin/email-data'
import { parseEventData } from '@suin/event-data'
import type { PubSubFunction } from '@suin/google-cloud-typed-pubsub-function'
import { JapannetbankNotification } from '@suin/japannetbank-email-parser'
import { notificationFormatter } from './notificationFormatter'
export const createFunction = ({
webhook,
logger = defaultLogger,
}: Dependencies): PubSubFunction => async event => {
const incomingEvent = parseEventData(
JSON.parse(Buffer.from(event.data, 'base64').toString('utf-8')),
)
logger.info('Received an event', { incomingEvent })
const { notification, email } = incomingEvent.data as Data // todo: parse
// Notifies a message
if (notification && notificationFormatter[notification.type]) {
logger.info('Notification formatting available')
const message = notificationFormatter[notification.type]!(
notification as any,
)
await webhook.send(message)
logger.info('Sent a message to slack', {
correlationId: incomingEvent.correlationId,
message,
})
return
}
// Fallback operation
if (isEmailData(email)) {
logger.info('Notification formatting unavailable')
const message = {
attachments: [{ text: email.subject! }],
}
await webhook.send(message)
logger.info('Sent a message to slack', {
correlationId: incomingEvent.correlationId,
message,
})
return
}
logger.info('Something wrong')
}
const defaultLogger: Logger = {
error(message: string, meta?: unknown): void {
console.error(JSON.stringify({ message, meta }))
},
info(message: string, meta?: unknown): void {
console.info(JSON.stringify({ message, meta }))
},
}
export type Dependencies = {
readonly webhook: Pick<IncomingWebhook, 'send'>
readonly logger?: Logger
}
export type Logger = Pick<Console, 'info' | 'error'>
export type Data = {
readonly notification?: JapannetbankNotification
readonly email: EmailData
}