Updating a User using Cloud Code JavaScript and Parse iOS SDK

As I work on developing an iOS app using Parse SDK hosted on back4app, I have encountered a problem with implementing a new feature. In the back4app dashboard, my app hosts a main.js file in Cloud Code that successfully sends push notifications when called by code.

Recently, I added a blockuser.js file to my Cloud Code. This file is supposed to edit the isBlocked column (which is of type Boolean) of a specific user in the _User class and set it to true. Here's the code snippet I used:

Parse.Cloud.define("blockUser", function(request, response) {

    var userId = request.params.userId,

    var User = Parse.Object.extend('_User'),
    user = new User({ objectId: userId });

    user.set('isBlocked', true);

    Parse.Cloud.useMasterKey();
    user.save().then(function(user) {
        response.success(user);
    }, function(error) {
        response.error(error)
    });

});

Additionally, here is the Swift code snippet I wrote to call the aforementioned function:

let request = ["userId" : userPointer.objectId!] as [String : Any]

PFCloud.callFunction(inBackground: "blockUser", withParameters: request as [String : Any], block: { (results, error) in
        if error == nil {
           print ("\(userPointer["username"]!) has been blocked!")
           // error in cloud code
        } else {
            print ("\(error!.localizedDescription)")
}})

Upon checking the Xcode console, I noticed this message being printed out:

[Error]: Invalid function. (Code: 141, Version: 1.14.2)

It is clear that the blockUser function is not functioning as expected. Can anyone provide insights into what might be going wrong with either the .js or Swift code?

Answer №1

After several attempts, I have finally cracked it! Below is the custom function I have integrated into my main.js file in Cloud Code:

// BLOCK A USER  ----------------------------------------
Parse.Cloud.define("blockUser", function(request, response) {

    var userId = request.params.userId;

    var User = Parse.Object.extend('_User'),
    user = new User({ objectId: userId });

    user.set('isBlocked', true);

    Parse.Cloud.useMasterKey();
    user.save(null, { useMasterKey: true } ).then(function(user) {
        response.success(user);
    }, function(error) {
        response.error(error)
    });
});

Additionally, here is the Swift 3 code snippet to invoke the blockUser function:

    let request = [
        "userId" : userPointer.objectId!
    ] as [String : Any]

    PFCloud.callFunction(inBackground: "blockUser", withParameters: request as [String : Any], block: { (results, error) in
     if error == nil {
          print ("\(userPointer["username"]!) has been successfully blocked!")
     // handle error
     } else {
         print ("\(error!.localizedDescription)")
   }})

Answer №2

It appears that you haven't refreshed your main.js (the file in which you write cloud code functions) on the server.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alter regular expression matches within the new string replacement

I am having an issue with using regex to extract URLs from a text and then modifying all the matches within the replacement string using a function. Below is a simplified example of what I am trying to accomplish. Is it possible to achieve something lik ...

Dependency injection of an Angular app factory toaster is causing the application to malfunction

