Skip to content

Commit

Permalink
4192 - Write a generateShortUrl() Function using Kotlin
Browse files Browse the repository at this point in the history
Update README.md
  • Loading branch information
Ritzy-NCode committed Jan 31, 2023
1 parent 186b160 commit 9884fc9
Show file tree
Hide file tree
Showing 3 changed files with 209 additions and 0 deletions.
93 changes: 93 additions & 0 deletions kotlin/generateShortUrl/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# generateShortUrl() - Kotlin

## ⚡ Function Details

Generate a short URL.
Introduce support for bitly and tinyurl APIs.

If necessary, introduce their secret keys as function variables. URL and provider to use must be provided as payload, and shortened URL should be returned.

## Example input:

```json
{
"provider":"bitly",
"url":"https://google.com/",
"provider_api_key": "--the api key from the provider--"
}
```

## Example output:

Successful response:

```json
{
"success":true,
"url":"https://bit.ly/3y3HDkC"
}
```

Error response:

```json
{
"success":false,
"message":"Payload does not contain 'provider'"
}
```

```json
{
"success":false,
"message":"Payload does not contain 'url'"
}
```

```json
{
"success":false,
"message":"Payload doesn't contain valid provider - 'random'"
}
```

## 🚀 Deployment

1. Clone this repository, and enter this function folder:

```
$ git clone https://github.com/open-runtimes/examples.git && cd examples
$ cd kotlin/generateShortUrl
```

2. Build the code:

```bash
docker run -e INTERNAL_RUNTIME_ENTRYPOINT=src/Index.kt --rm --interactive --tty --volume $PWD:/usr/code openruntimes/kotlin:v2-1.6 sh /usr/local/src/build.sh
```

3. Spin-up open-runtime:

```bash
docker run -p 3001:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/kotlin:v2-1.6 sh /usr/local/src/start.sh
```

Your function is now listening on port `3000`, and you can execute it by sending `POST` request with appropriate authorization headers. To learn more about runtime, you can visit Kotlin runtime [README](https://github.com/open-runtimes/open-runtimes/tree/main/runtimes/kotlin-1.6).

4. Execute command:
```bash
curl -X 'POST' \
'http:https://localhost:3000/' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-H 'X-Internal-Challenge: secret-key' \
-d '{
"payload": "{\"url\":\"https://facebook.com/test\",\"provider\":\"bitly\",\"provider_api_key\":\"to-be-created\"}"
}'
```
The provider_api_key should be created


## 📝 Notes

- This function is designed for use with Appwrite Cloud Functions. You can learn more about it in [Appwrite docs](https://appwrite.io/docs/functions).
3 changes: 3 additions & 0 deletions kotlin/generateShortUrl/deps.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
dependencies {
implementation 'com.google.code.gson:gson:2.9.0'
}
113 changes: 113 additions & 0 deletions kotlin/generateShortUrl/src/Index.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.google.gson.JsonSyntaxException
import io.openruntimes.kotlin.RuntimeRequest
import io.openruntimes.kotlin.RuntimeResponse
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL


val PROVIDER_API_MAP = mapOf("bitly" to "https://api-ssl.bitly.com/v4/shorten",
"tinyurl" to "https://api.tinyurl.com/create")

val PROVIDER_API_URL_KEY = mapOf("bitly" to "long_url","tinyurl" to "url")

val gson = Gson()

fun getErrorResponseWithMessage(res: RuntimeResponse, message: String? = "Some error occurred"): RuntimeResponse {
return res.json(
data = mapOf(
"success" to false,
"message" to message
),
statusCode = 400
)
}

@Throws(Exception::class)
suspend fun main(req: RuntimeRequest, res: RuntimeResponse): RuntimeResponse {

val payloadMap = Gson().fromJson<Map<String, String>>(
req.payload.ifBlank { "{}" },
Map::class.java
)

val provider = payloadMap["provider"]?:""
val longUrl = payloadMap["url"] ?: ""
val providerApiKey = payloadMap["provider_api_key"]?:""
var providerResponse="";

try{

if (provider.isEmpty() || provider.trim().isEmpty()) {
return getErrorResponseWithMessage(res, "Payload doesn't contain 'provider'")
}
if (longUrl.isEmpty() || longUrl.trim().isEmpty()) {
return getErrorResponseWithMessage(res, "Payload doesn't contain 'url'")
}

if(!PROVIDER_API_MAP.contains(provider)){
return getErrorResponseWithMessage(res, "Payload doesn't contain valid provider - '$provider'.")
}

val providerUrl = URL(PROVIDER_API_MAP.get(provider))

val connection = createConnection(providerUrl,providerApiKey)

val requestBody ="{\"${PROVIDER_API_URL_KEY.get(provider)}\":\"$longUrl\"}"

providerResponse= parseResponse(connection,requestBody,provider)
}
catch (e: Exception){
return getErrorResponseWithMessage(res, e.message)
}

return res.json(
data = mapOf(
"success" to true,
"url" to providerResponse
),
statusCode = 200
)
}

fun createConnection(providerUrl:URL,providerApiKey:String): HttpURLConnection {
val connection: HttpURLConnection = providerUrl.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.addRequestProperty("Content-Type", "application/json")
connection.addRequestProperty("Authorization", "Bearer $providerApiKey")
connection.setRequestProperty("accept", "application/json")
connection.doOutput = true
return connection
}

fun parseResponse(connection:HttpURLConnection,requestBody:String,provider:String): String {
val response = StringBuilder()
val os: OutputStream = connection.getOutputStream()
val input: ByteArray = requestBody.toByteArray(Charsets.UTF_8)
os.write(input, 0, input.size)

val br = BufferedReader(InputStreamReader(connection.getInputStream(), Charsets.UTF_8))

var responseLine: String? = null

while (br.readLine().also { responseLine = it } != null) {
response.append(responseLine!!.trim { it <= ' ' })
}

br.close()
connection.disconnect()

val jsonObject = JsonParser().parse(response.toString()).getAsJsonObject()

return when {
provider == "bitly" -> jsonObject.get("link").getAsString()
else -> jsonObject.getAsJsonObject("data").get("tiny_url").getAsString()
}

}

0 comments on commit 9884fc9

Please sign in to comment.