Back

[SOLVED] Function cannot get custom variable

  • 0
  • Functions
  • Web
Hexi
30 May, 2023, 17:30

Hello so I am trying to create something so I can add a attribute to a user and I right now have this code but it doesnt seem to be working:

TypeScript
const sdk = require("node-appwrite");

/*
  'req' variable has:
    'headers' - object with request headers
    'payload' - request body data as a string
    'variables' - object with function variables

  'res' variable has:
    'send(text, status)' - function to return text response. Status code defaults to 200
    'json(obj, status)' - function to return JSON response. Status code defaults to 200

  If an error is thrown, a response with code 500 will be returned.
*/

module.exports = async function (req, res) {
  const client = new sdk.Client();

  // You can remove services you don't use
  const account = new sdk.Account(client);
  const avatars = new sdk.Avatars(client);
  const database = new sdk.Databases(client);
  const functions = new sdk.Functions(client);
  const health = new sdk.Health(client);
  const locale = new sdk.Locale(client);
  const storage = new sdk.Storage(client);
  const teams = new sdk.Teams(client);
  const users = new sdk.Users(client);
  const userId = req.variables["APPWRITE_FUNCTION_USER_ID"];
  //get provided token
  const token = req.variables["APPWRITE_FUNCTION_DATA"]["token"];

  if (
    !req.variables["APPWRITE_FUNCTION_ENDPOINT"] ||
    !req.variables["APPWRITE_FUNCTION_API_KEY"]
  ) {
    console.warn(
      "Environment variables are not set. Function cannot use Appwrite SDK."
    );
  } else {
    client
      .setEndpoint(req.variables["APPWRITE_FUNCTION_ENDPOINT"])
      .setProject(req.variables["APPWRITE_FUNCTION_PROJECT_ID"])
      .setKey(req.variables["APPWRITE_FUNCTION_API_KEY"])
      .setSelfSigned(true);
  }
  var user = await users.get(userId).catch((err) => {
    return err;
  });
  //check if user already has a document in the database predictor-db in colllection users
  var userDoc = await database
    .listDocuments(`predictor-db`, `users`, [], 1, 0, userId)
    .catch((err) => {
      return err;
    });
  // if not create a new one
  if (userDoc.documents.length == 0) {
    //create a new document in the database predictor-db in colllection users and set the token
    await database.createDocument(`predictor-db`, `users`, userId, {
      token: token,
    });
  } else {
    //update the token
    await database.updateDocument(
      `predictor-db`,
      `users`,
      userDoc.documents[0].$id,
      {
        token: token,
      }
    );
  }

  res.json({
    user: user,
  });
};

ERROR:

TypeScript
Error: The document payload is missing.
    at Client.call (/usr/code-start/node_modules/node-appwrite/lib/client.js:171:31)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Databases.createDocument (/usr/code-start/node_modules/node-appwrite/lib/services/databases.js:1055:16)
    at async module.exports (/usr/code-start/src/index.js:59:5)
    at async /usr/local/src/server.js:68:13```
TL;DR
The function is unable to get the custom variable 'token'. The solution is to parse the function data and obtain the token value from it. Here is the updated code: ```js const sdk = require("node-appwrite"); module.exports = async function (req, res) { const client = new sdk.Client(); const database = new sdk.Databases(client); const users = new sdk.Users(client); const userId = req.variables["APPWRITE_FUNCTION_USER_ID"]; const functionData = JSON.parse(req.variables["APPWRITE_FUNCTION_DATA"] ?? '{}'); const token = functionData["token"] ?? ''; //
Binyamin
30 May, 2023, 17:39

Is the token const has a value or it's undefined?

Try to parse the function data as such

TypeScript
const token = JSON.parse(req.variables["APPWRITE_FUNCTION_DATA"] ?? '{}')["token"] ?? '';

Then resend

Binyamin
30 May, 2023, 17:43

Additionally you can check and send response back if not token was given.

Hexi
30 May, 2023, 17:49

has a value

Binyamin
30 May, 2023, 17:49

Without parsing?

Hexi
30 May, 2023, 17:49

its a long string

Hexi
30 May, 2023, 17:49

not a array/json

Binyamin
30 May, 2023, 17:50

Ohh got it

Binyamin
30 May, 2023, 17:50

So maybe try to remove the ["token"]?

Hexi
30 May, 2023, 17:53

{"variables":{"APPWRITE_FUNCTION_ID":"link_user","APPWRITE_FUNCTION_NAME":"linkUser","APPWRITE_FUNCTION_DEPLOYMENT":"64762868142071342215","APPWRITE_FUNCTION_PROJECT_ID":"hex-predictor","APPWRITE_FUNCTION_TRIGGER":"http","APPWRITE_FUNCTION_RUNTIME_NAME":"Node.js","APPWRITE_FUNCTION_RUNTIME_VERSION":"18.0","APPWRITE_FUNCTION_DATA":"{token:LONGToken"}"}

Hexi
30 May, 2023, 17:53

hmmmm it seems to be in a json

Binyamin
30 May, 2023, 17:53

So you just need to parse the token

Hexi
30 May, 2023, 17:53

👍

Binyamin
30 May, 2023, 17:53

Something like this

Binyamin
30 May, 2023, 17:53

lmn

Hexi
30 May, 2023, 17:57

That worked!

Binyamin
30 May, 2023, 17:57

Congrats

Hexi
30 May, 2023, 17:57

Tnx!

Hexi
30 May, 2023, 17:58

[SOLVED] Function cannot get custom variable

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more