Skip to content

Commit

Permalink
Adds basic tests
Browse files Browse the repository at this point in the history
  • Loading branch information
flovilmart committed Sep 3, 2016
1 parent 543224e commit 759fa1a
Show file tree
Hide file tree
Showing 3 changed files with 213 additions and 100 deletions.
107 changes: 107 additions & 0 deletions spec/ParseServerRESTController.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const ParseServerRESTController = require('../src/ParseServerRESTController').ParseServerRESTController;
const ParseServer = require('../src/ParseServer').default;
let RESTController;

describe('ParseServerRESTController', () => {

beforeEach(() => {
RESTController = ParseServerRESTController(Parse.applicationId, ParseServer.promiseRouter({appId: Parse.applicationId}));
})

it('should handle a get request', (done) => {
RESTController.request("GET", "/classes/MyObject").then((res) => {
expect(res.results.length).toBe(0);
done();
}, (err) => {
console.log(err);
jfail(err);
done();
});
});

it('should handle a get request with full serverURL mount path', (done) => {
RESTController.request("GET", "/1/classes/MyObject").then((res) => {
expect(res.results.length).toBe(0);
done();
}, (err) => {
jfail(err);
done();
});
});

it('should handle a POST batch', (done) => {
RESTController.request("POST", "batch", {
requests: [
{
method: 'GET',
path: '/classes/MyObject'
},
{
method: 'POST',
path: '/classes/MyObject',
body: {"key": "value"}
},
{
method: 'GET',
path: '/classes/MyObject'
}
]
}).then((res) => {
expect(res.length).toBe(3);
done();
}, (err) => {
jfail(err);
done();
});
});

it('should handle a POST request', (done) => {
RESTController.request("POST", "/classes/MyObject", {"key": "value"}).then((res) => {
return RESTController.request("GET", "/classes/MyObject");
}).then((res) => {
expect(res.results.length).toBe(1);
expect(res.results[0].key).toEqual("value");
done();
}).fail((err) => {
console.log(err);
jfail(err);
done();
});
});

it('ensures sessionTokens are properly handled', (done) => {
let userId;
Parse.User.signUp('user', 'pass').then((user) => {
userId = user.id;
let sessionToken = user.getSessionToken();
return RESTController.request("GET", "/users/me", undefined, {sessionToken});
}).then((res) => {
// Result is in JSON format
expect(res.objectId).toEqual(userId);
done();
}).fail((err) => {
console.log(err);
jfail(err);
done();
});
});

it('ensures masterKey is properly handled', (done) => {
let userId;
Parse.User.signUp('user', 'pass').then((user) => {
userId = user.id;
let sessionToken = user.getSessionToken();
return Parse.User.logOut().then(() => {
console.log('Sending request');
return RESTController.request("GET", "/classes/_User", undefined, {useMasterKey: true});
});
}).then((res) => {
expect(res.results.length).toBe(1);
expect(res.results[0].objectId).toEqual(userId);
done();
}, (err) => {
jfail(err);
done();
});
});
});
44 changes: 24 additions & 20 deletions src/ParseServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,29 @@ class ParseServer {
api.use(bodyParser.json({ 'type': '*/*' , limit: maxUploadSize }));
api.use(middlewares.allowMethodOverride);

let appRouter = ParseServer.promiseRouter({ appId });
api.use(appRouter.expressRouter());

api.use(middlewares.handleParseErrors);

//This causes tests to spew some useless warnings, so disable in test
if (!process.env.TESTING) {
process.on('uncaughtException', (err) => {
if ( err.code === "EADDRINUSE" ) { // user-friendly message for this common error
console.error(`Unable to listen on port ${err.port}. The port is already in use.`);
process.exit(0);
} else {
throw err;
}
});
}
if (process.env.PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS === '1') {
Parse.CoreManager.setRESTController(ParseServerRESTController(appId, appRouter));
}
return api;
}

