#[SOLVED] Speeding up Appwrite Cloud Function execution

41 messages · Page 1 of 1 (latest)

signal salmon
#

Hi, I've got a cloud function that has a sole purpose of creating a document. However, it takes around 1 second to run. With my current setup, I'm waiting for the promise to resolve when calling functions.createExecution(), from there, I have a Realtime database event subscription that updates the state of listed documents on my web app.

I was thinking that I should switch to updating the state with the request information in my front end, whilst the function runs asynchronously, is this bad practise? If I did it this way, the document would be created in the background and it would create the illusion that there is no waiting for the document to create.

upbeat isle
#

Or at least most relevant fragments

trim cosmos
#

You could do doc. creation in async if its result or access to document is not really necessary after executing the function.

Async is usually for fire/forget ops.

signal salmon
# upbeat isle Could yo please send the function code for better understanding if it's not conf...
import { Client, Databases, Users, ID, Permission, Role } from 'node-appwrite';

export default async ({ req, res, log, error }) => {

    const client = new Client()
        .setEndpoint('https://cloud.appwrite.io/v1')
        .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID)
        .setKey(process.env.APPWRITE_API_KEY);

    const databases = new Databases(client);
    const users = new Users(client)
    const userID = req.headers['x-appwrite-user-id']

    // Check validity of request body.
    const requestData = JSON.parse(req.body)
    if(requestData.body == "") return res.json({ message: "No body text provided." }, 400)
    else if(requestData.colour == "") return res.json({ message: "No colour provided." }, 400)

    const colours = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
    const foundInColours = colours.find(c => requestData.colour.includes(c))
    if(!foundInColours) return res.json({ message: "Colour provided was not found in red, orange, yellow, green, blue or purple." }, 400)

    // Add Memo to Database
    const user = users.get(userID)
    if(!user) return res.json({ message: "Invalid User Id Provided" }, 400)

    let permissions = [
        Permission.write(Role.user(userID)),
        Permission.read(Role.user(userID))
    ]

    let newPayload = {
      colour: requestData.colour,
      body: requestData.body,
      favourite: requestData.favourite
    }

    try {
        await databases.createDocument(
            process.env.MEMO_DATABASE_ID,
            process.env.MEMO_COLLECTION_ID,
            ID.unique(),
            newPayload,
            permissions
        )
    } catch (e) {
        console.error("Failed to create document: " + e.message)
        return res.json({ message: "Failed to create document." }, 500)
    }

    return res.json({ message: "Memo created!" }, 201)
}
trim cosmos
#

shouldn't users.get() be awaited? 👀

signal salmon
#

ooops

brittle sage
#

you could just return success after validation is complete

#

rather than waiting for document creation promise to resolve

trim cosmos
#

If you are using something like this -
client side - create notes & upload to backend.
backend - spin up the function & save.

couple of things you can do -
Save the note to local storage &

  1. shoot the function in async.
    mark the note as saved on the next app launch by checking the doc's existence.

  2. wait for the function to return a result.

  3. fire the function without await, use then() if using js on client side, or launch {} on kotlin or the lang. equivalent to offload the task & not block the thread. update the notes status later when the function returns an execution object.

#

this is just a overview of what I can think of rn.

signal salmon
# trim cosmos If you are using something like this - client side - create notes & upload to b...

Thank you, in relation to the whole function topic. I've got an issue regarding executing them with a specific method.
This is the code snippet:

await functions.createExecution('[FUNCTION_ID]', JSON.stringify({ body: "Hi" }), false, "/", "PATCH", { "memo-id": editModalContent.$id })

but the request is being shown as POST on the dashboard, and when I log the method received in my function, I also see POST. Any idea why?

tall oriole
signal salmon
tall oriole
signal salmon
#

Wait

tall oriole
#

FYI, im on cloud and i have a function that only creates a document after some validation. cold start takes 4s but after that it's .5s

signal salmon
tall oriole
signal salmon
#

Yes, that makes sense.

signal salmon
signal salmon
tall oriole
signal salmon
tall oriole
tall oriole
tall oriole
#

and of course network latency (distance from the server) can play a factor too

signal salmon
#

That way it looks like something is happening in a UX sense

signal salmon
#

No idea how

#

barely changed the code but..

upbeat isle
#

Can I mark this as solved then? appwriterocket

signal salmon
#

But, I have settled on awaiting the promise to resolve and just showing a loading animation on the create button whilst the function processes

upbeat isle
#

Perfect