1 /* 2 * Copyright (c) Meta Platforms, Inc. and affiliates. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.facebook.ktfmt.onlineformatter 18 19 import com.amazonaws.services.lambda.runtime.Context 20 import com.amazonaws.services.lambda.runtime.RequestHandler 21 import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent 22 import com.facebook.ktfmt.cli.ParsedArgs 23 import com.facebook.ktfmt.format.Formatter 24 import com.google.gson.Gson 25 import java.io.ByteArrayOutputStream 26 import java.io.PrintStream 27 28 class Handler : RequestHandler<APIGatewayProxyRequestEvent, String> { 29 init { 30 // Warm up. 31 gson.toJson(Formatter.format(Formatter.KOTLINLANG_FORMAT, "/* foo */ fun foo() {}")) 32 } 33 handleRequestnull34 override fun handleRequest(event: APIGatewayProxyRequestEvent, context: Context?): String { 35 return gson.toJson( 36 try { 37 val request = gson.fromJson(event.body, Request::class.java) 38 val parsingErrors = ByteArrayOutputStream() 39 val style = request.style 40 val parsedArgs = 41 ParsedArgs.parseOptions( 42 PrintStream(parsingErrors), if (style == null) arrayOf() else arrayOf(style)) 43 Response( 44 Formatter.format( 45 parsedArgs.formattingOptions.copy(maxWidth = request.maxWidth ?: 100), 46 request.source ?: ""), 47 parsingErrors.toString().ifEmpty { null }) 48 } catch (e: Exception) { 49 Response(null, e.message) 50 }) 51 } 52 53 companion object { 54 val gson = Gson() 55 } 56 } 57 58 class Request { 59 var source: String? = "" 60 var style: String? = "" 61 var maxWidth: Int? = 100 62 } 63 64 data class Response(val source: String?, val err: String?) 65