static promiseRouter({appId}) {
let routers = [
new ClassesRouter(),
new UsersRouter(),
Expand Down Expand Up @@ -303,26 +326,7 @@ class ParseServer {
appRouter.use(middlewares.handleParseHeaders);

batch.mountOnto(appRouter);

api.use(appRouter.expressRouter());

api.use(middlewares.handleParseErrors);

//This causes tests to spew some useless warnings, so disable in test
if (!process.env.TESTING) {
process.on('uncaughtException', (err) => {
if ( err.code === "EADDRINUSE" ) { // user-friendly message for this common error
console.error(`Unable to listen on port ${err.port}. The port is already in use.`);
process.exit(0);
} else {
throw err;
}
});
}
if (process.env.PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS === '1') {
Parse.CoreManager.setRESTController(ParseServerRESTController(appId, appRouter));
}
return api;
return appRouter;
}

static createLiveQueryServer(httpServer, config) {
Expand Down
162 changes: 82 additions & 80 deletions src/ParseServerRESTController.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,95 +2,97 @@ const Config = require('./Config');
const Auth = require('./Auth');
const RESTController = require('parse/lib/node/RESTController');
const URL = require('url');
import { logger } from './logger';
const Parse = require('parse/node');

export function ParseServerRESTController(applicationId, router) {
function getSessionToken(options) {
if (options && typeof options.sessionToken === 'string') {
return Parse.Promise.as(options.sessionToken);
}
return Parse.Promise.as(null);
}

function getAuth(options, config) {
if (options.useMasterKey) {
return Parse.Promise.as(new Auth.Auth({config, isMaster: true }));
}
return getSessionToken(options).then((sessionToken) => {
if (sessionToken) {
options.sessionToken = sessionToken;
return Auth.getAuthForSessionToken({
config,
sessionToken: sessionToken
});
} else {
return Parse.Promise.as(new Auth.Auth({ config }));
}
})
}

function ParseServerRESTController(applicationId, router) {
function handleRequest(method, path, data = {}, options = {}) {
let args = arguments;
if (path == 'batch') {
let promises = data.requests.map((request) => {
return handleRequest(request.method, request.path, request.body, options).then((response) => {
return Parse.Promise.as({success: response});
}, (error) => {
return Parse.Promise.as({error: {code: error.code, error: error.message}});
});
});
return Parse.Promise.all(promises);
}
// Store the arguments, for later use if internal fails
let args = arguments;

let config = new Config(applicationId);
let serverURL = URL.parse(config.serverURL);
if (path.indexOf(serverURL.path) === 0) {
path = path.slice(serverURL.path.length, path.length);
}

let config = new Config(applicationId);
let serverURL = URL.parse(config.serverURL);
if (path.indexOf(serverURL.path) === 0) {
path = path.slice(serverURL.path.length, path.length);
}
if (path[0] !== "/") {
path = "/" + path;
}

if (path[0] !== "/") {
path = "/" + path;
}
if (path === '/batch') {
let promises = data.requests.map((request) => {
return handleRequest(request.method, request.path, request.body, options).then((response) => {
return Parse.Promise.as({success: response});
}, (error) => {
return Parse.Promise.as({error: {code: error.code, error: error.message}});
});
});
return Parse.Promise.all(promises);
}

function getSessionToken(options) {
if (options && typeof options.sessionToken === 'string') {
return Parse.Promise.as(options.sessionToken);
}
return Parse.Promise.as(null);
}
let query;
if (method === 'GET') {
query = data;
}

function getAuth(options, config) {
if (options.useMasterKey) {
return Parse.Promise.as(new Auth.Auth({config, isMaster: true }));
}
return getSessionToken(options).then((sessionToken) => {
if (sessionToken) {
options.sessionToken = sessionToken;
return Auth.getAuthForSessionToken({
config,
sessionToken: sessionToken
});
return new Parse.Promise((resolve, reject) => {
getAuth(options, config).then((auth) => {
let request = {
body: data,
config,
auth,
info: {
applicationId: applicationId,
sessionToken: options.sessionToken
},
query
};
return Promise.resolve().then(() => {
return router.tryRouteRequest(method, path, request);
}).then((response) => {
resolve(response.response, response.status, response);
}, (err) => {
if (err instanceof Parse.Error &&
err.code == Parse.Error.INVALID_JSON &&
err.message == `cannot route ${method} ${path}`) {
RESTController.request.apply(null, args).then(resolve, reject);
} else {
return Parse.Promise.as(new Auth.Auth({ config }));
reject(err);
}
})
}

let query;
if (method === 'GET') {
query = data;
}

return new Parse.Promise((resolve, reject) => {
getAuth(options, config).then((auth) => {
let request = {
body: data,
config,
auth,
info: {
applicationId: applicationId,
sessionToken: options.sessionToken
},
query
};
return Promise.resolve().then(() => {
return router.tryRouteRequest(method, path, request);
}).then((response) => {
resolve(response.response, response.status, response);
}, (err) => {
if (err instanceof Parse.Error &&
err.code == Parse.Error.INVALID_JSON &&
err.message == `cannot route ${method} ${path}`) {
RESTController.request.apply(null, args).then(resolve, reject);
} else {
reject(err);
}
});
}, reject);
});

};
});
}, reject);
});
};

return {
request: handleRequest,
ajax: function() {
return RESTController.ajax.apply(null, arguments);
}
ajax: RESTController.ajax
};
};
};

export default ParseServerRESTController;
export { ParseServerRESTController };

0 comments on commit 759fa1a

Please sign in to comment.