-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.ts
71 lines (64 loc) · 1.84 KB
/
handler.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
68
69
70
71
import { Context, APIGatewayEvent, APIGatewayProxyResult } from 'aws-lambda'
import { eventSchema } from './utils/event-schema'
import { DatabaseConnection, MongoConnection } from './utils/database'
import { EventRepository, EventRepoInterface } from './event/event-repository'
let databaseConnection = null
export async function connectToDataBase() {
if (databaseConnection) return databaseConnection
const connection: DatabaseConnection = new MongoConnection()
databaseConnection = await connection.connect(
`mongodb+srv://${process.env.DB_USER_NAME}:${process.env.DB_PASSWORD}@${process.env.DB_URL}/myFirstDatabase?retryWrites=true&w=majority`,
process.env.DB_NAME
)
return databaseConnection
}
async function getEventRepo() {
if (!databaseConnection) await connectToDataBase()
const repository: EventRepoInterface = new EventRepository(databaseConnection)
return repository
}
export async function registerEvent(
event: APIGatewayEvent,
context: Context
): Promise<APIGatewayProxyResult> {
let data = {}
try {
data = JSON.parse(event.body)
} catch (err) {
return {
statusCode: 400,
body: JSON.stringify({
success: false,
message: 'Invalid request while parsing body'
})
}
}
const { error, value } = eventSchema.validate(data)
if (error) {
return {
statusCode: 400,
body: JSON.stringify({
success: false,
message: 'Invalid request from schema validation'
})
}
}
const eventRepository: EventRepoInterface = await getEventRepo()
try {
eventRepository.addEvent(value)
return {
statusCode: 200,
body: JSON.stringify({
success: true
})
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify({
success: false,
message: "Can't save the event data"
})
}
}
}