Invalid Function Error when running Cloud Function of Parse Server on back4app - parse-cloud-code

The error code is below:
{"code":141,"message":"Invalid function: \"test\""}
main.js
Parse.Cloud.define('test', function(request, response){
response.success('OK');
}, function(error){
response.error(error);
});
app.js
app.get('/test', function(req, res){
Parse.Cloud.run('test', null).then(function(result){
return res.send(result);
}, function(error){
return res.status(400).send(error);
});
});
The Cloud Function defined in main.js does not work or isn't called successfully. Are there any dependencies missing to be declared in main.js in order to run on back4app or what?

From what I could understand regarding Back4App's Cloud Code functions you won't need to have that "function(error)" within your main.js. The error treatment will be represented as an error code in your logs when the function present a problem.
I've done some tests and I'd update your example of main.js to be simple like this:
Parse.Cloud.define('test', function(request, response){
response.success('OK');
});
Then your app.js would be valid and you could call that function simply by going to your_webhost.back4app.io/test or using REST API.

Related

Rest api implementation with parameter using JetBrains WebStorm + node.js + express

First of all, i'm using JetBrains WebStorm and used to create the Node.js Express App project.
My modifications were at app.js
app.get('/api/restaurants', function(req, res) {
console.log("Parameter[0]", req.params.restaurant_id);
res.json({
'01010112D8139F13': '0ao123r1'
});
});
app.get('/api/restaurants/:id', function(req, res) {
console.log("Parameter[1]", req.params.restaurant_id);
res.json({
'message': 'worked?'
});
});
I'm using postman plugin at chrome to test my api and i can't access localhost:3000/api/restaurants?restaurant_id=01010112D8139F13 without being routed by router.route('/restaurants') instead of router.route('/restaurants/:restaurant_id')
At console i have:
GET /api/restaurants?id=01010112D8139F13 200 1.803 ms - 31
If anyone can help me, thanks in advance.
restaurant_id is not a query parameter but a variable part in your path. For example /restaurants/01010112 and /restaurants/1 are both handled by the same Web request handler because both fit on /restaurants/:restaurant_id pattern.
The restaurant specific endpoint need to be modified the following way:
app.get('/api/restaurants/:id', function(req, res) {
console.log("Parameter[1]", req.params.id);
res.json({
'message': 'worked?'
});
});
And use the following url on the console:
/api/restaurants/01010112D8139F13

How can I get stack traces from restify when I have errors in my code?