I am currently working on an Angular application that utilizes Firebase as its backend. My goal is to inject 'toaster' as a dependency within my authorization app factory. Below is the initial setup of the app.factory: app.factory('principa ...

Issue with Vue.js: Difficulty sending an array of values to an endpoint

I am currently in the process of learning Vue in order to complete my project, which has a Java Spring backend. The endpoint I am working with expects an object with the following values: LocalDate date; Long buyerId; Long supplierId; List<OrderDetails ...

How can I calculate the total sum of values in an array retrieved from an API call?

Within the array this.state.companiesIncome, I've got 50 objects each containing a {value and date}. However, when attempting to retrieve this.state.companiesIncome[2].value, I'm encountering an error stating: TypeError: Cannot read property &apo ...

What is the best method to retrieve information from a nested JSON array?

Whenever a user submits data, I receive it in a nested JSON array format and I must extract that information. For example, the data could range from question_1 to question_5 in one submission, and then from question_1 to question_9 in another submission. ...

Show only the populated fields in a user profile with ReactJS

Purpose Showcasing only completed fields. Context In my app, users fill out an application with fields like "early reg fee, early reg date, regular reg fee, regular reg date". After completing all the information and clicking "view profile", they should ...

Prevent users from changing dropdown options after a form submission fails using Javascript and Jquery

Currently, I am pursuing the tech degree at Team Treehouse and my third project involves creating an interactive form. To simplify my issue, I will outline it in bullet points: The credit card payment method should be preselected when the page loads. I n ...

Guide on utilizing direction.set within threejs for Vector3 types

In the code below, I have defined a plane, wall, and a character. Now, I am trying to set the direction using vector3(). However, I seem to be encountering an issue. Whenever I press the left or right arrow key on the keyboard, I keep receiving the follow ...

403 Forbidden error encountered while making a REST API call using jQuery AJAX

Attempting to create a basic jQuery ajax call to an API Here is the code I'm using: jQuery.ajax({ type: "GET", url: "http://example.com/api/v1/testapi", headers: { "Authorization": "Basic Ylc5aWXXXXXXlk1ucWx5ZnA=" }, success: fu ...

Using jQuery to fetch data asynchronously

I am currently dealing with a web application that needs to carry out the following task. It must send GET requests to a web service for each date within a selected date range, yet this process can be time-consuming. Since I plan to visualize the retrieved ...

jQuery Date-Based Price Countdown Feature

Unfortunately, I am not well-versed in jQuery/JavaScript and I am facing a challenging issue. In essence, there is an upcoming event where the prices of certain fixed items will decrease every minute between two specified dates. For example: 2012 07 25 ...

Tips for looping through client.get from the Twitter API with node.js and express

I am in the process of developing an application that can download a specific number of tweets. For this project, I am utilizing node.js and express() within my server.js file. To retrieve data from the Twitter API, I have set up a route app.get('/ap ...

Creating a Sum Column in a DataTables Editor

https://datatables.net/forums/discussion/45999 Is there a way to create a Total column which sums up three columns (No.1, No.2, No.3)? Here is an example table structure: ------------------------- No1 | No2 | No3 | Total | ------------------------- 4 ...

Inquiring about using React typescript useRef function for improved performance

Creating a reusable hook to manipulate the DOM is the objective. Sample Code: import { useEffect, useRef } from 'react'; function useFocus() { const domRef = useRef<HTMLElement | null>(null); useEffect(() => { domRef.current?.f ...

Navigate divs with varying z-index values

I want to change the z-index of 3 divs by toggling them using jQuery, but I'm not sure how to do it. What I want is to click a button that relates to a specific div and increase the z-index of that div so the content inside it is shown. Currently, all ...

I am unable to deliver an email to the mailbox

Whenever I try to send an email, I encounter an issue. In order to complete the registration process, a confirmation mail needs to be sent. The error message that I receive is: Callback must be a function at maybeCallback const fs = require(& ...

Looking to enhance the accessibility of a dynamically generated file by implementing the ability to expand and collapse sections as parent nodes

Currently working on a webpage where I am showcasing a testsuite file as the parent node and test cases within the testsuite file as child nodes. I have added checkboxes to both the parent and child nodes. Now, my goal is to include an ex ...

What steps do I need to take to ensure my app shows an error message instead of the broken image link?

function getDogImage(breed) { fetch(`https://dog.ceo/api/breed/${breed}/images/random`) .then(response => response.json()) .then(responseJson => displayResults(responseJson)) .catch(error => alert('Something went wrong. T ...

Ensure that a component does not receive a value if the string is equal to an empty string

When passing values to my component, I encountered an issue where some values were empty (""). This resulted in a visual container appearing empty on my view. To resolve this, I need the value not to pass at all if it equals "". <AddIntel initialValues ...

Form with a dropdown menu and a button to duplicate the dropdown menu

In my form, I have a simple setup where user names are listed, and for each user, there is a drop-down box displaying items that can be assigned to them. To facilitate the assignment of multiple items to a user, I want to implement a feature where a "add a ...