-
Notifications
You must be signed in to change notification settings - Fork 8
/
handler.js
118 lines (100 loc) · 2.5 KB
/
handler.js
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
108
109
110
111
112
113
114
115
116
117
118
'use strict'
const AWS = require('aws-sdk')
const client = new AWS.DynamoDB.DocumentClient()
const SDK = require('@serverless/event-gateway-sdk')
const USERS_TABLE = process.env.USERS_TABLE
const URL = process.env.URL
const eventGateway = new SDK({
url: URL,
})
/*
* Create User
*/
module.exports.createUser = (event, context, callback) => {
const user = event.data.body
if (!user.firstName || !user.lastName || !user.email || !user.id) {
callback(null, {
statusCode: 400,
body: JSON.stringify({errors: [`Invalid request. Missing required field.`]})
})
return
}
const params = {
TableName: USERS_TABLE,
Item: {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
}
}
client.put(params, (error, result) => {
if (error) {
console.error(error)
callback(null, {
statusCode: error.statusCode || 501,
body: JSON.stringify({errors: ['Could not create user']})
})
return
}
eventGateway
.emit({
eventID: '1',
eventType: 'user.created',
cloudEventsVersion: '0.1',
source: '/services/users',
contentType: 'application/json',
data: params.Item
})
.then(() => console.log('Emitted user.created event'))
const response = {
statusCode: 200,
body: JSON.stringify(params.Item),
}
callback(null, response)
})
}
/*
* Get User
*/
module.exports.getUser = (event, context, callback) => {
const params = {
TableName: USERS_TABLE,
Key: {
id: event.data.params.id
}
}
client.get(params, (error, result) => {
if (error) {
console.error(error)
callback(null, {
statusCode: error.statusCode || 501,
body: JSON.stringify({errors: [`Could not retrieve user with ID ${event.data.params.id}`]})
})
return
}
if (result.Item === undefined) {
const response = {
statusCode: 404,
body: JSON.stringify({errors: [`Could not retrieve user with ID ${event.data.params.id}`]})
}
callback(null, response)
return
}
const response = {
statusCode: 200,
body: JSON.stringify(result.Item),
}
callback(null, response)
})
}
/*
* Email User
*/
module.exports.emailUser = (event, context, callback) => {
const user = event.data
console.log(`Received ${event.eventType} event with user:`)
console.dir(user)
// Email your user here
callback(null, { message: 'Success' })
}