Reputation: 4378
Currently I uhhh... sorta built a very large main.js file that includes all of the meat of my cloud code for Parse-Server. It's full of over ~200 individual Parse.Cloud.job("jobName", function(request, status){})
and Parse.Cloud.define("functionName", function(request, response){})
calls, complete with their implementation.
I want to refactor / structure my code more properly in the future, but I'm not really sure the best practice for doing that.
Should my main.js be full of stuff like this:
Parse.Cloud.define("function1", require('../function1.js'));
Parse.Cloud.define("function2", require('../function2.js'));
Parse.Cloud.job("job1", require('../job1.js'));
where I call Parse.Cloud.define/job for every function / job in main.js, and require in line, with individual files being individual functions?
Or is there a way main.js can require my various js files that contain several related functions, and call Parse.Cloud.define/job from within those files?
Would it be better to kinda combine these two:
const module1 = require('../module1.js');
const module2 = require('../module2.js');
Parse.Cloud.define("function1", module1.function1(request, response));
Parse.Cloud.define("function2", module2.function2(request, response));
Parse.Cloud.job("job1", module1.job1(request, status));
Parse.Cloud.job("job2", module2.job2(request, status));
I'm very interested in being pointed to some materials on how best this should be structured. I found a little bit of material about node.js apps in general, but am concerned about the Parse-Server specific aspects, and whether or not Parse.Cloud.define can be called anywhere other than just main.js . I was unable to find any answer for that question in my searching. If you have any examples of public projects utilizing Parse-Server that you think are structured very well, I'd love a look at those as well.
Thanks for any advice you have!
Upvotes: 0
Views: 466
Reputation: 2788
i faced exactly the same situation like you and what i decided to do is to divide my cloud code into modules. I built one module per one class. So let's assume you have the following classes in your project:
Then you need to create user.js, contact.js, communication.js in addition to your main.js file inside your main.js file you need to require those modules. When you require them please notice that you use the right path i recommend you to use nodejs pathmodule.
inside your main.js you can also add some common logic and of course the code which require the other modules from above.
Inside your modules you can create the cloud code events (afterSave,beforeSave etc.) and also the custom cloud code functions. From there you are free to use any method or design pattern that you want (util, classes, functions, closures etc.)
Moreover, i recommend you to use Promises in order to have a clean code.
Hope it helps.
Upvotes: 2