-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiGatewayRequestHandler.scala
48 lines (40 loc) · 1.44 KB
/
ApiGatewayRequestHandler.scala
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
package org.encalmo.lambda
import scala.util.matching.Regex
/** Abstract base class of an http request handler. */
trait ApiGatewayRequestHandler[ApplicationContext] {
type Resource = (String, Regex)
def handleRequest(
request: ApiGatewayRequest
)(using LambdaContext, ApplicationContext): Option[ApiGatewayResponse]
extension (r: Resource)
inline def httpMethod: String = r._1
inline def pathRegex: Regex = r._2
inline def unapplySeq(request: ApiGatewayRequest) =
if (request.httpMethod == r._1 || r._1 == "ANY")
then r._2.unapplySeq(request.getResourceOrPathIfProxy)
else None
final def createApiGatewaySuccessResponse(body: String): ApiGatewayResponse =
ApiGatewayResponse(
statusCode = 200,
headers = Map("Content-Type" -> "application/json"),
isBase64Encoded = false,
body = body
)
final def createApiGatewaySuccessResponse(
json: ujson.Value
): ApiGatewayResponse =
ApiGatewayResponse(
statusCode = 200,
headers = Map("Content-Type" -> "application/json"),
isBase64Encoded = false,
body = ujson.write(json)
)
final def returnErrorResponseWhenException(e: Throwable): ApiGatewayResponse =
ApiGatewayResponse(
statusCode = 501,
headers = Map("Content-Type" -> "plain/text"),
isBase64Encoded = false,
body = s"${e.getClass.getName()} ${e
.getMessage()}\n${e.getStackTrace().take(10).mkString("\n")}"
)
}