Let's say I've defined the following restify endpoint:
server.get('/test/1', function (req, res, next) {
undefinedFunctionCall(); // Will cause exception
return next();
}
How can I get a stack trace in my server console which tells me that undefinedFunctionCall is undefined? The client gets it but not the server.
I've read in the docs that you can listen to the event InternalServerError and InternalError, but none of the fire when I test. What must I do?
Code:
server.on('InternalServerError', function (req, res, err, cb) {
console.log('INTERNAL ERROR!'); // Never executed
return cb();
});
I'm running Restify 4.0.0 on node 0.10.33 on Windows 10
Hm, this seems to have changed with version 4.0.0. I'm still on version 0.10 and the stack trace is automatically output to the server console.
However, try this solution that I gleaned from this post. I tried it and it works for me.
server.on('uncaughtException', function (req, res, err, cb) {
console.log(err);
return cb();
});
It's not exactly the same as the server dies, but at least you're getting a stack trace.

How to exit from a stack of middleware in Express.js

I am working a REST web application backend and I got some problem when linking my middleware together.
For example, the stack of the middlewares that each request has to go through is like [before1, service, after1], and here's the code for the middleware "before1", this is just the code I used for testing:
'use strict';
var express = require('express');
var router = express.Router();
router.use(function(request, response, next){
console.log('This is middleware BEFORE1');
var success = true
if (!success){
// Go the logging middleware underneath
next();
}
else{
// Go to the 'service' middleware
next('route');
}
})
router.use(function(request, response, next){
console.log('This is middleware LOGGING');
response.sendStatus(400);
response.end();
})
module.exports = router;
The above code is simply saying if the 'before1' succeeds, it should go straight to call 'service' middleware, and otherwise go to the logging middleware underneath and end the request. But my problem is that I can't figure out a way that it could skip the logging middleware, I searched and found next('route') could help, but it didn't work here. What have I missed?
Thanks in advance!
EDIT:
Or more preferably, it's the best if I can issue an error in any of my middleware and handle all types of errors properly using a error handler middleware.
The skeleton of my top level code is the following:
// An array of middleware to be executed asynchronously
operations = [before1, service, before2];
async.series(operations, function(err) {
if(err) {
// one of the functions passed back an error so handle it here
console.log('Handling error!!!!');
res.end();
// return next(err);
}
console.log('middleware get executed');
// no errors so pass control back to express
next();
});
But I am not sure How should change my middlewares accordingly in order to do that.
next is a node-style callback, which means fn(err, ..), so your next('route') will only work to invoke errorhandlers.
You can implement your series directly by supplying an array of functions to the route, and using an express error handler as the catch all (see http://expressjs.com/guide/error-handling.html)

Returning/getting object from a module in nodejs mongodb

I am working on a nodejs app.
Folder structure is
app
app.js
package.json
../model/schema.js
../controller/controller.js
../views
All the logic is in controller.js while app.js performing routing itself....
I want to know how to get/return data(object) from controller.js to app.js.
I am using 'return' to send mongodb document from controller to app but its undefined.
Heres code of app.js..i have removed unneccessary code
var express = require('express'),
app = express.createServer(express.logger()),
io = require('socket.io').listen(app),
routes = require('./routes');
var controller=require('./controller/controller');
var model=require('./model/schema');
app.get("/", function(req, res) {
res.render("chatroom.html");
});
io.sockets.on('connection', function (socket) {
socket.on('login',function(user)
{
var onliner=controller.loginUser(user);
console.log("Onlinersss: ",onliner);
});
socket.on('registerUser',function(user){
controller.registerUser(user);
});
});
Heres controller.js code:
var model=require('../model/schema');
exports.loginUser=function(user)
{
model.registerUser.findOne({uname:user.uname,pass:user.pass},function(err,doc){
if(!err){
console.log("Here loggedin: ",doc);
return doc;
}
else
console.log("Invalid username or password");
});
};
I've just pushed a project to GitHub that uses pretty much the same libraries and RethinkDB as the database (very similar to MongoDB). Basically you need to pass callbacks to your controller and have them invoked with the data retrieved from the DB. Take a look at app.js and lib/db.js in the linked project.
JavaScript (and therefore node.js) is asynchronous. When you 'return doc' the anonymous function defined at function(err, doc) is returned... not the function loginUser that you are trying to get data from.
loginUser returns immediately, and it returns undefined (since you don't specify anything else). To see what I mean, put 'return true;' as the last line in loginUser and you'll notice that you get the value back of 'true.'
However, you don't want to return a value. You want to callback with a value. That's beyond the scope of a stackoverflow answer, so here is a good resource:
http://bjouhier.wordpress.com/2011/01/09/asynchronous-javascript-the-tale-of-harry/

How to handle code exceptions in node.js?

I went through the documentation of Express, and the part describing error handling is completely opaque to me.
I figured the app they're referring to is an instance createServer(), right? But I have no clue how to stop node.js from blowing up the application process when an exception occurs during handling a request.
I don't need anything fancy really; I just want to return a status of 500, plus an otherwise empty response, whenever there's an exception. The node process must not terminate just because there was an uncaught exception somewhere.
Is there a simple example of how to achieve this?
var express = require('express');
var http = require('http');
var app = express.createServer();
app.get('/', function(req, res){
console.log("debug", "calling")
var options = {
host: 'www.google.com',
port: 80,
path: "/"
};
http.get(options, function(response) {
response.on("data", function(chunk) {
console.log("data: " + chunk);
chunk.call(); // no such method; throws here
});
}).on('error', function(e) {
console.log("error connecting" + e.message);
});
});
app.configure(function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.listen(3000);
crashes the entire app, producing traceback
mypath/tst.js:16
chunk.call(); // no such method; throws here
^ TypeError: Object ... has no method 'call'
at IncomingMessage.<anonymous> (/Library/WebServer/Documents/discovery/tst.js:16:18)
at IncomingMessage.emit (events.js:67:17)
at HTTPParser.onBody (http.js:115:23)
at Socket.ondata (http.js:1150:24)
at TCP.onread (net.js:374:27)
If you really want to catch all exceptions and provide some handling other than exiting the Node.js process, you need to handle Node's uncaughtException event.
If you think about it, this is a Node thing, and not an Express thing, because if you throw an exception from some arbitrary piece of code, there's no guarantee Express can or will ever see it, or be in a position to trap it. (Why? Exceptions don't interact very well with asynchronous event-driven callbacky code that is the Node style. Exceptions travel up the call stack to find a catch() block that's in scope at the time the exception is thrown. If myFunction defers some work to a callback function that runs when some event happens, then return to the event loop, then when that callback function is invoked, it's invoked directly from the main event loop, and myFunction is no longer on the call stack; if this callback function throws an exception, even if myFunction has a try/catch block, it's not going to catch the exception.)
What this means in practice is that if you throw an exception and don't catch it yourself and you do so in a function that was directly called by Express, Express can catch the exception and call the error handler you've installed, assuming you've configured some piece of error-handling middleware like app.use(express.errorHandler()). But if you throw the same exception in a function that was called in response to an asynchronous event, Express won't be able to catch it. (The only way it could catch it is by listening for the global Node uncaughtException event, which would be a bad idea first because that's global and you might need to use it for other things, and second because Express will have no idea what request was associated with the exception.)
Here's an example. I add this snippet of route-handling code to an existing Express app:
app.get('/fail/sync', function(req, res) {
throw new Error('whoops');
});
app.get('/fail/async', function(req, res) {
process.nextTick(function() {
throw new Error('whoops');
});
});
Now if I visit http://localhost:3000/fail/sync in my browser, the browser dumps a call stack (showing express.errorHandler in action). If I visit http://localhost:3000/fail/async in my browser, however, the browser gets angry (Chrome shows a "No data received: Error 324, net::ERR_EMPTY_RESPONSE: The server closed the connection without sending any data" message), because the Node process has exited, showing a backtrace on stdout in the terminal where I invoked it.
To be able to catch asynchronous errors I use domain. With Express you can try this code:
function domainWrapper() {
return function (req, res, next) {
var reqDomain = domain.create();
reqDomain.add(req);
reqDomain.add(res);
res.on('close', function () {
reqDomain.dispose();
});
reqDomain.on('error', function (err) {
next(err);
});
reqDomain.run(next)
}
}
app.use(domainWrapper());
//all your other app.use
app.use(express.errorHandler());
This code will make your asynchronous error be captured and sent to your error handler. In this example I use the express.errorHandler, but it works with any handler.
For more information about domain: http://nodejs.org/api/domain.html
You can use the default error handler that express uses, which is actually connect error handler.
var app = require('express').createServer();
app.get('/', function(req, res){
throw new Error('Error thrown here!');
});
app.configure(function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.listen(3000);
Update
For your code, you actually need to capture the error and pass it to express like this
var express = require('express');
var http = require('http');
var app = express.createServer();
app.get('/', function (req, res, next) {
console.log("debug", "calling");
var options = {
host:'www.google.com',
port:80,
path:"/"
};
http.get(options,
function (response) {
response.on("data", function (chunk) {
try {
console.log("data: " + chunk);
chunk.call(); // no such method; throws here
}
catch (err) {
return next(err);
}
});
}).on('error', function (e) {
console.log("error connecting" + e.message);
});
});
app.configure(function () {
app.use(express.errorHandler({ dumpExceptions:true, showStack:true }));
});
app.listen(3000);
express 5.0.0-alpha.7 came out 27 days ago. With this very specific pre-release version, you can now finally reject a promise inside a request handler and it will be handled properly:
Middleware and handlers can now return promises and if the promise is rejected, next(err) will be called with err being the value of the rejection. (source)
For example:
app.get('/', async () => {
throw new Error();
});
app.use((err, req, res, next) => {
res.status(500).send('unexpected error :(');
});
However, only use this as a fallback. Proper error handling should still happen inside catch-phrases inside the request handlers themselves with proper error status codes.
If you don't catch an uncaught exception in your application, it will crash catastrophically, meaning the server process will exit with non-zero error code, and users will never see any response. If you don't have a process manager like pm2 installed, it will also remain dead. To avoid this, and to catch every possible kind of error like logic errors or programmer errors, you need to place the code in a try-catch block. However, there is a really simple solution that avoids having to have a try-catch block around every single controller function. This article explains how.
Simply install express-async-errors and put this on top of your app.js:
const express = require('express');
require('express-async-errors');
...
Now every possible error in a controller is automatically passed to express error handler, no matter if it's async or sync, even if you write things like null.test. You can define an error handler like the following:
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
});
To make this more useful, you can even define your own error classes that inherits from Error, and throw it anywhere you want in your controllers, and it will be automatically caught by Express. Then check if (err instanceof MyCustomErrorClass) in your error handler to display custom messages in your 500 page.

Resources