Search code examples
javascriptparse-platformparse-cloud-code

How to run a Parse background job locally


I'm trying to run a Parse background job locally instead of the Parse cloud. And I need the Node SDK because the browser SDK doesn't support use of the master key which this job needs.

Here is what I have tried in order to run the job locally :

var Parse = require('parse-cloud-express').Parse;

Parse.Cloud.job("myBackgroundJob", function(request, status) {

    status.success("Hello world!");

});

I have 2 issues :

  1. I don't know how to actually run the job. I think the Parse.Cloud.job call only registers it. And I probably need to initialise the SDK (with API keys) in some way but I don't know how.
  2. When I run this code it outputs Running jobs is not supported in parse-cloud-express, which leads me to believe that I might not be able to make it work this way.

Solution

  • Turns out it was much easier than I thought. I'll still post my solution in case it helps someone.

    In order for it to work, you need a job called myBackgroundJob registered inside a myBackgroundJobFile.js file. You also need a params.json file containing the job parameters.

    I'm using eval() instead of require because it allows me to use the file as is (meaning this file can also be used on Parse without modification).

    var fs = require('fs');
    var Parse = require('parse/node').Parse;
    var BackgroundJobs = {}
    
    var JobRequest = function (params) {
        this.params = params;
    };
    var JobStatus = function () {};
    JobStatus.prototype.error = function () {};
    JobStatus.prototype.message = function () {};
    JobStatus.prototype.success = function () {};
    
    Parse.Cloud.job = function (jobName, jobCall) {
        BackgroundJobs[jobName] = jobCall;
    };
    function callBackgroundJob(jobName, params) {
        var jobCall = BackgroundJobs[jobName];
        if (!jobCall) {
            console.error("There is no registered background job named `" + jobName + "`.");
            return Parse.Promise.error();
        } else {
            var request = new JobRequest(params);
            var status = new JobStatus();
            return jobCall(request, status);
        }
    }
    
    eval(fs.readFileSync('myBackgroundJobFile.js').toString());
    
    Parse._initialize("APPLICATION_ID", "JAVASCRIPT_KEY", "MASTER_KEY");
    Parse.Cloud.useMasterKey();
    
    var params = JSON.parse(fs.readFileSync('params.json', 'utf8'));
    callBackgroundJob("myBackgroundJob", params);