“JavaScript runtime function invalid.”,”key”:”afterUpdateAccount”

44 Views Asked by At

im trying to add metdata after userupdate. however after adding function in main.ts and go to the ApiExplorer UpdateAccount its not running my function. in my logs shows this error:

template_nk_backend | {“level”:“error”,“ts”:“2023-07-29T05:59:14.888Z”,“caller”:“server/runtime_javascript.go:477”,“msg”:“JavaScript runtime function invalid.”,“key”:“afterUpdateAccount”}

Dont know whats causing the issue. I'm new to nakama.

This is my main.ts:

 function InitModule(
    ctx: nkruntime.Context,
    logger: nkruntime.Logger,
    nk: nkruntime.Nakama,
    initializer: nkruntime.Initializer
  ) {
    let afterUpdateAccount: nkruntime.AfterHookFunction<
      void,
      nkruntime.UserUpdateAccount
    > = function (
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama
    ): nkruntime.UserUpdateAccount {
      // Check the group name does not contain profanity (containsProfanity implementation not provided)
      logger.info("afterUpdateAccount hook called.");
  
      let user_id = ctx.userId;
      try {
        const account = nk.accountGetId(user_id);
        let metadata = account.user.metadata || {};
  
        metadata.gameResult = "won";
  
        // Convert the metadata to a JSON string
        const metadataString = JSON.stringify(metadata);
  
        // Update the user's metadata using the JSON string
        nk.accountUpdateId(user_id, metadataString);
  
        // Return a dummy UserUpdateAccount object
        return {
          userId: user_id,
          username: "please",
          displayName: "please2",
          timezone: "",
          location: "",
          langTag: "",
          avatarUrl: "please3",
          metadata: { metadataString },
        };
      } catch (error) {
        // Handle the error as appropriate.
        logger.error("Error updating user account metadata:", error);
  
        // Return a dummy UserUpdateAccount object in case of an error
        return {
          userId: "",
          username: "",
          displayName: "",
          timezone: "",
          location: "",
          langTag: "",
          avatarUrl: "",
          metadata: {},
        };
      }
    };
  
    // Register the afterUpdateAccount hook
    initializer.registerAfterUpdateAccount(afterUpdateAccount);
  
    // Define the rpcCreateNewAccount function
    function rpcCreateNewAccount(
      ctx: nkruntime.Context,
      logger: nkruntime.Logger,
      nk: nkruntime.Nakama,
      payload: any
    ): any {
      // Your rpcCreateNewAccount function implementation here...
    }
  
    // Register the rpcCreateNewAccount function
    initializer.registerRpc("updateaccount", rpcCreateNewAccount);
  
    logger.info("JavaScript logic loaded.");
  }
0

There are 0 best solutions below