Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat 4103 Create WipeAppwriteCollection Java #177

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions java/wipe_appwrite_collection/Index.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import java.util.Map;
import java.util.HashMap;
import java.util.*;
import io.openruntimes.java.*;
import com.google.gson.Gson;
import io.appwrite.Client;
import io.appwrite.exceptions.AppwriteException;
import io.appwrite.services.Databases;
import kotlin.Result;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;
import kotlin.coroutines.EmptyCoroutineContext;
import org.jetbrains.annotations.NotNull;
import okhttp3.Response;
import com.google.gson.JsonParser;
import com.google.gson.JsonObject;

final Gson gson = new Gson();

public RuntimeResponse main(RuntimeRequest req, RuntimeResponse res) throws Exception {
// Initialize the Appwrite client and databases service
Client client = new Client();
var variables = req.getVariables();
String payloadString = req.getPayload().toString();
Map<String, Object> responseData = new HashMap<>();

// Check if the required environment variables are set
if (variables == null
|| !variables.containsKey("APPWRITE_FUNCTION_ENDPOINT")
|| !variables.containsKey("APPWRITE_FUNCTION_API_KEY")
|| !variables.containsKey("APPWRITE_FUNCTION_PROJECT_ID")
|| variables.get("APPWRITE_FUNCTION_ENDPOINT") == null
|| variables.get("APPWRITE_FUNCTION_API_KEY") == null
|| variables.get("APPWRITE_FUNCTION_PROJECT_ID") == null) {
return res.json(Map.of("Environment variables are not set. Function cannot use Appwrite SDK.", false));
} else {
// Set the Appwrite client properties
client
.setEndpoint(variables.get("APPWRITE_FUNCTION_ENDPOINT"))
.setProject(variables.get("APPWRITE_FUNCTION_PROJECT_ID"))
.setKey(variables.get("APPWRITE_FUNCTION_API_KEY"));
}

try {
// Parse the payload data into a Map
Databases databases = new Databases(client);
Map<String, String> payload = gson.fromJson(payloadString, Map.class);
String databaseId = (String) payload.get("databaseId");
String collectionId = (String) payload.get("collectionId");

if (databaseId == null || collectionId == null) {
return res.json(Map.of("Invalid payload.", false));
}

databases.deleteCollection(
databaseId,
collectionId,
new Continuation<Object>() {
@NotNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}

@Override
public void resumeWith(@NotNull Object o) {
String json = "";
try {
if (o instanceof Result.Failure) {
Result.Failure failure = (Result.Failure) o;
throw failure.exception;
} else {
Response response = (Response) o;
}
} catch (Throwable th) {
System.out.print("ERROR: " + th.toString());
}
}
}
);

return res.json(Map.of("success", true));
} catch (AppwriteException e) {
return res.json(Map.of("Collection not found.", false));
}
}
70 changes: 70 additions & 0 deletions java/wipe_appwrite_collection/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Appwrite Collection Wiper

Welcome to the documentation of this function 👋 We strongly recommend keeping this file in sync with your function's logic to make sure anyone can easily understand your function in the future. If you don't need documentation, you can remove this file.

## 🤖 Documentation

A Java Cloud Function that wipes all the documents inside a collection.

_Example input:_

```json
{
"databaseId": "stage",
"collectionId": "profiles"
}
```

_Example output (_sucess_):_

```json
{
"success": true,
}
```

_Example output (_failure_):_

```json
{
"success": false,
"message": "Collection not found."
}
```

## 📝 Environment Variables

APPWRITE_FUNCTION_ENDPOINT - Endpoint of your Appwrite server
APPWRITE_FUNCTION_API_KEY - Appwrite API Key
APPWRITE_FUNCTION_PROJECT_ID - Appwrite project ID. If running on Appwrite, this variable is provided automatically.

## 🚀 Deployment

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

$ git clone https://github.com/open-runtimes/examples.git && cd examples
$ cd java/wipe_appwrite_collection

2. Enter this function folder and build the code:

docker run -e INTERNAL_RUNTIME_ENTRYPOINT=Index.java --rm --interactive --tty --volume $PWD:/usr/code openruntimes/java:v2-18.0 sh /usr/local/src/build.sh
As a result, a code.tar.gz file will be generated.

3. Start the Open Runtime:

docker run -p 3000:3000 -e INTERNAL_RUNTIME_KEY=secret-key --rm --interactive --tty --volume $PWD/code.tar.gz:/tmp/code.tar.gz:ro openruntimes/java:v2-18.0 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 Java runtime README.

4. Execute function:

curl http://localhost:3000/ -d '{"variables":{"APPWRITE_FUNCTION_ENDPOINT":"YOUR_ENDPOINT","APPWRITE_FUNCTION_PROJECT_ID":"YOUR_PROJECT_ID","APPWRITE_FUNCTION_API_KEY":"YOUR_API_KEY"},"payload":"{\"databaseId\":\"stage\",\"collectionId\":\"profiles\"}"}' -H "X-Internal-Challenge: secret-key" -H "Content-Type: application/json"

### Using CLI

Make sure you have [Appwrite CLI](https://appwrite.io/docs/command-line#installation) installed, and you have successfully logged into your Appwrite server. To make sure Appwrite CLI is ready, you can use the command `appwrite client --debug` and it should respond with green text `✓ Success`.

Make sure you are in the same folder as your `appwrite.json` file and run `appwrite deploy function` to deploy your function. You will be prompted to select which functions you want to deploy.

### Manual using tar.gz

Manual deployment has no requirements and uses Appwrite Console to deploy the tag. First, enter the folder of your function. Then, create a tarball of the whole folder and gzip it. After creating `.tar.gz` file, visit Appwrite Console, click on the `Deploy Tag` button and switch to the `Manual` tab. There, set the `entrypoint` to `src/Index.java`, and upload the file we just generated.
4 changes: 4 additions & 0 deletions java/wipe_appwrite_collection/deps.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
dependencies {
implementation 'io.appwrite:sdk-for-kotlin:1.2.0'
implementation 'com.google.code.gson:gson:2.9.0'
}