3
votes

I am using parse.com cloud code with express to setup my routes. I have done this in the past with node, and I have my routes in separate files. So, in node I do

app.js

express = require("express"); 
app = exports.app = express();
require("./routes/js/account");

account.js

app = module.parent.exports.app;
app.get("/api/account/twitter", passport.authenticate("twitter"));

All the examples on parses site https://parse.com/docs/cloud_code_guide#webapp show this being done as follows.

app.js

var express = require('express');
var app = express();

app.get('/hello', function(req, res) {
  res.render('hello', { message: 'Congrats, you just set up your app!' });
});

So, I would like to change the bottom to include a routes folder with separate routes files, but am not sure how to do this in parse.

3

3 Answers

4
votes

I know this post is a little old, but I just wanted to post a solution for anyone still looking to get this to work.

What you need to do, is create your route file, I keep them in 'routes' forlder, for example <my_app_dir>/cloud/routes/user.js

Inside user.js you will have something that looks like this:

module.exports = function(app) {

   app.get("/users/login", function(req, res) {
      .. do your custom logic here ..
   });

   app.get("/users/logout", function(req, res) {
      .. do your custom logic here ..
   });
}

Then, in app.js you just include your file, but remember that you need to append cloud to the path, and pass the reference to your app instance:

require('cloud/routes/user')(app);

Also, remember that express evaluates routes in order, so you should take that into consideration when importing several route files.

1
votes

I'm using a different method, have the routes in app.js, but you can probably include them in file if you prefer. Take a look at the example app, anyblog on github

The way it works:

Set up a controller:

// Controller code in separate files.
var postsController = require('cloud/controllers/posts.js');

Add the controller route

// Show all posts on homepage
app.get('/', postsController.index);

// RESTful routes for the blog post object.
app.get('/posts', postsController.index);
app.get('/posts/new', postsController.new);

And then in posts.js, you can use exports, ex.

var Post = Parse.Object.extend('Post');

// Display all posts.
exports.index = function(req, res) {
  var query = new Parse.Query(Post);
  query.descending('createdAt');
  query.find().then(function(results) {
    res.render('posts/index', { 
      posts: results
    });
  },
  function() {
    res.send(500, 'Failed loading posts');
  });
};

// Display a form for creating a new post.
exports.new = function(req, res) {
  res.render('posts/new', {});
};
0
votes

Pass the app reference to the post controller, and add the routes from there