Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unify and cleanup cache.js. #694

Merged
merged 5 commits into from
Feb 29, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions spec/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ delete defaultConfiguration.cloud;

// Allows testing specific configurations of Parse Server
var setServerConfiguration = configuration => {
api = new ParseServer(configuration);
server.close();
cache.clearCache();
app = express();
api = new ParseServer(configuration);
app.use('/1', api);
cache.clearCache();
server.close();
server = app.listen(port);
}
};

var restoreServerConfiguration = () => setServerConfiguration(defaultConfiguration);

Expand Down
6 changes: 3 additions & 3 deletions src/Auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function nobody(config) {

// Returns a promise that resolves to an Auth object
var getAuthForSessionToken = function(config, sessionToken) {
var cachedUser = cache.getUser(sessionToken);
var cachedUser = cache.users.get(sessionToken);
if (cachedUser) {
return Promise.resolve(new Auth(config, false, cachedUser));
}
Expand All @@ -65,8 +65,8 @@ var getAuthForSessionToken = function(config, sessionToken) {
delete obj.password;
obj['className'] = '_User';
obj['sessionToken'] = sessionToken;
var userObject = Parse.Object.fromJSON(obj);
cache.setUser(sessionToken, userObject);
let userObject = Parse.Object.fromJSON(obj);
cache.users.set(sessionToken, userObject);
return new Auth(config, false, userObject);
});
};
Expand Down
9 changes: 3 additions & 6 deletions src/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@ import cache from './cache';
export class Config {
constructor(applicationId: string, mount: string) {
let DatabaseAdapter = require('./DatabaseAdapter');

let cacheInfo = cache.apps[applicationId];
this.valid = !!cacheInfo;
if (!this.valid) {
let cacheInfo = cache.apps.get(applicationId);
if (!cacheInfo) {
return;
}

this.applicationId = applicationId;
this.collectionPrefix = cacheInfo.collectionPrefix || '';
this.masterKey = cacheInfo.masterKey;
this.clientKey = cacheInfo.clientKey;
this.javascriptKey = cacheInfo.javascriptKey;
Expand All @@ -25,7 +22,7 @@ export class Config {
this.facebookAppIds = cacheInfo.facebookAppIds;
this.enableAnonymousUsers = cacheInfo.enableAnonymousUsers;
this.allowClientClassCreation = cacheInfo.allowClientClassCreation;
this.database = DatabaseAdapter.getDatabaseConnection(applicationId, this.collectionPrefix);
this.database = DatabaseAdapter.getDatabaseConnection(applicationId, cacheInfo.collectionPrefix);
this.hooksController = cacheInfo.hooksController;
this.filesController = cacheInfo.filesController;
this.pushController = cacheInfo.pushController;
Expand Down
2 changes: 1 addition & 1 deletion src/Routers/UsersRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class UsersRouter extends ClassesRouter {
}

let user;
return req.database.find('_User', { username: req.body.username })
return req.config.database.find('_User', { username: req.body.username })
.then((results) => {
if (!results.length) {
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Invalid username/password.');
Expand Down
58 changes: 24 additions & 34 deletions src/cache.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,35 @@
export var apps = {};
export var stats = {};
export var isLoaded = false;
export var users = {};
/** @flow weak */

export function getApp(app, callback) {
if (apps[app]) return callback(true, apps[app]);
return callback(false);
export function CacheStore<KeyType, ValueType>() {
let dataStore: {[id:KeyType]:ValueType} = {};
return {
get: (key: KeyType): ValueType => {
return dataStore[key];
},
set(key: KeyType, value: ValueType): void {
dataStore[key] = value;
},
remove(key: KeyType): void {
delete dataStore[key];
},
clear(): void {
dataStore = {};
}
};
}

export function updateStat(key, value) {
stats[key] = value;
}

export function getUser(sessionToken) {
if (users[sessionToken]) return users[sessionToken];
return undefined;
}

export function setUser(sessionToken, userObject) {
users[sessionToken] = userObject;
}

export function clearUser(sessionToken) {
delete users[sessionToken];
}
const apps = CacheStore();
const users = CacheStore();

//So far used only in tests
export function clearCache() {
apps = {};
stats = {};
users = {};
export function clearCache(): void {
apps.clear();
users.clear();
}

export default {
apps,
stats,
isLoaded,
getApp,
updateStat,
clearUser,
getUser,
setUser,
users,
clearCache,
CacheStore
};
13 changes: 3 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ function ParseServer({
const loggerController = new LoggerController(loggerControllerAdapter);
const hooksController = new HooksController(appId, collectionPrefix);

cache.apps[appId] = {
cache.apps.set(appId, {
masterKey: masterKey,
collectionPrefix: collectionPrefix,
clientKey: clientKey,
Expand All @@ -142,11 +142,11 @@ function ParseServer({
enableAnonymousUsers: enableAnonymousUsers,
allowClientClassCreation: allowClientClassCreation,
oauth: oauth
};
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use es6 style { masterKey, collectionPrefix...}


// To maintain compatibility. TODO: Remove in v2.1
if (process.env.FACEBOOK_APP_ID) {
cache.apps[appId]['facebookAppIds'].push(process.env.FACEBOOK_APP_ID);
cache.apps.get(appId)['facebookAppIds'].push(process.env.FACEBOOK_APP_ID);
}

// This app serves the Parse API directly.
Expand Down Expand Up @@ -220,13 +220,6 @@ function addParseCloud() {
global.Parse = Parse;
}

function getClassName(parseClass) {
if (parseClass && parseClass.className) {
return parseClass.className;
}
return parseClass;
}

module.exports = {
ParseServer: ParseServer,
S3Adapter: S3Adapter
Expand Down
15 changes: 6 additions & 9 deletions src/middlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function handleParseHeaders(req, res, next) {

var fileViaJSON = false;

if (!info.appId || !cache.apps[info.appId]) {
if (!info.appId || !cache.apps.get(info.appId)) {
// See if we can find the app id on the body.
if (req.body instanceof Buffer) {
// The only chance to find the app id is if this is a file
Expand All @@ -44,12 +44,10 @@ function handleParseHeaders(req, res, next) {
fileViaJSON = true;
}

if (req.body && req.body._ApplicationId
&& cache.apps[req.body._ApplicationId]
&& (
!info.masterKey
||
cache.apps[req.body._ApplicationId]['masterKey'] === info.masterKey)
if (req.body &&
req.body._ApplicationId &&
cache.apps.get(req.body._ApplicationId) &&
(!info.masterKey || cache.apps.get(req.body._ApplicationId).masterKey === info.masterKey)
) {
info.appId = req.body._ApplicationId;
info.javascriptKey = req.body._JavaScriptKey || '';
Expand Down Expand Up @@ -84,9 +82,8 @@ function handleParseHeaders(req, res, next) {
req.body = new Buffer(base64, 'base64');
}

info.app = cache.apps[info.appId];
info.app = cache.apps.get(info.appId);
req.config = new Config(info.appId, mount);
req.database = req.config.database;
req.info = info;

var isMaster = (info.masterKey === req.config.masterKey);
Expand Down
4 changes: 2 additions & 2 deletions src/requiredParameter.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/* @flow */
export default (errorMessage: string) => {throw errorMessage}
/** @flow */
export default (errorMessage: string): any => { throw errorMessage }
2 changes: 1 addition & 1 deletion src/rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function del(config, auth, className, objectId) {
.then((response) => {
if (response && response.results && response.results.length) {
response.results[0].className = className;
cache.clearUser(response.results[0].sessionToken);
cache.users.remove(response.results[0].sessionToken);
inflatedObject = Parse.Object.fromJSON(response.results[0]);
return triggers.maybeRunTrigger(triggers.Types.beforeDelete, auth, inflatedObject, null, config.applicationId);
}
Expand Down
11 changes: 6 additions & 5 deletions src/testing-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@ var router = express.Router();
// creates a unique app in the cache, with a collection prefix
function createApp(req, res) {
var appId = cryptoUtils.randomHexString(32);
cache.apps[appId] = {
// TODO: (nlutsenko) This doesn't work and should die, since there are no controllers on this configuration.
cache.apps.set(appId, {
'collectionPrefix': appId + '_',
'masterKey': 'master'
};
});
var keys = {
'application_id': appId,
'client_key': 'unused',
Expand All @@ -31,7 +32,7 @@ function clearApp(req, res) {
if (!req.auth.isMaster) {
return res.status(401).send({"error": "unauthorized"});
}
req.database.deleteEverything().then(() => {
return req.config.database.deleteEverything().then(() => {
res.status(200).send({});
});
}
Expand All @@ -41,8 +42,8 @@ function dropApp(req, res) {
if (!req.auth.isMaster) {
return res.status(401).send({"error": "unauthorized"});
}
req.database.deleteEverything().then(() => {
delete cache.apps[req.config.applicationId];
return req.config.database.deleteEverything().then(() => {
cache.apps.remove(req.config.applicationId);
res.status(200).send({});
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/triggers.js
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ export function maybeRunTrigger(triggerType, auth, parseObject, originalParseObj
var response = getResponseObject(request, resolve, reject);
// Force the current Parse app before the trigger
Parse.applicationId = applicationId;
Parse.javascriptKey = cache.apps[applicationId].javascriptKey || '';
Parse.masterKey = cache.apps[applicationId].masterKey;
Parse.javascriptKey = cache.apps.get(applicationId).javascriptKey || '';
Parse.masterKey = cache.apps.get(applicationId).masterKey;
trigger(request, response);
});
};
Expand Down