Skip to content

Instantly share code, notes, and snippets.

@Meldiron
Created August 16, 2021 10:07
Show Gist options
  • Save Meldiron/27ff3b343643e2566bd4b0c0b5ef4fd0 to your computer and use it in GitHub Desktop.
Save Meldiron/27ff3b343643e2566bd4b0c0b5ef4fd0 to your computer and use it in GitHub Desktop.
Typescript snippet for sync-like function execution in Appwrite
// This snippets expect that your functions use JSON as both input and output
// Connect to appwrite, should be globaly shared
let sdk = new Appwrite();
sdk
.setEndpoint("https://[HOSTNAME_OR_IP]/v1") // Your API Endpoint
.setProject("5df5acd0d48c2"); // Your project ID
// Shared type for strict type definition
// If success is false, there will always be `data.msg`: string
export type AppwriteExecutionResponse = {
success: boolean;
data: any;
};
// Function to get appwrite's execution result - should be in separate "lib.ts" file
const getExecutionResponse = async (
functionId: string,
executionId: string
): Promise<AppwriteExecutionResponse> => {
// Recursive function to attept to get data multiple times
const getResponseRecursion = async (
currentIteration: number = 1
): Promise<AppwriteExecutionResponse | null> => {
// Return error if we didn't get response in 15 attepmts (3secs + response await times)
if (currentIteration >= 5) {
return {
success: false,
data: {
msg: "Execution didn't respond for too long."
},
};
}
// Get execution info
const executionData = await sdk.functions.getExecution(
functionId,
executionId
);
// If we have status, reutrn it
if (executionData.status === "completed") {
return {
success: true,
data: JSON.parse(executionData.stdout),
};
} else if (executionData.status === "failed") {
return {
success: false,
data: JSON.stringify({
msg: executionData.stderr
}),
};
}
// We dont have status yet
// Wait 0.2s
await new Promise<void>((promiseResponse, _promiseReject) => {
setTimeout(() => {
promiseResponse();
}, 200);
});
// Try to get status again
return await getResponseRecursion(currentIteration + 1);
};
// Run recursive function, wait for result
const responseData = await getResponseRecursion();
return responseData;
};
// Execute function and get response - the code you will write each time
const functionId = "894fsd65sd";
const functionData = { user: "Meldiron", age: 101, canPlayWithLego: false };
const { $id: executionId } = await sdk.functions.createExecution(functionId, JSON.stringify(functionData));
const executionResponse = await getExecutionResponse(functionId, executionId);
// Use data
if(executionResponse.success) {
// Success, we have data - JSON object
console.log(executionResponse.data);
} else {
// Whoops, problem. We have data.msg
console.log(executionResponse.data.msg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment