Enable prefer-const lint rule (#3202)
This commit is contained in:
committed by
Florent Vilmart
parent
a6c988176e
commit
ca286b7108
@@ -19,6 +19,7 @@
|
|||||||
"no-trailing-spaces": 2,
|
"no-trailing-spaces": 2,
|
||||||
"eol-last": 2,
|
"eol-last": 2,
|
||||||
"space-in-parens": ["error", "never"],
|
"space-in-parens": ["error", "never"],
|
||||||
"no-multiple-empty-lines": 1
|
"no-multiple-empty-lines": 1,
|
||||||
|
"prefer-const": "error"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ describe('AnalyticsController', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
expect(analyticsAdapter.trackEvent).toHaveBeenCalled();
|
expect(analyticsAdapter.trackEvent).toHaveBeenCalled();
|
||||||
var lastCall = analyticsAdapter.trackEvent.calls.first();
|
var lastCall = analyticsAdapter.trackEvent.calls.first();
|
||||||
let args = lastCall.args;
|
const args = lastCall.args;
|
||||||
expect(args[0]).toEqual('MyEvent');
|
expect(args[0]).toEqual('MyEvent');
|
||||||
expect(args[1]).toEqual({
|
expect(args[1]).toEqual({
|
||||||
dimensions: {
|
dimensions: {
|
||||||
@@ -45,7 +45,7 @@ describe('AnalyticsController', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
expect(analyticsAdapter.appOpened).toHaveBeenCalled();
|
expect(analyticsAdapter.appOpened).toHaveBeenCalled();
|
||||||
var lastCall = analyticsAdapter.appOpened.calls.first();
|
var lastCall = analyticsAdapter.appOpened.calls.first();
|
||||||
let args = lastCall.args;
|
const args = lastCall.args;
|
||||||
expect(args[0]).toEqual({
|
expect(args[0]).toEqual({
|
||||||
dimensions: {
|
dimensions: {
|
||||||
key: 'value',
|
key: 'value',
|
||||||
|
|||||||
@@ -208,7 +208,7 @@ describe('AuthenticationProviers', function() {
|
|||||||
id: 'hello',
|
id: 'hello',
|
||||||
token: 'world'
|
token: 'world'
|
||||||
}
|
}
|
||||||
let adapter = {
|
const adapter = {
|
||||||
validateAppId: function() {
|
validateAppId: function() {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
},
|
},
|
||||||
@@ -220,15 +220,15 @@ describe('AuthenticationProviers', function() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let authDataSpy = spyOn(adapter, 'validateAuthData').and.callThrough();
|
const authDataSpy = spyOn(adapter, 'validateAuthData').and.callThrough();
|
||||||
let appIdSpy = spyOn(adapter, 'validateAppId').and.callThrough();
|
const appIdSpy = spyOn(adapter, 'validateAppId').and.callThrough();
|
||||||
|
|
||||||
let authenticationHandler = authenticationLoader({
|
const authenticationHandler = authenticationLoader({
|
||||||
customAuthentication: adapter
|
customAuthentication: adapter
|
||||||
});
|
});
|
||||||
|
|
||||||
validateAuthenticationHandler(authenticationHandler);
|
validateAuthenticationHandler(authenticationHandler);
|
||||||
let validator = authenticationHandler.getValidatorForProvider('customAuthentication');
|
const validator = authenticationHandler.getValidatorForProvider('customAuthentication');
|
||||||
validateValidator(validator);
|
validateValidator(validator);
|
||||||
|
|
||||||
validator(validAuthData).then(() => {
|
validator(validAuthData).then(() => {
|
||||||
@@ -243,12 +243,12 @@ describe('AuthenticationProviers', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly loads custom adapter module object', (done) => {
|
it('properly loads custom adapter module object', (done) => {
|
||||||
let authenticationHandler = authenticationLoader({
|
const authenticationHandler = authenticationLoader({
|
||||||
customAuthentication: path.resolve('./spec/support/CustomAuth.js')
|
customAuthentication: path.resolve('./spec/support/CustomAuth.js')
|
||||||
});
|
});
|
||||||
|
|
||||||
validateAuthenticationHandler(authenticationHandler);
|
validateAuthenticationHandler(authenticationHandler);
|
||||||
let validator = authenticationHandler.getValidatorForProvider('customAuthentication');
|
const validator = authenticationHandler.getValidatorForProvider('customAuthentication');
|
||||||
validateValidator(validator);
|
validateValidator(validator);
|
||||||
|
|
||||||
validator({
|
validator({
|
||||||
@@ -262,12 +262,12 @@ describe('AuthenticationProviers', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly loads custom adapter module object', (done) => {
|
it('properly loads custom adapter module object', (done) => {
|
||||||
let authenticationHandler = authenticationLoader({
|
const authenticationHandler = authenticationLoader({
|
||||||
customAuthentication: { module: path.resolve('./spec/support/CustomAuthFunction.js'), options: { token: 'valid-token' }}
|
customAuthentication: { module: path.resolve('./spec/support/CustomAuthFunction.js'), options: { token: 'valid-token' }}
|
||||||
});
|
});
|
||||||
|
|
||||||
validateAuthenticationHandler(authenticationHandler);
|
validateAuthenticationHandler(authenticationHandler);
|
||||||
let validator = authenticationHandler.getValidatorForProvider('customAuthentication');
|
const validator = authenticationHandler.getValidatorForProvider('customAuthentication');
|
||||||
validateValidator(validator);
|
validateValidator(validator);
|
||||||
|
|
||||||
validator({
|
validator({
|
||||||
|
|||||||
@@ -94,7 +94,7 @@ describe('commander additions', () => {
|
|||||||
'PROGRAM_ARG_0': 'arg0ENVValue',
|
'PROGRAM_ARG_0': 'arg0ENVValue',
|
||||||
'PROGRAM_ARG_1': 'arg1ENVValue',
|
'PROGRAM_ARG_1': 'arg1ENVValue',
|
||||||
});
|
});
|
||||||
let options = commander.getOptions();
|
const options = commander.getOptions();
|
||||||
expect(options.arg2).toBe(8888);
|
expect(options.arg2).toBe(8888);
|
||||||
expect(options.arg3).toBe('hello'); //config value
|
expect(options.arg3).toBe('hello'); //config value
|
||||||
expect(options.arg4).toBe('/1');
|
expect(options.arg4).toBe('/1');
|
||||||
@@ -123,7 +123,7 @@ describe('commander additions', () => {
|
|||||||
it('should load config from apps', (done) => {
|
it('should load config from apps', (done) => {
|
||||||
commander.loadDefinitions(testDefinitions);
|
commander.loadDefinitions(testDefinitions);
|
||||||
commander.parse(['node', './CLI.spec.js', './spec/configs/CLIConfigApps.json']);
|
commander.parse(['node', './CLI.spec.js', './spec/configs/CLIConfigApps.json']);
|
||||||
let options = commander.getOptions();
|
const options = commander.getOptions();
|
||||||
expect(options.arg1).toBe('my_app');
|
expect(options.arg1).toBe('my_app');
|
||||||
expect(options.arg2).toBe(8888);
|
expect(options.arg2).toBe(8888);
|
||||||
expect(options.arg3).toBe('hello'); //config value
|
expect(options.arg3).toBe('hello'); //config value
|
||||||
@@ -142,8 +142,8 @@ describe('commander additions', () => {
|
|||||||
|
|
||||||
describe('definitions', () => {
|
describe('definitions', () => {
|
||||||
it('should have valid types', () => {
|
it('should have valid types', () => {
|
||||||
for (let key in definitions) {
|
for (const key in definitions) {
|
||||||
let definition = definitions[key];
|
const definition = definitions[key];
|
||||||
expect(typeof definition).toBe('object');
|
expect(typeof definition).toBe('object');
|
||||||
if (typeof definition.env !== 'undefined') {
|
if (typeof definition.env !== 'undefined') {
|
||||||
expect(typeof definition.env).toBe('string');
|
expect(typeof definition.env).toBe('string');
|
||||||
@@ -161,8 +161,8 @@ describe('definitions', () => {
|
|||||||
|
|
||||||
describe('LiveQuery definitions', () => {
|
describe('LiveQuery definitions', () => {
|
||||||
it('should have valid types', () => {
|
it('should have valid types', () => {
|
||||||
for (let key in liveQueryDefinitions) {
|
for (const key in liveQueryDefinitions) {
|
||||||
let definition = liveQueryDefinitions[key];
|
const definition = liveQueryDefinitions[key];
|
||||||
expect(typeof definition).toBe('object');
|
expect(typeof definition).toBe('object');
|
||||||
if (typeof definition.env !== 'undefined') {
|
if (typeof definition.env !== 'undefined') {
|
||||||
expect(typeof definition.env).toBe('string');
|
expect(typeof definition.env).toBe('string');
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ var ClientSDK = require('../src/ClientSDK');
|
|||||||
|
|
||||||
describe('ClientSDK', () => {
|
describe('ClientSDK', () => {
|
||||||
it('should properly parse the SDK versions', () => {
|
it('should properly parse the SDK versions', () => {
|
||||||
let clientSDKFromVersion = ClientSDK.fromString;
|
const clientSDKFromVersion = ClientSDK.fromString;
|
||||||
expect(clientSDKFromVersion('i1.1.1')).toEqual({
|
expect(clientSDKFromVersion('i1.1.1')).toEqual({
|
||||||
sdk: 'i',
|
sdk: 'i',
|
||||||
version: '1.1.1'
|
version: '1.1.1'
|
||||||
|
|||||||
@@ -180,10 +180,10 @@ describe('Cloud Code', () => {
|
|||||||
|
|
||||||
it('test afterSave ran on created object and returned a promise', function(done) {
|
it('test afterSave ran on created object and returned a promise', function(done) {
|
||||||
Parse.Cloud.afterSave('AfterSaveTest2', function(req) {
|
Parse.Cloud.afterSave('AfterSaveTest2', function(req) {
|
||||||
let obj = req.object;
|
const obj = req.object;
|
||||||
if(!obj.existed())
|
if(!obj.existed())
|
||||||
{
|
{
|
||||||
let promise = new Parse.Promise();
|
const promise = new Parse.Promise();
|
||||||
setTimeout(function(){
|
setTimeout(function(){
|
||||||
obj.set('proof', obj.id);
|
obj.set('proof', obj.id);
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
@@ -195,13 +195,13 @@ describe('Cloud Code', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('AfterSaveTest2');
|
const obj = new Parse.Object('AfterSaveTest2');
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
let query = new Parse.Query('AfterSaveTest2');
|
const query = new Parse.Query('AfterSaveTest2');
|
||||||
query.equalTo('proof', obj.id);
|
query.equalTo('proof', obj.id);
|
||||||
query.find().then(function(results) {
|
query.find().then(function(results) {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let savedObject = results[0];
|
const savedObject = results[0];
|
||||||
expect(savedObject.get('proof')).toEqual(obj.id);
|
expect(savedObject.get('proof')).toEqual(obj.id);
|
||||||
done();
|
done();
|
||||||
},
|
},
|
||||||
@@ -215,10 +215,10 @@ describe('Cloud Code', () => {
|
|||||||
// TODO: Fails on CI randomly as racing
|
// TODO: Fails on CI randomly as racing
|
||||||
xit('test afterSave ignoring promise, object not found', function(done) {
|
xit('test afterSave ignoring promise, object not found', function(done) {
|
||||||
Parse.Cloud.afterSave('AfterSaveTest2', function(req) {
|
Parse.Cloud.afterSave('AfterSaveTest2', function(req) {
|
||||||
let obj = req.object;
|
const obj = req.object;
|
||||||
if(!obj.existed())
|
if(!obj.existed())
|
||||||
{
|
{
|
||||||
let promise = new Parse.Promise();
|
const promise = new Parse.Promise();
|
||||||
setTimeout(function(){
|
setTimeout(function(){
|
||||||
obj.set('proof', obj.id);
|
obj.set('proof', obj.id);
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
@@ -230,12 +230,12 @@ describe('Cloud Code', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('AfterSaveTest2');
|
const obj = new Parse.Object('AfterSaveTest2');
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
|
|
||||||
let query = new Parse.Query('AfterSaveTest2');
|
const query = new Parse.Query('AfterSaveTest2');
|
||||||
query.equalTo('proof', obj.id);
|
query.equalTo('proof', obj.id);
|
||||||
query.find().then(function(results) {
|
query.find().then(function(results) {
|
||||||
expect(results.length).toEqual(0);
|
expect(results.length).toEqual(0);
|
||||||
@@ -247,7 +247,7 @@ describe('Cloud Code', () => {
|
|||||||
|
|
||||||
it('test afterSave rejecting promise', function(done) {
|
it('test afterSave rejecting promise', function(done) {
|
||||||
Parse.Cloud.afterSave('AfterSaveTest2', function() {
|
Parse.Cloud.afterSave('AfterSaveTest2', function() {
|
||||||
let promise = new Parse.Promise();
|
const promise = new Parse.Promise();
|
||||||
setTimeout(function(){
|
setTimeout(function(){
|
||||||
promise.reject("THIS SHOULD BE IGNORED");
|
promise.reject("THIS SHOULD BE IGNORED");
|
||||||
}, 1000);
|
}, 1000);
|
||||||
@@ -255,7 +255,7 @@ describe('Cloud Code', () => {
|
|||||||
return promise;
|
return promise;
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('AfterSaveTest2');
|
const obj = new Parse.Object('AfterSaveTest2');
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
done();
|
done();
|
||||||
}, function(error){
|
}, function(error){
|
||||||
@@ -266,10 +266,10 @@ describe('Cloud Code', () => {
|
|||||||
|
|
||||||
it('test afterDelete returning promise, object is deleted when destroy resolves', function(done) {
|
it('test afterDelete returning promise, object is deleted when destroy resolves', function(done) {
|
||||||
Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) {
|
Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) {
|
||||||
let promise = new Parse.Promise();
|
const promise = new Parse.Promise();
|
||||||
|
|
||||||
setTimeout(function(){
|
setTimeout(function(){
|
||||||
let obj = new Parse.Object('AfterDeleteTestProof');
|
const obj = new Parse.Object('AfterDeleteTestProof');
|
||||||
obj.set('proof', req.object.id);
|
obj.set('proof', req.object.id);
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
promise.resolve();
|
promise.resolve();
|
||||||
@@ -280,19 +280,19 @@ describe('Cloud Code', () => {
|
|||||||
return promise;
|
return promise;
|
||||||
});
|
});
|
||||||
|
|
||||||
let errorHandler = function(error) {
|
const errorHandler = function(error) {
|
||||||
fail(error);
|
fail(error);
|
||||||
done();
|
done();
|
||||||
}
|
}
|
||||||
|
|
||||||
let obj = new Parse.Object('AfterDeleteTest2');
|
const obj = new Parse.Object('AfterDeleteTest2');
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
obj.destroy().then(function(){
|
obj.destroy().then(function(){
|
||||||
let query = new Parse.Query('AfterDeleteTestProof');
|
const query = new Parse.Query('AfterDeleteTestProof');
|
||||||
query.equalTo('proof', obj.id);
|
query.equalTo('proof', obj.id);
|
||||||
query.find().then(function(results) {
|
query.find().then(function(results) {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let deletedObject = results[0];
|
const deletedObject = results[0];
|
||||||
expect(deletedObject.get('proof')).toEqual(obj.id);
|
expect(deletedObject.get('proof')).toEqual(obj.id);
|
||||||
done();
|
done();
|
||||||
}, errorHandler);
|
}, errorHandler);
|
||||||
@@ -302,10 +302,10 @@ describe('Cloud Code', () => {
|
|||||||
|
|
||||||
it('test afterDelete ignoring promise, object is not yet deleted', function(done) {
|
it('test afterDelete ignoring promise, object is not yet deleted', function(done) {
|
||||||
Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) {
|
Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) {
|
||||||
let promise = new Parse.Promise();
|
const promise = new Parse.Promise();
|
||||||
|
|
||||||
setTimeout(function(){
|
setTimeout(function(){
|
||||||
let obj = new Parse.Object('AfterDeleteTestProof');
|
const obj = new Parse.Object('AfterDeleteTestProof');
|
||||||
obj.set('proof', req.object.id);
|
obj.set('proof', req.object.id);
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
promise.resolve();
|
promise.resolve();
|
||||||
@@ -316,18 +316,18 @@ describe('Cloud Code', () => {
|
|||||||
return promise;
|
return promise;
|
||||||
});
|
});
|
||||||
|
|
||||||
let errorHandler = function(error) {
|
const errorHandler = function(error) {
|
||||||
fail(error);
|
fail(error);
|
||||||
done();
|
done();
|
||||||
}
|
}
|
||||||
|
|
||||||
let obj = new Parse.Object('AfterDeleteTest2');
|
const obj = new Parse.Object('AfterDeleteTest2');
|
||||||
obj.save().then(function(){
|
obj.save().then(function(){
|
||||||
obj.destroy().then(function(){
|
obj.destroy().then(function(){
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
|
|
||||||
let query = new Parse.Query('AfterDeleteTestProof');
|
const query = new Parse.Query('AfterDeleteTestProof');
|
||||||
query.equalTo('proof', obj.id);
|
query.equalTo('proof', obj.id);
|
||||||
query.find().then(function(results) {
|
query.find().then(function(results) {
|
||||||
expect(results.length).toEqual(0);
|
expect(results.length).toEqual(0);
|
||||||
@@ -509,7 +509,7 @@ describe('Cloud Code', () => {
|
|||||||
return res.success({});
|
return res.success({});
|
||||||
});
|
});
|
||||||
|
|
||||||
let params = {
|
const params = {
|
||||||
'date': {
|
'date': {
|
||||||
'__type': 'Date',
|
'__type': 'Date',
|
||||||
'iso': '2016-05-22T09:00:00.000Z'
|
'iso': '2016-05-22T09:00:00.000Z'
|
||||||
@@ -616,7 +616,7 @@ describe('Cloud Code', () => {
|
|||||||
res.success();
|
res.success();
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('GameScore');
|
const obj = new Parse.Object('GameScore');
|
||||||
obj.set('foo', 'bar');
|
obj.set('foo', 'bar');
|
||||||
obj.set('fooAgain', 'barAgain');
|
obj.set('fooAgain', 'barAgain');
|
||||||
obj.save().then(() => {
|
obj.save().then(() => {
|
||||||
@@ -703,7 +703,7 @@ describe('Cloud Code', () => {
|
|||||||
request.object.set('foo', 'baz');
|
request.object.set('foo', 'baz');
|
||||||
response.success();
|
response.success();
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('ChangingObject');
|
const obj = new Parse.Object('ChangingObject');
|
||||||
obj.save({ foo: 'bar' }).then((objAgain) => {
|
obj.save({ foo: 'bar' }).then((objAgain) => {
|
||||||
expect(objAgain.get('foo')).toEqual('baz');
|
expect(objAgain.get('foo')).toEqual('baz');
|
||||||
done();
|
done();
|
||||||
@@ -726,9 +726,9 @@ describe('Cloud Code', () => {
|
|||||||
expect(request.object.get('file')).toBeUndefined();
|
expect(request.object.get('file')).toBeUndefined();
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
});
|
});
|
||||||
let file = new Parse.File("yolo.txt", [1,2,3], "text/plain");
|
const file = new Parse.File("yolo.txt", [1,2,3], "text/plain");
|
||||||
file.save().then(() => {
|
file.save().then(() => {
|
||||||
let obj = new Parse.Object('ChangingObject');
|
const obj = new Parse.Object('ChangingObject');
|
||||||
return obj.save({ file, date: new Date() })
|
return obj.save({ file, date: new Date() })
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
done();
|
done();
|
||||||
@@ -995,7 +995,7 @@ describe('Cloud Code', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let object;
|
let object;
|
||||||
let testObject = new TestObject({key: 'value'});
|
const testObject = new TestObject({key: 'value'});
|
||||||
testObject.save().then(() => {
|
testObject.save().then(() => {
|
||||||
object = new BeforeSaveObject();
|
object = new BeforeSaveObject();
|
||||||
return object.save().then(() => {
|
return object.save().then(() => {
|
||||||
@@ -1026,7 +1026,7 @@ describe('Cloud Code', () => {
|
|||||||
}, res.error);
|
}, res.error);
|
||||||
});
|
});
|
||||||
|
|
||||||
let object = new BeforeSaveObject();
|
const object = new BeforeSaveObject();
|
||||||
object.save().then((objectAgain) => {
|
object.save().then((objectAgain) => {
|
||||||
// Originally it would throw as it would be a non-relation
|
// Originally it would throw as it would be a non-relation
|
||||||
expect(() => { objectAgain.relation('testsRelation') }).not.toThrow();
|
expect(() => { objectAgain.relation('testsRelation') }).not.toThrow();
|
||||||
@@ -1194,7 +1194,7 @@ describe('Cloud Code', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
function getJobStatus(jobId) {
|
function getJobStatus(jobId) {
|
||||||
let q = new Parse.Query('_JobStatus');
|
const q = new Parse.Query('_JobStatus');
|
||||||
return q.get(jobId, {useMasterKey: true});
|
return q.get(jobId, {useMasterKey: true});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -1203,9 +1203,9 @@ describe('Cloud Code', () => {
|
|||||||
describe('beforeFind hooks', () => {
|
describe('beforeFind hooks', () => {
|
||||||
it('should add beforeFind trigger', (done) => {
|
it('should add beforeFind trigger', (done) => {
|
||||||
Parse.Cloud.beforeFind('MyObject', (req) => {
|
Parse.Cloud.beforeFind('MyObject', (req) => {
|
||||||
let q = req.query;
|
const q = req.query;
|
||||||
expect(q instanceof Parse.Query).toBe(true);
|
expect(q instanceof Parse.Query).toBe(true);
|
||||||
let jsonQuery = q.toJSON();
|
const jsonQuery = q.toJSON();
|
||||||
expect(jsonQuery.where.key).toEqual('value');
|
expect(jsonQuery.where.key).toEqual('value');
|
||||||
expect(jsonQuery.where.some).toEqual({'$gt': 10});
|
expect(jsonQuery.where.some).toEqual({'$gt': 10});
|
||||||
expect(jsonQuery.include).toEqual('otherKey,otherValue');
|
expect(jsonQuery.include).toEqual('otherKey,otherValue');
|
||||||
@@ -1213,7 +1213,7 @@ describe('beforeFind hooks', () => {
|
|||||||
expect(jsonQuery.skip).toBe(undefined);
|
expect(jsonQuery.skip).toBe(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.equalTo('key', 'value');
|
query.equalTo('key', 'value');
|
||||||
query.greaterThan('some', 10);
|
query.greaterThan('some', 10);
|
||||||
query.include('otherKey');
|
query.include('otherKey');
|
||||||
@@ -1225,21 +1225,21 @@ describe('beforeFind hooks', () => {
|
|||||||
|
|
||||||
it('should use modify', (done) => {
|
it('should use modify', (done) => {
|
||||||
Parse.Cloud.beforeFind('MyObject', (req) => {
|
Parse.Cloud.beforeFind('MyObject', (req) => {
|
||||||
let q = req.query;
|
const q = req.query;
|
||||||
q.equalTo('forced', true);
|
q.equalTo('forced', true);
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj0 = new Parse.Object('MyObject');
|
const obj0 = new Parse.Object('MyObject');
|
||||||
obj0.set('forced', false);
|
obj0.set('forced', false);
|
||||||
|
|
||||||
let obj1 = new Parse.Object('MyObject');
|
const obj1 = new Parse.Object('MyObject');
|
||||||
obj1.set('forced', true);
|
obj1.set('forced', true);
|
||||||
Parse.Object.saveAll([obj0, obj1]).then(() => {
|
Parse.Object.saveAll([obj0, obj1]).then(() => {
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.equalTo('forced', false);
|
query.equalTo('forced', false);
|
||||||
query.find().then((results) => {
|
query.find().then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let firstResult = results[0];
|
const firstResult = results[0];
|
||||||
expect(firstResult.get('forced')).toBe(true);
|
expect(firstResult.get('forced')).toBe(true);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
@@ -1248,19 +1248,19 @@ describe('beforeFind hooks', () => {
|
|||||||
|
|
||||||
it('should use the modified the query', (done) => {
|
it('should use the modified the query', (done) => {
|
||||||
Parse.Cloud.beforeFind('MyObject', (req) => {
|
Parse.Cloud.beforeFind('MyObject', (req) => {
|
||||||
let q = req.query;
|
const q = req.query;
|
||||||
let otherQuery = new Parse.Query('MyObject');
|
const otherQuery = new Parse.Query('MyObject');
|
||||||
otherQuery.equalTo('forced', true);
|
otherQuery.equalTo('forced', true);
|
||||||
return Parse.Query.or(q, otherQuery);
|
return Parse.Query.or(q, otherQuery);
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj0 = new Parse.Object('MyObject');
|
const obj0 = new Parse.Object('MyObject');
|
||||||
obj0.set('forced', false);
|
obj0.set('forced', false);
|
||||||
|
|
||||||
let obj1 = new Parse.Object('MyObject');
|
const obj1 = new Parse.Object('MyObject');
|
||||||
obj1.set('forced', true);
|
obj1.set('forced', true);
|
||||||
Parse.Object.saveAll([obj0, obj1]).then(() => {
|
Parse.Object.saveAll([obj0, obj1]).then(() => {
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.equalTo('forced', false);
|
query.equalTo('forced', false);
|
||||||
query.find().then((results) => {
|
query.find().then((results) => {
|
||||||
expect(results.length).toBe(2);
|
expect(results.length).toBe(2);
|
||||||
@@ -1274,7 +1274,7 @@ describe('beforeFind hooks', () => {
|
|||||||
return Promise.reject('Do not run that query');
|
return Promise.reject('Do not run that query');
|
||||||
});
|
});
|
||||||
|
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.find().then(() => {
|
query.find().then(() => {
|
||||||
fail('should not succeed');
|
fail('should not succeed');
|
||||||
done();
|
done();
|
||||||
@@ -1287,7 +1287,7 @@ describe('beforeFind hooks', () => {
|
|||||||
|
|
||||||
it('should handle empty where', (done) => {
|
it('should handle empty where', (done) => {
|
||||||
Parse.Cloud.beforeFind('MyObject', (req) => {
|
Parse.Cloud.beforeFind('MyObject', (req) => {
|
||||||
let otherQuery = new Parse.Query('MyObject');
|
const otherQuery = new Parse.Query('MyObject');
|
||||||
otherQuery.equalTo('some', true);
|
otherQuery.equalTo('some', true);
|
||||||
return Parse.Query.or(req.query, otherQuery);
|
return Parse.Query.or(req.query, otherQuery);
|
||||||
});
|
});
|
||||||
@@ -1315,10 +1315,10 @@ describe('afterFind hooks', () => {
|
|||||||
}
|
}
|
||||||
res.success(req.objects);
|
res.success(req.objects);
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('MyObject');
|
const obj = new Parse.Object('MyObject');
|
||||||
obj.set('secretField', 'SSID');
|
obj.set('secretField', 'SSID');
|
||||||
obj.save().then(function() {
|
obj.save().then(function() {
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.get(obj.id).then(function(result) {
|
query.get(obj.id).then(function(result) {
|
||||||
expect(result.get('secretField')).toEqual('###');
|
expect(result.get('secretField')).toEqual('###');
|
||||||
done();
|
done();
|
||||||
@@ -1339,10 +1339,10 @@ describe('afterFind hooks', () => {
|
|||||||
}
|
}
|
||||||
res.success(req.objects);
|
res.success(req.objects);
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('MyObject');
|
const obj = new Parse.Object('MyObject');
|
||||||
obj.set('secretField', 'SSID');
|
obj.set('secretField', 'SSID');
|
||||||
obj.save().then(function() {
|
obj.save().then(function() {
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.equalTo('objectId',obj.id);
|
query.equalTo('objectId',obj.id);
|
||||||
query.find().then(function(results) {
|
query.find().then(function(results) {
|
||||||
expect(results[0].get('secretField')).toEqual('###');
|
expect(results[0].get('secretField')).toEqual('###');
|
||||||
@@ -1359,7 +1359,7 @@ describe('afterFind hooks', () => {
|
|||||||
|
|
||||||
it('should filter out results',(done) => {
|
it('should filter out results',(done) => {
|
||||||
Parse.Cloud.afterFind('MyObject', (req, res) => {
|
Parse.Cloud.afterFind('MyObject', (req, res) => {
|
||||||
let filteredResults = [];
|
const filteredResults = [];
|
||||||
for(let i = 0 ; i < req.objects.length ; i++){
|
for(let i = 0 ; i < req.objects.length ; i++){
|
||||||
if(req.objects[i].get("secretField")==="SSID1") {
|
if(req.objects[i].get("secretField")==="SSID1") {
|
||||||
filteredResults.push(req.objects[i]);
|
filteredResults.push(req.objects[i]);
|
||||||
@@ -1367,12 +1367,12 @@ describe('afterFind hooks', () => {
|
|||||||
}
|
}
|
||||||
res.success(filteredResults);
|
res.success(filteredResults);
|
||||||
});
|
});
|
||||||
let obj0 = new Parse.Object('MyObject');
|
const obj0 = new Parse.Object('MyObject');
|
||||||
obj0.set('secretField', 'SSID1');
|
obj0.set('secretField', 'SSID1');
|
||||||
let obj1 = new Parse.Object('MyObject');
|
const obj1 = new Parse.Object('MyObject');
|
||||||
obj1.set('secretField', 'SSID2');
|
obj1.set('secretField', 'SSID2');
|
||||||
Parse.Object.saveAll([obj0, obj1]).then(function() {
|
Parse.Object.saveAll([obj0, obj1]).then(function() {
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.find().then(function(results) {
|
query.find().then(function(results) {
|
||||||
expect(results[0].get('secretField')).toEqual('SSID1');
|
expect(results[0].get('secretField')).toEqual('SSID1');
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
@@ -1391,10 +1391,10 @@ describe('afterFind hooks', () => {
|
|||||||
Parse.Cloud.afterFind('MyObject', (req, res) => {
|
Parse.Cloud.afterFind('MyObject', (req, res) => {
|
||||||
res.error(Parse.Error.SCRIPT_FAILED, "It should fail");
|
res.error(Parse.Error.SCRIPT_FAILED, "It should fail");
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('MyObject');
|
const obj = new Parse.Object('MyObject');
|
||||||
obj.set('secretField', 'SSID');
|
obj.set('secretField', 'SSID');
|
||||||
obj.save().then(function() {
|
obj.save().then(function() {
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.equalTo('objectId',obj.id);
|
query.equalTo('objectId',obj.id);
|
||||||
query.find().then(function() {
|
query.find().then(function() {
|
||||||
fail("AfterFind should handle response failure correctly");
|
fail("AfterFind should handle response failure correctly");
|
||||||
@@ -1409,7 +1409,7 @@ describe('afterFind hooks', () => {
|
|||||||
|
|
||||||
it('should also work with promise',(done) => {
|
it('should also work with promise',(done) => {
|
||||||
Parse.Cloud.afterFind('MyObject', (req) => {
|
Parse.Cloud.afterFind('MyObject', (req) => {
|
||||||
let promise = new Parse.Promise();
|
const promise = new Parse.Promise();
|
||||||
setTimeout(function(){
|
setTimeout(function(){
|
||||||
for(let i = 0 ; i < req.objects.length ; i++){
|
for(let i = 0 ; i < req.objects.length ; i++){
|
||||||
req.objects[i].set("secretField","###");
|
req.objects[i].set("secretField","###");
|
||||||
@@ -1418,10 +1418,10 @@ describe('afterFind hooks', () => {
|
|||||||
}, 1000);
|
}, 1000);
|
||||||
return promise;
|
return promise;
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('MyObject');
|
const obj = new Parse.Object('MyObject');
|
||||||
obj.set('secretField', 'SSID');
|
obj.set('secretField', 'SSID');
|
||||||
obj.save().then(function() {
|
obj.save().then(function() {
|
||||||
let query = new Parse.Query('MyObject');
|
const query = new Parse.Query('MyObject');
|
||||||
query.equalTo('objectId',obj.id);
|
query.equalTo('objectId',obj.id);
|
||||||
query.find().then(function(results) {
|
query.find().then(function(results) {
|
||||||
expect(results[0].get('secretField')).toEqual('###');
|
expect(results[0].get('secretField')).toEqual('###');
|
||||||
|
|||||||
@@ -37,10 +37,10 @@ describe("Cloud Code Logger", () => {
|
|||||||
return logController.getLogs({ from: Date.now() - 500, size: 1000 });
|
return logController.getLogs({ from: Date.now() - 500, size: 1000 });
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
expect(res.length).not.toBe(0);
|
expect(res.length).not.toBe(0);
|
||||||
let lastLogs = res.slice(0, 3);
|
const lastLogs = res.slice(0, 3);
|
||||||
let cloudFunctionMessage = lastLogs[0];
|
const cloudFunctionMessage = lastLogs[0];
|
||||||
let errorMessage = lastLogs[1];
|
const errorMessage = lastLogs[1];
|
||||||
let infoMessage = lastLogs[2];
|
const infoMessage = lastLogs[2];
|
||||||
expect(cloudFunctionMessage.level).toBe('info');
|
expect(cloudFunctionMessage.level).toBe('info');
|
||||||
expect(cloudFunctionMessage.params).toEqual({});
|
expect(cloudFunctionMessage.params).toEqual({});
|
||||||
expect(cloudFunctionMessage.message).toMatch(/Ran cloud function loggerTest for user [^ ]* with:\n {2}Input: {}\n {2}Result: {}/);
|
expect(cloudFunctionMessage.message).toMatch(/Ran cloud function loggerTest for user [^ ]* with:\n {2}Input: {}\n {2}Result: {}/);
|
||||||
@@ -82,15 +82,15 @@ describe("Cloud Code Logger", () => {
|
|||||||
res.success({});
|
res.success({});
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('MyObject');
|
const obj = new Parse.Object('MyObject');
|
||||||
obj.save().then(() => {
|
obj.save().then(() => {
|
||||||
return logController.getLogs({ from: Date.now() - 500, size: 1000 })
|
return logController.getLogs({ from: Date.now() - 500, size: 1000 })
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
expect(res.length).not.toBe(0);
|
expect(res.length).not.toBe(0);
|
||||||
let lastLogs = res.slice(0, 3);
|
const lastLogs = res.slice(0, 3);
|
||||||
let cloudTriggerMessage = lastLogs[0];
|
const cloudTriggerMessage = lastLogs[0];
|
||||||
let errorMessage = lastLogs[1];
|
const errorMessage = lastLogs[1];
|
||||||
let infoMessage = lastLogs[2];
|
const infoMessage = lastLogs[2];
|
||||||
expect(cloudTriggerMessage.level).toBe('info');
|
expect(cloudTriggerMessage.level).toBe('info');
|
||||||
expect(cloudTriggerMessage.triggerType).toEqual('beforeSave');
|
expect(cloudTriggerMessage.triggerType).toEqual('beforeSave');
|
||||||
expect(cloudTriggerMessage.message).toMatch(/beforeSave triggered for MyObject for user [^ ]*\n {2}Input: {}\n {2}Result: {}/);
|
expect(cloudTriggerMessage.message).toMatch(/beforeSave triggered for MyObject for user [^ ]*\n {2}Input: {}\n {2}Result: {}/);
|
||||||
|
|||||||
@@ -241,12 +241,12 @@ describe("Email Verification Token Expiration: ", () => {
|
|||||||
return user.signUp();
|
return user.signUp();
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
return config.database.find('_User', {username: 'sets_email_verify_token_expires_at'});
|
return config.database.find('_User', {username: 'sets_email_verify_token_expires_at'});
|
||||||
})
|
})
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let user = results[0];
|
const user = results[0];
|
||||||
expect(typeof user).toBe('object');
|
expect(typeof user).toBe('object');
|
||||||
expect(user.emailVerified).toEqual(false);
|
expect(user.emailVerified).toEqual(false);
|
||||||
expect(typeof user._email_verify_token).toBe('string');
|
expect(typeof user._email_verify_token).toBe('string');
|
||||||
@@ -288,7 +288,7 @@ describe("Email Verification Token Expiration: ", () => {
|
|||||||
followRedirect: false,
|
followRedirect: false,
|
||||||
}, (error, response) => {
|
}, (error, response) => {
|
||||||
expect(response.statusCode).toEqual(302);
|
expect(response.statusCode).toEqual(302);
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
return config.database.find('_User', {username: 'unsets_email_verify_token_expires_at'}).then((results) => {
|
return config.database.find('_User', {username: 'unsets_email_verify_token_expires_at'}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
return results[0];
|
return results[0];
|
||||||
@@ -420,18 +420,18 @@ describe("Email Verification Token Expiration: ", () => {
|
|||||||
|
|
||||||
it('setting the email on the user should set a new email verification token and new expiration date for the token when expire email verify token flag is set', done => {
|
it('setting the email on the user should set a new email verification token and new expiration date for the token when expire email verify token flag is set', done => {
|
||||||
|
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let userBeforeEmailReset;
|
let userBeforeEmailReset;
|
||||||
|
|
||||||
let sendEmailOptions;
|
let sendEmailOptions;
|
||||||
let emailAdapter = {
|
const emailAdapter = {
|
||||||
sendVerificationEmail: options => {
|
sendVerificationEmail: options => {
|
||||||
sendEmailOptions = options;
|
sendEmailOptions = options;
|
||||||
},
|
},
|
||||||
sendPasswordResetEmail: () => Promise.resolve(),
|
sendPasswordResetEmail: () => Promise.resolve(),
|
||||||
sendMail: () => {}
|
sendMail: () => {}
|
||||||
};
|
};
|
||||||
let serverConfig = {
|
const serverConfig = {
|
||||||
appName: 'emailVerifyToken',
|
appName: 'emailVerifyToken',
|
||||||
verifyUserEmails: true,
|
verifyUserEmails: true,
|
||||||
emailAdapter: emailAdapter,
|
emailAdapter: emailAdapter,
|
||||||
@@ -447,7 +447,7 @@ describe("Email Verification Token Expiration: ", () => {
|
|||||||
return user.signUp();
|
return user.signUp();
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
return config.database.find('_User', {username: 'newEmailVerifyTokenOnEmailReset'}).then((results) => {
|
return config.database.find('_User', {username: 'newEmailVerifyTokenOnEmailReset'}).then((results) => {
|
||||||
return results[0];
|
return results[0];
|
||||||
});
|
});
|
||||||
@@ -464,7 +464,7 @@ describe("Email Verification Token Expiration: ", () => {
|
|||||||
});
|
});
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
return config.database.find('_User', {username: 'newEmailVerifyTokenOnEmailReset'}).then((results) => {
|
return config.database.find('_User', {username: 'newEmailVerifyTokenOnEmailReset'}).then((results) => {
|
||||||
return results[0];
|
return results[0];
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -162,10 +162,10 @@ describe("httpRequest", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("should encode a query string body by default", (done) => {
|
it("should encode a query string body by default", (done) => {
|
||||||
let options = {
|
const options = {
|
||||||
body: {"foo": "bar"},
|
body: {"foo": "bar"},
|
||||||
}
|
}
|
||||||
let result = httpRequest.encodeBody(options);
|
const result = httpRequest.encodeBody(options);
|
||||||
expect(result.body).toEqual('foo=bar');
|
expect(result.body).toEqual('foo=bar');
|
||||||
expect(result.headers['Content-Type']).toEqual('application/x-www-form-urlencoded');
|
expect(result.headers['Content-Type']).toEqual('application/x-www-form-urlencoded');
|
||||||
done();
|
done();
|
||||||
@@ -173,30 +173,30 @@ describe("httpRequest", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it("should encode a JSON body", (done) => {
|
it("should encode a JSON body", (done) => {
|
||||||
let options = {
|
const options = {
|
||||||
body: {"foo": "bar"},
|
body: {"foo": "bar"},
|
||||||
headers: {'Content-Type': 'application/json'}
|
headers: {'Content-Type': 'application/json'}
|
||||||
}
|
}
|
||||||
let result = httpRequest.encodeBody(options);
|
const result = httpRequest.encodeBody(options);
|
||||||
expect(result.body).toEqual('{"foo":"bar"}');
|
expect(result.body).toEqual('{"foo":"bar"}');
|
||||||
done();
|
done();
|
||||||
|
|
||||||
})
|
})
|
||||||
it("should encode a www-form body", (done) => {
|
it("should encode a www-form body", (done) => {
|
||||||
let options = {
|
const options = {
|
||||||
body: {"foo": "bar", "bar": "baz"},
|
body: {"foo": "bar", "bar": "baz"},
|
||||||
headers: {'cOntent-tYpe': 'application/x-www-form-urlencoded'}
|
headers: {'cOntent-tYpe': 'application/x-www-form-urlencoded'}
|
||||||
}
|
}
|
||||||
let result = httpRequest.encodeBody(options);
|
const result = httpRequest.encodeBody(options);
|
||||||
expect(result.body).toEqual("foo=bar&bar=baz");
|
expect(result.body).toEqual("foo=bar&bar=baz");
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
it("should not encode a wrong content type", (done) => {
|
it("should not encode a wrong content type", (done) => {
|
||||||
let options = {
|
const options = {
|
||||||
body:{"foo": "bar", "bar": "baz"},
|
body:{"foo": "bar", "bar": "baz"},
|
||||||
headers: {'cOntent-tYpe': 'mime/jpeg'}
|
headers: {'cOntent-tYpe': 'mime/jpeg'}
|
||||||
}
|
}
|
||||||
let result = httpRequest.encodeBody(options);
|
const result = httpRequest.encodeBody(options);
|
||||||
expect(result.body).toEqual({"foo": "bar", "bar": "baz"});
|
expect(result.body).toEqual({"foo": "bar", "bar": "baz"});
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
@@ -247,7 +247,7 @@ describe("httpRequest", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should not crash with undefined body', () => {
|
it('should not crash with undefined body', () => {
|
||||||
let httpResponse = new HTTPResponse({});
|
const httpResponse = new HTTPResponse({});
|
||||||
expect(httpResponse.body).toBeUndefined();
|
expect(httpResponse.body).toBeUndefined();
|
||||||
expect(httpResponse.data).toBeUndefined();
|
expect(httpResponse.data).toBeUndefined();
|
||||||
expect(httpResponse.text).toBeUndefined();
|
expect(httpResponse.text).toBeUndefined();
|
||||||
@@ -255,23 +255,23 @@ describe("httpRequest", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('serialized httpResponse correctly with body string', () => {
|
it('serialized httpResponse correctly with body string', () => {
|
||||||
let httpResponse = new HTTPResponse({}, 'hello');
|
const httpResponse = new HTTPResponse({}, 'hello');
|
||||||
expect(httpResponse.text).toBe('hello');
|
expect(httpResponse.text).toBe('hello');
|
||||||
expect(httpResponse.data).toBe(undefined);
|
expect(httpResponse.data).toBe(undefined);
|
||||||
expect(httpResponse.body).toBe('hello');
|
expect(httpResponse.body).toBe('hello');
|
||||||
|
|
||||||
let serialized = JSON.stringify(httpResponse);
|
const serialized = JSON.stringify(httpResponse);
|
||||||
let result = JSON.parse(serialized);
|
const result = JSON.parse(serialized);
|
||||||
expect(result.text).toBe('hello');
|
expect(result.text).toBe('hello');
|
||||||
expect(result.data).toBe(undefined);
|
expect(result.data).toBe(undefined);
|
||||||
expect(result.body).toBe(undefined);
|
expect(result.body).toBe(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('serialized httpResponse correctly with body object', () => {
|
it('serialized httpResponse correctly with body object', () => {
|
||||||
let httpResponse = new HTTPResponse({}, {foo: "bar"});
|
const httpResponse = new HTTPResponse({}, {foo: "bar"});
|
||||||
Parse._encode(httpResponse);
|
Parse._encode(httpResponse);
|
||||||
let serialized = JSON.stringify(httpResponse);
|
const serialized = JSON.stringify(httpResponse);
|
||||||
let result = JSON.parse(serialized);
|
const result = JSON.parse(serialized);
|
||||||
|
|
||||||
expect(httpResponse.text).toEqual('{"foo":"bar"}');
|
expect(httpResponse.text).toEqual('{"foo":"bar"}');
|
||||||
expect(httpResponse.data).toEqual({foo: 'bar'});
|
expect(httpResponse.data).toEqual({foo: 'bar'});
|
||||||
@@ -283,29 +283,29 @@ describe("httpRequest", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('serialized httpResponse correctly with body buffer string', () => {
|
it('serialized httpResponse correctly with body buffer string', () => {
|
||||||
let httpResponse = new HTTPResponse({}, new Buffer('hello'));
|
const httpResponse = new HTTPResponse({}, new Buffer('hello'));
|
||||||
expect(httpResponse.text).toBe('hello');
|
expect(httpResponse.text).toBe('hello');
|
||||||
expect(httpResponse.data).toBe(undefined);
|
expect(httpResponse.data).toBe(undefined);
|
||||||
|
|
||||||
let serialized = JSON.stringify(httpResponse);
|
const serialized = JSON.stringify(httpResponse);
|
||||||
let result = JSON.parse(serialized);
|
const result = JSON.parse(serialized);
|
||||||
expect(result.text).toBe('hello');
|
expect(result.text).toBe('hello');
|
||||||
expect(result.data).toBe(undefined);
|
expect(result.data).toBe(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('serialized httpResponse correctly with body buffer JSON Object', () => {
|
it('serialized httpResponse correctly with body buffer JSON Object', () => {
|
||||||
let json = '{"foo":"bar"}';
|
const json = '{"foo":"bar"}';
|
||||||
let httpResponse = new HTTPResponse({}, new Buffer(json));
|
const httpResponse = new HTTPResponse({}, new Buffer(json));
|
||||||
let serialized = JSON.stringify(httpResponse);
|
const serialized = JSON.stringify(httpResponse);
|
||||||
let result = JSON.parse(serialized);
|
const result = JSON.parse(serialized);
|
||||||
expect(result.text).toEqual('{"foo":"bar"}');
|
expect(result.text).toEqual('{"foo":"bar"}');
|
||||||
expect(result.data).toEqual({foo: 'bar'});
|
expect(result.data).toEqual({foo: 'bar'});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('serialized httpResponse with Parse._encode should be allright', () => {
|
it('serialized httpResponse with Parse._encode should be allright', () => {
|
||||||
let json = '{"foo":"bar"}';
|
const json = '{"foo":"bar"}';
|
||||||
let httpResponse = new HTTPResponse({}, new Buffer(json));
|
const httpResponse = new HTTPResponse({}, new Buffer(json));
|
||||||
let encoded = Parse._encode(httpResponse);
|
const encoded = Parse._encode(httpResponse);
|
||||||
let foundData, foundText, foundBody = false;
|
let foundData, foundText, foundBody = false;
|
||||||
for(var key in encoded) {
|
for(var key in encoded) {
|
||||||
if (key == 'data') {
|
if (key == 'data') {
|
||||||
|
|||||||
@@ -23,8 +23,8 @@ describe('Logger', () => {
|
|||||||
|
|
||||||
it('should have files transports', (done) => {
|
it('should have files transports', (done) => {
|
||||||
reconfigureServer().then(() => {
|
reconfigureServer().then(() => {
|
||||||
let transports = logging.logger.transports;
|
const transports = logging.logger.transports;
|
||||||
let transportKeys = Object.keys(transports);
|
const transportKeys = Object.keys(transports);
|
||||||
expect(transportKeys.length).toBe(3);
|
expect(transportKeys.length).toBe(3);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
@@ -34,8 +34,8 @@ describe('Logger', () => {
|
|||||||
reconfigureServer({
|
reconfigureServer({
|
||||||
logsFolder: null
|
logsFolder: null
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let transports = logging.logger.transports;
|
const transports = logging.logger.transports;
|
||||||
let transportKeys = Object.keys(transports);
|
const transportKeys = Object.keys(transports);
|
||||||
expect(transportKeys.length).toBe(1);
|
expect(transportKeys.length).toBe(1);
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ module.exports = options => {
|
|||||||
if (!options) {
|
if (!options) {
|
||||||
throw "Options were not provided"
|
throw "Options were not provided"
|
||||||
}
|
}
|
||||||
let adapter = {
|
const adapter = {
|
||||||
sendVerificationEmail: () => Promise.resolve(),
|
sendVerificationEmail: () => Promise.resolve(),
|
||||||
sendPasswordResetEmail: () => Promise.resolve(),
|
sendPasswordResetEmail: () => Promise.resolve(),
|
||||||
sendMail: () => Promise.resolve()
|
sendMail: () => Promise.resolve()
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('stores objectId in _id', done => {
|
it('stores objectId in _id', done => {
|
||||||
let adapter = new MongoStorageAdapter({ uri: databaseURI });
|
const adapter = new MongoStorageAdapter({ uri: databaseURI });
|
||||||
adapter.createObject('Foo', { fields: {} }, { objectId: 'abcde' })
|
adapter.createObject('Foo', { fields: {} }, { objectId: 'abcde' })
|
||||||
.then(() => adapter._rawFind('Foo', {}))
|
.then(() => adapter._rawFind('Foo', {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
@@ -62,7 +62,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
|
|
||||||
it('find succeeds when query is within maxTimeMS', (done) => {
|
it('find succeeds when query is within maxTimeMS', (done) => {
|
||||||
const maxTimeMS = 250;
|
const maxTimeMS = 250;
|
||||||
let adapter = new MongoStorageAdapter({
|
const adapter = new MongoStorageAdapter({
|
||||||
uri: databaseURI,
|
uri: databaseURI,
|
||||||
mongoOptions: { maxTimeMS },
|
mongoOptions: { maxTimeMS },
|
||||||
});
|
});
|
||||||
@@ -78,7 +78,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
|
|
||||||
it('find fails when query exceeds maxTimeMS', (done) => {
|
it('find fails when query exceeds maxTimeMS', (done) => {
|
||||||
const maxTimeMS = 250;
|
const maxTimeMS = 250;
|
||||||
let adapter = new MongoStorageAdapter({
|
const adapter = new MongoStorageAdapter({
|
||||||
uri: databaseURI,
|
uri: databaseURI,
|
||||||
mongoOptions: { maxTimeMS },
|
mongoOptions: { maxTimeMS },
|
||||||
});
|
});
|
||||||
@@ -98,7 +98,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('stores pointers with a _p_ prefix', (done) => {
|
it('stores pointers with a _p_ prefix', (done) => {
|
||||||
let obj = {
|
const obj = {
|
||||||
objectId: 'bar',
|
objectId: 'bar',
|
||||||
aPointer: {
|
aPointer: {
|
||||||
__type: 'Pointer',
|
__type: 'Pointer',
|
||||||
@@ -106,7 +106,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
objectId: 'qwerty'
|
objectId: 'qwerty'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let adapter = new MongoStorageAdapter({ uri: databaseURI });
|
const adapter = new MongoStorageAdapter({ uri: databaseURI });
|
||||||
adapter.createObject('APointerDarkly', { fields: {
|
adapter.createObject('APointerDarkly', { fields: {
|
||||||
objectId: { type: 'String' },
|
objectId: { type: 'String' },
|
||||||
aPointer: { type: 'Pointer', targetClass: 'JustThePointer' },
|
aPointer: { type: 'Pointer', targetClass: 'JustThePointer' },
|
||||||
@@ -114,7 +114,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
.then(() => adapter._rawFind('APointerDarkly', {}))
|
.then(() => adapter._rawFind('APointerDarkly', {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let output = results[0];
|
const output = results[0];
|
||||||
expect(typeof output._id).toEqual('string');
|
expect(typeof output._id).toEqual('string');
|
||||||
expect(typeof output._p_aPointer).toEqual('string');
|
expect(typeof output._p_aPointer).toEqual('string');
|
||||||
expect(output._p_aPointer).toEqual('JustThePointer$qwerty');
|
expect(output._p_aPointer).toEqual('JustThePointer$qwerty');
|
||||||
@@ -124,24 +124,24 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('handles object and subdocument', done => {
|
it('handles object and subdocument', done => {
|
||||||
let adapter = new MongoStorageAdapter({ uri: databaseURI });
|
const adapter = new MongoStorageAdapter({ uri: databaseURI });
|
||||||
let schema = { fields : { subdoc: { type: 'Object' } } };
|
const schema = { fields : { subdoc: { type: 'Object' } } };
|
||||||
let obj = { subdoc: {foo: 'bar', wu: 'tan'} };
|
const obj = { subdoc: {foo: 'bar', wu: 'tan'} };
|
||||||
adapter.createObject('MyClass', schema, obj)
|
adapter.createObject('MyClass', schema, obj)
|
||||||
.then(() => adapter._rawFind('MyClass', {}))
|
.then(() => adapter._rawFind('MyClass', {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let mob = results[0];
|
const mob = results[0];
|
||||||
expect(typeof mob.subdoc).toBe('object');
|
expect(typeof mob.subdoc).toBe('object');
|
||||||
expect(mob.subdoc.foo).toBe('bar');
|
expect(mob.subdoc.foo).toBe('bar');
|
||||||
expect(mob.subdoc.wu).toBe('tan');
|
expect(mob.subdoc.wu).toBe('tan');
|
||||||
let obj = { 'subdoc.wu': 'clan' };
|
const obj = { 'subdoc.wu': 'clan' };
|
||||||
return adapter.findOneAndUpdate('MyClass', schema, {}, obj);
|
return adapter.findOneAndUpdate('MyClass', schema, {}, obj);
|
||||||
})
|
})
|
||||||
.then(() => adapter._rawFind('MyClass', {}))
|
.then(() => adapter._rawFind('MyClass', {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let mob = results[0];
|
const mob = results[0];
|
||||||
expect(typeof mob.subdoc).toBe('object');
|
expect(typeof mob.subdoc).toBe('object');
|
||||||
expect(mob.subdoc.foo).toBe('bar');
|
expect(mob.subdoc.foo).toBe('bar');
|
||||||
expect(mob.subdoc.wu).toBe('clan');
|
expect(mob.subdoc.wu).toBe('clan');
|
||||||
@@ -150,8 +150,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('handles creating an array, object, date', (done) => {
|
it('handles creating an array, object, date', (done) => {
|
||||||
let adapter = new MongoStorageAdapter({ uri: databaseURI });
|
const adapter = new MongoStorageAdapter({ uri: databaseURI });
|
||||||
let obj = {
|
const obj = {
|
||||||
array: [1, 2, 3],
|
array: [1, 2, 3],
|
||||||
object: {foo: 'bar'},
|
object: {foo: 'bar'},
|
||||||
date: {
|
date: {
|
||||||
@@ -159,7 +159,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
iso: '2016-05-26T20:55:01.154Z',
|
iso: '2016-05-26T20:55:01.154Z',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let schema = { fields: {
|
const schema = { fields: {
|
||||||
array: { type: 'Array' },
|
array: { type: 'Array' },
|
||||||
object: { type: 'Object' },
|
object: { type: 'Object' },
|
||||||
date: { type: 'Date' },
|
date: { type: 'Date' },
|
||||||
@@ -168,7 +168,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
.then(() => adapter._rawFind('MyClass', {}))
|
.then(() => adapter._rawFind('MyClass', {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let mob = results[0];
|
const mob = results[0];
|
||||||
expect(mob.array instanceof Array).toBe(true);
|
expect(mob.array instanceof Array).toBe(true);
|
||||||
expect(typeof mob.object).toBe('object');
|
expect(typeof mob.object).toBe('object');
|
||||||
expect(mob.date instanceof Date).toBe(true);
|
expect(mob.date instanceof Date).toBe(true);
|
||||||
@@ -176,7 +176,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
})
|
})
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let mob = results[0];
|
const mob = results[0];
|
||||||
expect(mob.array instanceof Array).toBe(true);
|
expect(mob.array instanceof Array).toBe(true);
|
||||||
expect(typeof mob.object).toBe('object');
|
expect(typeof mob.object).toBe('object');
|
||||||
expect(mob.date.__type).toBe('Date');
|
expect(mob.date.__type).toBe('Date');
|
||||||
@@ -191,9 +191,9 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("handles updating a single object with array, object date", (done) => {
|
it("handles updating a single object with array, object date", (done) => {
|
||||||
let adapter = new MongoStorageAdapter({ uri: databaseURI });
|
const adapter = new MongoStorageAdapter({ uri: databaseURI });
|
||||||
|
|
||||||
let schema = { fields: {
|
const schema = { fields: {
|
||||||
array: { type: 'Array' },
|
array: { type: 'Array' },
|
||||||
object: { type: 'Object' },
|
object: { type: 'Object' },
|
||||||
date: { type: 'Date' },
|
date: { type: 'Date' },
|
||||||
@@ -204,7 +204,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
.then(() => adapter._rawFind('MyClass', {}))
|
.then(() => adapter._rawFind('MyClass', {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let update = {
|
const update = {
|
||||||
array: [1, 2, 3],
|
array: [1, 2, 3],
|
||||||
object: {foo: 'bar'},
|
object: {foo: 'bar'},
|
||||||
date: {
|
date: {
|
||||||
@@ -212,11 +212,11 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
iso: '2016-05-26T20:55:01.154Z',
|
iso: '2016-05-26T20:55:01.154Z',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
let query = {};
|
const query = {};
|
||||||
return adapter.findOneAndUpdate('MyClass', schema, query, update)
|
return adapter.findOneAndUpdate('MyClass', schema, query, update)
|
||||||
})
|
})
|
||||||
.then(results => {
|
.then(results => {
|
||||||
let mob = results;
|
const mob = results;
|
||||||
expect(mob.array instanceof Array).toBe(true);
|
expect(mob.array instanceof Array).toBe(true);
|
||||||
expect(typeof mob.object).toBe('object');
|
expect(typeof mob.object).toBe('object');
|
||||||
expect(mob.date.__type).toBe('Date');
|
expect(mob.date.__type).toBe('Date');
|
||||||
@@ -225,7 +225,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => {
|
|||||||
})
|
})
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let mob = results[0];
|
const mob = results[0];
|
||||||
expect(mob.array instanceof Array).toBe(true);
|
expect(mob.array instanceof Array).toBe(true);
|
||||||
expect(typeof mob.object).toBe('object');
|
expect(typeof mob.object).toBe('object');
|
||||||
expect(mob.date instanceof Date).toBe(true);
|
expect(mob.date instanceof Date).toBe(true);
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
// These tests are unit tests designed to only test transform.js.
|
// These tests are unit tests designed to only test transform.js.
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
let transform = require('../src/Adapters/Storage/Mongo/MongoTransform');
|
const transform = require('../src/Adapters/Storage/Mongo/MongoTransform');
|
||||||
let dd = require('deep-diff');
|
const dd = require('deep-diff');
|
||||||
let mongodb = require('mongodb');
|
const mongodb = require('mongodb');
|
||||||
|
|
||||||
describe('parseObjectToMongoObjectForCreate', () => {
|
describe('parseObjectToMongoObjectForCreate', () => {
|
||||||
it('a basic number', (done) => {
|
it('a basic number', (done) => {
|
||||||
@@ -179,7 +179,7 @@ describe('parseObjectToMongoObjectForCreate', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('untransforms objects containing nested special keys', done => {
|
it('untransforms objects containing nested special keys', done => {
|
||||||
let input = {array: [{
|
const input = {array: [{
|
||||||
_id: "Test ID",
|
_id: "Test ID",
|
||||||
_hashed_password: "I Don't know why you would name a key this, but if you do it should work",
|
_hashed_password: "I Don't know why you would name a key this, but if you do it should work",
|
||||||
_tombstone: {
|
_tombstone: {
|
||||||
@@ -190,7 +190,7 @@ describe('parseObjectToMongoObjectForCreate', () => {
|
|||||||
},
|
},
|
||||||
regularKey: "some data",
|
regularKey: "some data",
|
||||||
}]}
|
}]}
|
||||||
let output = transform.mongoObjectToParseObject(null, input, {
|
const output = transform.mongoObjectToParseObject(null, input, {
|
||||||
fields: { array: { type: 'Array' }},
|
fields: { array: { type: 'Array' }},
|
||||||
});
|
});
|
||||||
expect(dd(output, input)).toEqual(undefined);
|
expect(dd(output, input)).toEqual(undefined);
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
let request = require('request');
|
const request = require('request');
|
||||||
|
|
||||||
describe('Parse.Push', () => {
|
describe('Parse.Push', () => {
|
||||||
var setup = function() {
|
var setup = function() {
|
||||||
var pushAdapter = {
|
var pushAdapter = {
|
||||||
send: function(body, installations) {
|
send: function(body, installations) {
|
||||||
var badge = body.data.badge;
|
var badge = body.data.badge;
|
||||||
let promises = installations.map((installation) => {
|
const promises = installations.map((installation) => {
|
||||||
if (installation.deviceType == "ios") {
|
if (installation.deviceType == "ios") {
|
||||||
expect(installation.badge).toEqual(badge);
|
expect(installation.badge).toEqual(badge);
|
||||||
expect(installation.originalBadge+1).toEqual(installation.badge);
|
expect(installation.originalBadge+1).toEqual(installation.badge);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
var request = require('request');
|
var request = require('request');
|
||||||
const rp = require('request-promise');
|
const rp = require('request-promise');
|
||||||
const Parse = require("parse/node");
|
const Parse = require("parse/node");
|
||||||
let Config = require('../src/Config');
|
const Config = require('../src/Config');
|
||||||
const SchemaController = require('../src/Controllers/SchemaController');
|
const SchemaController = require('../src/Controllers/SchemaController');
|
||||||
var TestUtils = require('../src/TestUtils');
|
var TestUtils = require('../src/TestUtils');
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ describe_only_db('mongo')('miscellaneous', () => {
|
|||||||
obj.set('foo', 'bar');
|
obj.set('foo', 'bar');
|
||||||
return obj.save();
|
return obj.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let config = new Config(appId);
|
const config = new Config(appId);
|
||||||
return config.database.adapter.find('TestObject', { fields: {} }, {}, {});
|
return config.database.adapter.find('TestObject', { fields: {} }, {}, {});
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
@@ -83,7 +83,7 @@ describe('miscellaneous', function() {
|
|||||||
it('fail to create a duplicate username', done => {
|
it('fail to create a duplicate username', done => {
|
||||||
let numCreated = 0;
|
let numCreated = 0;
|
||||||
let numFailed = 0;
|
let numFailed = 0;
|
||||||
let p1 = createTestUser();
|
const p1 = createTestUser();
|
||||||
p1.then(() => {
|
p1.then(() => {
|
||||||
numCreated++;
|
numCreated++;
|
||||||
expect(numCreated).toEqual(1);
|
expect(numCreated).toEqual(1);
|
||||||
@@ -93,7 +93,7 @@ describe('miscellaneous', function() {
|
|||||||
expect(numFailed).toEqual(1);
|
expect(numFailed).toEqual(1);
|
||||||
expect(error.code).toEqual(Parse.Error.USERNAME_TAKEN);
|
expect(error.code).toEqual(Parse.Error.USERNAME_TAKEN);
|
||||||
});
|
});
|
||||||
let p2 = createTestUser();
|
const p2 = createTestUser();
|
||||||
p2.then(() => {
|
p2.then(() => {
|
||||||
numCreated++;
|
numCreated++;
|
||||||
expect(numCreated).toEqual(1);
|
expect(numCreated).toEqual(1);
|
||||||
@@ -114,11 +114,11 @@ describe('miscellaneous', function() {
|
|||||||
it('ensure that email is uniquely indexed', done => {
|
it('ensure that email is uniquely indexed', done => {
|
||||||
let numFailed = 0;
|
let numFailed = 0;
|
||||||
let numCreated = 0;
|
let numCreated = 0;
|
||||||
let user1 = new Parse.User();
|
const user1 = new Parse.User();
|
||||||
user1.setPassword('asdf');
|
user1.setPassword('asdf');
|
||||||
user1.setUsername('u1');
|
user1.setUsername('u1');
|
||||||
user1.setEmail('dupe@dupe.dupe');
|
user1.setEmail('dupe@dupe.dupe');
|
||||||
let p1 = user1.signUp();
|
const p1 = user1.signUp();
|
||||||
p1.then(() => {
|
p1.then(() => {
|
||||||
numCreated++;
|
numCreated++;
|
||||||
expect(numCreated).toEqual(1);
|
expect(numCreated).toEqual(1);
|
||||||
@@ -128,11 +128,11 @@ describe('miscellaneous', function() {
|
|||||||
expect(error.code).toEqual(Parse.Error.EMAIL_TAKEN);
|
expect(error.code).toEqual(Parse.Error.EMAIL_TAKEN);
|
||||||
});
|
});
|
||||||
|
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user2.setPassword('asdf');
|
user2.setPassword('asdf');
|
||||||
user2.setUsername('u2');
|
user2.setUsername('u2');
|
||||||
user2.setEmail('dupe@dupe.dupe');
|
user2.setEmail('dupe@dupe.dupe');
|
||||||
let p2 = user2.signUp();
|
const p2 = user2.signUp();
|
||||||
p2.then(() => {
|
p2.then(() => {
|
||||||
numCreated++;
|
numCreated++;
|
||||||
expect(numCreated).toEqual(1);
|
expect(numCreated).toEqual(1);
|
||||||
@@ -151,7 +151,7 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('ensure that if people already have duplicate users, they can still sign up new users', done => {
|
it('ensure that if people already have duplicate users, they can still sign up new users', done => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
// Remove existing data to clear out unique index
|
// Remove existing data to clear out unique index
|
||||||
TestUtils.destroyAllDataPermanently()
|
TestUtils.destroyAllDataPermanently()
|
||||||
.then(() => config.database.adapter.createClass('_User', userSchema))
|
.then(() => config.database.adapter.createClass('_User', userSchema))
|
||||||
@@ -161,13 +161,13 @@ describe('miscellaneous', function() {
|
|||||||
.then(reconfigureServer)
|
.then(reconfigureServer)
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
expect(error.code).toEqual(Parse.Error.DUPLICATE_VALUE);
|
expect(error.code).toEqual(Parse.Error.DUPLICATE_VALUE);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword('asdf');
|
user.setPassword('asdf');
|
||||||
user.setUsername('zxcv');
|
user.setUsername('zxcv');
|
||||||
return user.signUp().catch(fail);
|
return user.signUp().catch(fail);
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword('asdf');
|
user.setPassword('asdf');
|
||||||
user.setUsername('u');
|
user.setUsername('u');
|
||||||
return user.signUp()
|
return user.signUp()
|
||||||
@@ -183,7 +183,7 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('ensure that if people already have duplicate emails, they can still sign up new users', done => {
|
it('ensure that if people already have duplicate emails, they can still sign up new users', done => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
// Remove existing data to clear out unique index
|
// Remove existing data to clear out unique index
|
||||||
TestUtils.destroyAllDataPermanently()
|
TestUtils.destroyAllDataPermanently()
|
||||||
.then(() => config.database.adapter.createClass('_User', userSchema))
|
.then(() => config.database.adapter.createClass('_User', userSchema))
|
||||||
@@ -191,14 +191,14 @@ describe('miscellaneous', function() {
|
|||||||
.then(() => config.database.adapter.createObject('_User', userSchema, { objectId: 'y', email: 'a@b.c' }))
|
.then(() => config.database.adapter.createObject('_User', userSchema, { objectId: 'y', email: 'a@b.c' }))
|
||||||
.then(reconfigureServer)
|
.then(reconfigureServer)
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword('asdf');
|
user.setPassword('asdf');
|
||||||
user.setUsername('qqq');
|
user.setUsername('qqq');
|
||||||
user.setEmail('unique@unique.unique');
|
user.setEmail('unique@unique.unique');
|
||||||
return user.signUp().catch(fail);
|
return user.signUp().catch(fail);
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword('asdf');
|
user.setPassword('asdf');
|
||||||
user.setUsername('www');
|
user.setUsername('www');
|
||||||
user.setEmail('a@b.c');
|
user.setEmail('a@b.c');
|
||||||
@@ -211,11 +211,11 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('ensure that if you try to sign up a user with a unique username and email, but duplicates in some other field that has a uniqueness constraint, you get a regular duplicate value error', done => {
|
it('ensure that if you try to sign up a user with a unique username and email, but duplicates in some other field that has a uniqueness constraint, you get a regular duplicate value error', done => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
config.database.adapter.addFieldIfNotExists('_User', 'randomField', { type: 'String' })
|
config.database.adapter.addFieldIfNotExists('_User', 'randomField', { type: 'String' })
|
||||||
.then(() => config.database.adapter.ensureUniqueness('_User', userSchema, ['randomField']))
|
.then(() => config.database.adapter.ensureUniqueness('_User', userSchema, ['randomField']))
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword('asdf');
|
user.setPassword('asdf');
|
||||||
user.setUsername('1');
|
user.setUsername('1');
|
||||||
user.setEmail('1@b.c');
|
user.setEmail('1@b.c');
|
||||||
@@ -223,7 +223,7 @@ describe('miscellaneous', function() {
|
|||||||
return user.signUp()
|
return user.signUp()
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword('asdf');
|
user.setPassword('asdf');
|
||||||
user.setUsername('2');
|
user.setUsername('2');
|
||||||
user.setEmail('2@b.c');
|
user.setEmail('2@b.c');
|
||||||
@@ -374,7 +374,7 @@ describe('miscellaneous', function() {
|
|||||||
let triggerTime = 0;
|
let triggerTime = 0;
|
||||||
// Register a mock beforeSave hook
|
// Register a mock beforeSave hook
|
||||||
Parse.Cloud.beforeSave('GameScore', (req, res) => {
|
Parse.Cloud.beforeSave('GameScore', (req, res) => {
|
||||||
let object = req.object;
|
const object = req.object;
|
||||||
expect(object instanceof Parse.Object).toBeTruthy();
|
expect(object instanceof Parse.Object).toBeTruthy();
|
||||||
expect(object.get('fooAgain')).toEqual('barAgain');
|
expect(object.get('fooAgain')).toEqual('barAgain');
|
||||||
if (triggerTime == 0) {
|
if (triggerTime == 0) {
|
||||||
@@ -397,7 +397,7 @@ describe('miscellaneous', function() {
|
|||||||
res.success();
|
res.success();
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('GameScore');
|
const obj = new Parse.Object('GameScore');
|
||||||
obj.set('foo', 'bar');
|
obj.set('foo', 'bar');
|
||||||
obj.set('fooAgain', 'barAgain');
|
obj.set('fooAgain', 'barAgain');
|
||||||
obj.save().then(() => {
|
obj.save().then(() => {
|
||||||
@@ -417,13 +417,13 @@ describe('miscellaneous', function() {
|
|||||||
let triggerTime = 0;
|
let triggerTime = 0;
|
||||||
// Register a mock beforeSave hook
|
// Register a mock beforeSave hook
|
||||||
Parse.Cloud.beforeSave('GameScore', (req, res) => {
|
Parse.Cloud.beforeSave('GameScore', (req, res) => {
|
||||||
let object = req.object;
|
const object = req.object;
|
||||||
object.set('foo', 'bar');
|
object.set('foo', 'bar');
|
||||||
triggerTime++;
|
triggerTime++;
|
||||||
res.success(object);
|
res.success(object);
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('GameScore');
|
const obj = new Parse.Object('GameScore');
|
||||||
obj.set('foo', 'baz');
|
obj.set('foo', 'baz');
|
||||||
obj.save().then(() => {
|
obj.save().then(() => {
|
||||||
expect(triggerTime).toBe(1);
|
expect(triggerTime).toBe(1);
|
||||||
@@ -439,10 +439,10 @@ describe('miscellaneous', function() {
|
|||||||
let triggerTime = 0;
|
let triggerTime = 0;
|
||||||
// Register a mock beforeSave hook
|
// Register a mock beforeSave hook
|
||||||
Parse.Cloud.beforeSave('GameScore', (req, res) => {
|
Parse.Cloud.beforeSave('GameScore', (req, res) => {
|
||||||
let object = req.object;
|
const object = req.object;
|
||||||
expect(object instanceof Parse.Object).toBeTruthy();
|
expect(object instanceof Parse.Object).toBeTruthy();
|
||||||
expect(object.get('fooAgain')).toEqual('barAgain');
|
expect(object.get('fooAgain')).toEqual('barAgain');
|
||||||
let originalObject = req.original;
|
const originalObject = req.original;
|
||||||
if (triggerTime == 0) {
|
if (triggerTime == 0) {
|
||||||
// No id/createdAt/updatedAt
|
// No id/createdAt/updatedAt
|
||||||
expect(object.id).toBeUndefined();
|
expect(object.id).toBeUndefined();
|
||||||
@@ -472,7 +472,7 @@ describe('miscellaneous', function() {
|
|||||||
res.success();
|
res.success();
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('GameScore');
|
const obj = new Parse.Object('GameScore');
|
||||||
obj.set('foo', 'bar');
|
obj.set('foo', 'bar');
|
||||||
obj.set('fooAgain', 'barAgain');
|
obj.set('fooAgain', 'barAgain');
|
||||||
obj.save().then(() => {
|
obj.save().then(() => {
|
||||||
@@ -490,13 +490,13 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('pointer mutation properly saves object', done => {
|
it('pointer mutation properly saves object', done => {
|
||||||
let className = 'GameScore';
|
const className = 'GameScore';
|
||||||
|
|
||||||
Parse.Cloud.beforeSave(className, (req, res) => {
|
Parse.Cloud.beforeSave(className, (req, res) => {
|
||||||
let object = req.object;
|
const object = req.object;
|
||||||
expect(object instanceof Parse.Object).toBeTruthy();
|
expect(object instanceof Parse.Object).toBeTruthy();
|
||||||
|
|
||||||
let child = object.get('child');
|
const child = object.get('child');
|
||||||
expect(child instanceof Parse.Object).toBeTruthy();
|
expect(child instanceof Parse.Object).toBeTruthy();
|
||||||
child.set('a', 'b');
|
child.set('a', 'b');
|
||||||
child.save().then(() => {
|
child.save().then(() => {
|
||||||
@@ -504,20 +504,20 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object(className);
|
const obj = new Parse.Object(className);
|
||||||
obj.set('foo', 'bar');
|
obj.set('foo', 'bar');
|
||||||
|
|
||||||
let child = new Parse.Object('Child');
|
const child = new Parse.Object('Child');
|
||||||
child.save().then(() => {
|
child.save().then(() => {
|
||||||
obj.set('child', child);
|
obj.set('child', child);
|
||||||
return obj.save();
|
return obj.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query(className);
|
const query = new Parse.Query(className);
|
||||||
query.include('child');
|
query.include('child');
|
||||||
return query.get(obj.id).then(objAgain => {
|
return query.get(obj.id).then(objAgain => {
|
||||||
expect(objAgain.get('foo')).toEqual('bar');
|
expect(objAgain.get('foo')).toEqual('bar');
|
||||||
|
|
||||||
let childAgain = objAgain.get('child');
|
const childAgain = objAgain.get('child');
|
||||||
expect(childAgain instanceof Parse.Object).toBeTruthy();
|
expect(childAgain instanceof Parse.Object).toBeTruthy();
|
||||||
expect(childAgain.get('a')).toEqual('b');
|
expect(childAgain.get('a')).toEqual('b');
|
||||||
|
|
||||||
@@ -703,9 +703,9 @@ describe('miscellaneous', function() {
|
|||||||
var triggerTime = 0;
|
var triggerTime = 0;
|
||||||
// Register a mock beforeSave hook
|
// Register a mock beforeSave hook
|
||||||
Parse.Cloud.afterSave('GameScore', function(req, res) {
|
Parse.Cloud.afterSave('GameScore', function(req, res) {
|
||||||
let object = req.object;
|
const object = req.object;
|
||||||
expect(object instanceof Parse.Object).toBeTruthy();
|
expect(object instanceof Parse.Object).toBeTruthy();
|
||||||
let originalObject = req.original;
|
const originalObject = req.original;
|
||||||
if (triggerTime == 0) {
|
if (triggerTime == 0) {
|
||||||
// Create
|
// Create
|
||||||
expect(object.get('yolo')).toEqual(1);
|
expect(object.get('yolo')).toEqual(1);
|
||||||
@@ -740,13 +740,13 @@ describe('miscellaneous', function() {
|
|||||||
let triggerTime = 0;
|
let triggerTime = 0;
|
||||||
// Register a mock beforeSave hook
|
// Register a mock beforeSave hook
|
||||||
Parse.Cloud.beforeSave('GameScore', function(req, res) {
|
Parse.Cloud.beforeSave('GameScore', function(req, res) {
|
||||||
let object = req.object;
|
const object = req.object;
|
||||||
if (triggerTime == 0) {
|
if (triggerTime == 0) {
|
||||||
let acl = object.getACL();
|
const acl = object.getACL();
|
||||||
expect(acl.getPublicReadAccess()).toBeTruthy();
|
expect(acl.getPublicReadAccess()).toBeTruthy();
|
||||||
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
||||||
} else if (triggerTime == 1) {
|
} else if (triggerTime == 1) {
|
||||||
let acl = object.getACL();
|
const acl = object.getACL();
|
||||||
expect(acl.getPublicReadAccess()).toBeFalsy();
|
expect(acl.getPublicReadAccess()).toBeFalsy();
|
||||||
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
||||||
} else {
|
} else {
|
||||||
@@ -756,8 +756,8 @@ describe('miscellaneous', function() {
|
|||||||
res.success();
|
res.success();
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('GameScore');
|
const obj = new Parse.Object('GameScore');
|
||||||
let acl = new Parse.ACL();
|
const acl = new Parse.ACL();
|
||||||
acl.setPublicReadAccess(true);
|
acl.setPublicReadAccess(true);
|
||||||
acl.setPublicWriteAccess(true);
|
acl.setPublicWriteAccess(true);
|
||||||
obj.setACL(acl);
|
obj.setACL(acl);
|
||||||
@@ -779,13 +779,13 @@ describe('miscellaneous', function() {
|
|||||||
let triggerTime = 0;
|
let triggerTime = 0;
|
||||||
// Register a mock beforeSave hook
|
// Register a mock beforeSave hook
|
||||||
Parse.Cloud.afterSave('GameScore', function(req, res) {
|
Parse.Cloud.afterSave('GameScore', function(req, res) {
|
||||||
let object = req.object;
|
const object = req.object;
|
||||||
if (triggerTime == 0) {
|
if (triggerTime == 0) {
|
||||||
let acl = object.getACL();
|
const acl = object.getACL();
|
||||||
expect(acl.getPublicReadAccess()).toBeTruthy();
|
expect(acl.getPublicReadAccess()).toBeTruthy();
|
||||||
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
||||||
} else if (triggerTime == 1) {
|
} else if (triggerTime == 1) {
|
||||||
let acl = object.getACL();
|
const acl = object.getACL();
|
||||||
expect(acl.getPublicReadAccess()).toBeFalsy();
|
expect(acl.getPublicReadAccess()).toBeFalsy();
|
||||||
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
expect(acl.getPublicWriteAccess()).toBeTruthy();
|
||||||
} else {
|
} else {
|
||||||
@@ -795,8 +795,8 @@ describe('miscellaneous', function() {
|
|||||||
res.success();
|
res.success();
|
||||||
});
|
});
|
||||||
|
|
||||||
let obj = new Parse.Object('GameScore');
|
const obj = new Parse.Object('GameScore');
|
||||||
let acl = new Parse.ACL();
|
const acl = new Parse.ACL();
|
||||||
acl.setPublicReadAccess(true);
|
acl.setPublicReadAccess(true);
|
||||||
acl.setPublicWriteAccess(true);
|
acl.setPublicWriteAccess(true);
|
||||||
obj.setACL(acl);
|
obj.setACL(acl);
|
||||||
@@ -815,7 +815,7 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should return the updated fields on PUT', done => {
|
it('should return the updated fields on PUT', done => {
|
||||||
let obj = new Parse.Object('GameScore');
|
const obj = new Parse.Object('GameScore');
|
||||||
obj.save({a:'hello', c: 1, d: ['1'], e:['1'], f:['1','2']}).then(() => {
|
obj.save({a:'hello', c: 1, d: ['1'], e:['1'], f:['1','2']}).then(() => {
|
||||||
var headers = {
|
var headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
@@ -1037,7 +1037,7 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('can handle date params in cloud functions (#2214)', done => {
|
it('can handle date params in cloud functions (#2214)', done => {
|
||||||
let date = new Date();
|
const date = new Date();
|
||||||
Parse.Cloud.define('dateFunc', (request, response) => {
|
Parse.Cloud.define('dateFunc', (request, response) => {
|
||||||
expect(request.params.date.__type).toEqual('Date');
|
expect(request.params.date.__type).toEqual('Date');
|
||||||
expect(request.params.date.iso).toEqual(date.toISOString());
|
expect(request.params.date.iso).toEqual(date.toISOString());
|
||||||
@@ -1133,27 +1133,27 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('dedupes an installation properly and returns updatedAt', (done) => {
|
it('dedupes an installation properly and returns updatedAt', (done) => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest'
|
'X-Parse-REST-API-Key': 'rest'
|
||||||
};
|
};
|
||||||
let data = {
|
const data = {
|
||||||
'installationId': 'lkjsahdfkjhsdfkjhsdfkjhsdf',
|
'installationId': 'lkjsahdfkjhsdfkjhsdfkjhsdf',
|
||||||
'deviceType': 'embedded'
|
'deviceType': 'embedded'
|
||||||
};
|
};
|
||||||
let requestOptions = {
|
const requestOptions = {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
url: 'http://localhost:8378/1/installations',
|
url: 'http://localhost:8378/1/installations',
|
||||||
body: JSON.stringify(data)
|
body: JSON.stringify(data)
|
||||||
};
|
};
|
||||||
request.post(requestOptions, (error, response, body) => {
|
request.post(requestOptions, (error, response, body) => {
|
||||||
expect(error).toBe(null);
|
expect(error).toBe(null);
|
||||||
let b = JSON.parse(body);
|
const b = JSON.parse(body);
|
||||||
expect(typeof b.objectId).toEqual('string');
|
expect(typeof b.objectId).toEqual('string');
|
||||||
request.post(requestOptions, (error, response, body) => {
|
request.post(requestOptions, (error, response, body) => {
|
||||||
expect(error).toBe(null);
|
expect(error).toBe(null);
|
||||||
let b = JSON.parse(body);
|
const b = JSON.parse(body);
|
||||||
expect(typeof b.updatedAt).toEqual('string');
|
expect(typeof b.updatedAt).toEqual('string');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
@@ -1161,17 +1161,17 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('android login providing empty authData block works', (done) => {
|
it('android login providing empty authData block works', (done) => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest'
|
'X-Parse-REST-API-Key': 'rest'
|
||||||
};
|
};
|
||||||
let data = {
|
const data = {
|
||||||
username: 'pulse1989',
|
username: 'pulse1989',
|
||||||
password: 'password1234',
|
password: 'password1234',
|
||||||
authData: {}
|
authData: {}
|
||||||
};
|
};
|
||||||
let requestOptions = {
|
const requestOptions = {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
url: 'http://localhost:8378/1/users',
|
url: 'http://localhost:8378/1/users',
|
||||||
body: JSON.stringify(data)
|
body: JSON.stringify(data)
|
||||||
@@ -1181,7 +1181,7 @@ describe('miscellaneous', function() {
|
|||||||
requestOptions.url = 'http://localhost:8378/1/login';
|
requestOptions.url = 'http://localhost:8378/1/login';
|
||||||
request.get(requestOptions, (error, response, body) => {
|
request.get(requestOptions, (error, response, body) => {
|
||||||
expect(error).toBe(null);
|
expect(error).toBe(null);
|
||||||
let b = JSON.parse(body);
|
const b = JSON.parse(body);
|
||||||
expect(typeof b['sessionToken']).toEqual('string');
|
expect(typeof b['sessionToken']).toEqual('string');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
@@ -1189,25 +1189,25 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('gets relation fields', (done) => {
|
it('gets relation fields', (done) => {
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
let relatedObject = new Parse.Object('RelatedObject');
|
const relatedObject = new Parse.Object('RelatedObject');
|
||||||
Parse.Object.saveAll([object, relatedObject]).then(() => {
|
Parse.Object.saveAll([object, relatedObject]).then(() => {
|
||||||
object.relation('related').add(relatedObject);
|
object.relation('related').add(relatedObject);
|
||||||
return object.save();
|
return object.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest'
|
'X-Parse-REST-API-Key': 'rest'
|
||||||
};
|
};
|
||||||
let requestOptions = {
|
const requestOptions = {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
url: 'http://localhost:8378/1/classes/AnObject',
|
url: 'http://localhost:8378/1/classes/AnObject',
|
||||||
json: true
|
json: true
|
||||||
};
|
};
|
||||||
request.get(requestOptions, (err, res, body) => {
|
request.get(requestOptions, (err, res, body) => {
|
||||||
expect(body.results.length).toBe(1);
|
expect(body.results.length).toBe(1);
|
||||||
let result = body.results[0];
|
const result = body.results[0];
|
||||||
expect(result.related).toEqual({
|
expect(result.related).toEqual({
|
||||||
__type: "Relation",
|
__type: "Relation",
|
||||||
className: 'RelatedObject'
|
className: 'RelatedObject'
|
||||||
@@ -1221,20 +1221,20 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly returns incremented values (#1554)', (done) => {
|
it('properly returns incremented values (#1554)', (done) => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest'
|
'X-Parse-REST-API-Key': 'rest'
|
||||||
};
|
};
|
||||||
let requestOptions = {
|
const requestOptions = {
|
||||||
headers: headers,
|
headers: headers,
|
||||||
url: 'http://localhost:8378/1/classes/AnObject',
|
url: 'http://localhost:8378/1/classes/AnObject',
|
||||||
json: true
|
json: true
|
||||||
};
|
};
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
|
|
||||||
function runIncrement(amount) {
|
function runIncrement(amount) {
|
||||||
let options = Object.assign({}, requestOptions, {
|
const options = Object.assign({}, requestOptions, {
|
||||||
body: {
|
body: {
|
||||||
"key": {
|
"key": {
|
||||||
__op: 'Increment',
|
__op: 'Increment',
|
||||||
@@ -1266,7 +1266,7 @@ describe('miscellaneous', function() {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('ignores _RevocableSession "header" send by JS SDK', (done) => {
|
it('ignores _RevocableSession "header" send by JS SDK', (done) => {
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('a', 'b');
|
object.set('a', 'b');
|
||||||
object.save().then(() => {
|
object.save().then(() => {
|
||||||
request.post({
|
request.post({
|
||||||
@@ -1285,7 +1285,7 @@ describe('miscellaneous', function() {
|
|||||||
expect(body.error).toBeUndefined();
|
expect(body.error).toBeUndefined();
|
||||||
expect(body.results).not.toBeUndefined();
|
expect(body.results).not.toBeUndefined();
|
||||||
expect(body.results.length).toBe(1);
|
expect(body.results.length).toBe(1);
|
||||||
let result = body.results[0];
|
const result = body.results[0];
|
||||||
expect(result.a).toBe('b');
|
expect(result.a).toBe('b');
|
||||||
done();
|
done();
|
||||||
})
|
})
|
||||||
@@ -1293,7 +1293,7 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('doesnt convert interior keys of objects that use special names', done => {
|
it('doesnt convert interior keys of objects that use special names', done => {
|
||||||
let obj = new Parse.Object('Obj');
|
const obj = new Parse.Object('Obj');
|
||||||
obj.set('val', { createdAt: 'a', updatedAt: 1 });
|
obj.set('val', { createdAt: 'a', updatedAt: 1 });
|
||||||
obj.save()
|
obj.save()
|
||||||
.then(obj => new Parse.Query('Obj').get(obj.id))
|
.then(obj => new Parse.Query('Obj').get(obj.id))
|
||||||
@@ -1361,10 +1361,10 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('does not change inner objects if the key has the same name as a geopoint field on the class, and the value is an array of length 2, or if the key has the same name as a file field on the class, and the value is a string', done => {
|
it('does not change inner objects if the key has the same name as a geopoint field on the class, and the value is an array of length 2, or if the key has the same name as a file field on the class, and the value is a string', done => {
|
||||||
let file = new Parse.File('myfile.txt', { base64: 'eAo=' });
|
const file = new Parse.File('myfile.txt', { base64: 'eAo=' });
|
||||||
file.save()
|
file.save()
|
||||||
.then(f => {
|
.then(f => {
|
||||||
let obj = new Parse.Object('O');
|
const obj = new Parse.Object('O');
|
||||||
obj.set('fileField', f);
|
obj.set('fileField', f);
|
||||||
obj.set('geoField', new Parse.GeoPoint(0, 0));
|
obj.set('geoField', new Parse.GeoPoint(0, 0));
|
||||||
obj.set('innerObj', {
|
obj.set('innerObj', {
|
||||||
@@ -1387,17 +1387,17 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('purge all objects in class', (done) => {
|
it('purge all objects in class', (done) => {
|
||||||
let object = new Parse.Object('TestObject');
|
const object = new Parse.Object('TestObject');
|
||||||
object.set('foo', 'bar');
|
object.set('foo', 'bar');
|
||||||
let object2 = new Parse.Object('TestObject');
|
const object2 = new Parse.Object('TestObject');
|
||||||
object2.set('alice', 'wonderland');
|
object2.set('alice', 'wonderland');
|
||||||
Parse.Object.saveAll([object, object2])
|
Parse.Object.saveAll([object, object2])
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let query = new Parse.Query(TestObject);
|
const query = new Parse.Query(TestObject);
|
||||||
return query.count()
|
return query.count()
|
||||||
}).then((count) => {
|
}).then((count) => {
|
||||||
expect(count).toBe(2);
|
expect(count).toBe(2);
|
||||||
let headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-Master-Key': 'test'
|
'X-Parse-Master-Key': 'test'
|
||||||
@@ -1408,7 +1408,7 @@ describe('miscellaneous', function() {
|
|||||||
json: true
|
json: true
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
expect(err).toBe(null);
|
expect(err).toBe(null);
|
||||||
let query = new Parse.Query(TestObject);
|
const query = new Parse.Query(TestObject);
|
||||||
return query.count().then((count) => {
|
return query.count().then((count) => {
|
||||||
expect(count).toBe(0);
|
expect(count).toBe(0);
|
||||||
done();
|
done();
|
||||||
@@ -1418,7 +1418,7 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('fail on purge all objects in class without master key', (done) => {
|
it('fail on purge all objects in class without master key', (done) => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest'
|
'X-Parse-REST-API-Key': 'rest'
|
||||||
@@ -1437,7 +1437,7 @@ describe('miscellaneous', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('purge all objects in _Role also purge cache', (done) => {
|
it('purge all objects in _Role also purge cache', (done) => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-Master-Key': 'test'
|
'X-Parse-Master-Key': 'test'
|
||||||
@@ -1445,26 +1445,26 @@ describe('miscellaneous', function() {
|
|||||||
var user, object;
|
var user, object;
|
||||||
createTestUser().then((x) => {
|
createTestUser().then((x) => {
|
||||||
user = x;
|
user = x;
|
||||||
let acl = new Parse.ACL();
|
const acl = new Parse.ACL();
|
||||||
acl.setPublicReadAccess(true);
|
acl.setPublicReadAccess(true);
|
||||||
acl.setPublicWriteAccess(false);
|
acl.setPublicWriteAccess(false);
|
||||||
let role = new Parse.Object('_Role');
|
const role = new Parse.Object('_Role');
|
||||||
role.set('name', 'TestRole');
|
role.set('name', 'TestRole');
|
||||||
role.setACL(acl);
|
role.setACL(acl);
|
||||||
let users = role.relation('users');
|
const users = role.relation('users');
|
||||||
users.add(user);
|
users.add(user);
|
||||||
return role.save({}, { useMasterKey: true });
|
return role.save({}, { useMasterKey: true });
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('_Role');
|
const query = new Parse.Query('_Role');
|
||||||
return query.find({ useMasterKey: true });
|
return query.find({ useMasterKey: true });
|
||||||
}).then((x) => {
|
}).then((x) => {
|
||||||
expect(x.length).toEqual(1);
|
expect(x.length).toEqual(1);
|
||||||
let relation = x[0].relation('users').query();
|
const relation = x[0].relation('users').query();
|
||||||
return relation.first({ useMasterKey: true });
|
return relation.first({ useMasterKey: true });
|
||||||
}).then((x) => {
|
}).then((x) => {
|
||||||
expect(x.id).toEqual(user.id);
|
expect(x.id).toEqual(user.id);
|
||||||
object = new Parse.Object('TestObject');
|
object = new Parse.Object('TestObject');
|
||||||
let acl = new Parse.ACL();
|
const acl = new Parse.ACL();
|
||||||
acl.setPublicReadAccess(false);
|
acl.setPublicReadAccess(false);
|
||||||
acl.setPublicWriteAccess(false);
|
acl.setPublicWriteAccess(false);
|
||||||
acl.setRoleReadAccess('TestRole', true);
|
acl.setRoleReadAccess('TestRole', true);
|
||||||
@@ -1472,7 +1472,7 @@ describe('miscellaneous', function() {
|
|||||||
object.setACL(acl);
|
object.setACL(acl);
|
||||||
return object.save();
|
return object.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('TestObject');
|
const query = new Parse.Query('TestObject');
|
||||||
return query.find({ sessionToken: user.getSessionToken() });
|
return query.find({ sessionToken: user.getSessionToken() });
|
||||||
}).then((x) => {
|
}).then((x) => {
|
||||||
expect(x.length).toEqual(1);
|
expect(x.length).toEqual(1);
|
||||||
@@ -1483,7 +1483,7 @@ describe('miscellaneous', function() {
|
|||||||
json: true
|
json: true
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('TestObject');
|
const query = new Parse.Query('TestObject');
|
||||||
return query.get(object.id, { sessionToken: user.getSessionToken() });
|
return query.get(object.id, { sessionToken: user.getSessionToken() });
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
fail('Should not succeed');
|
fail('Should not succeed');
|
||||||
@@ -1502,7 +1502,7 @@ describe('miscellaneous', function() {
|
|||||||
response.success();
|
response.success();
|
||||||
});
|
});
|
||||||
|
|
||||||
let object = new Parse.Object('MyObject');
|
const object = new Parse.Object('MyObject');
|
||||||
object.set('key', 'value');
|
object.set('key', 'value');
|
||||||
object.save().then(() => {
|
object.save().then(() => {
|
||||||
return object.save({'secret': 'should not update schema'});
|
return object.save({'secret': 'should not update schema'});
|
||||||
@@ -1520,7 +1520,7 @@ describe('miscellaneous', function() {
|
|||||||
json: true
|
json: true
|
||||||
});
|
});
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
let fields = res.fields;
|
const fields = res.fields;
|
||||||
expect(fields.secret).toBeUndefined();
|
expect(fields.secret).toBeUndefined();
|
||||||
done();
|
done();
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
@@ -1532,7 +1532,7 @@ describe('miscellaneous', function() {
|
|||||||
|
|
||||||
describe_only_db('mongo')('legacy _acl', () => {
|
describe_only_db('mongo')('legacy _acl', () => {
|
||||||
it('should have _acl when locking down (regression for #2465)', (done) => {
|
it('should have _acl when locking down (regression for #2465)', (done) => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest'
|
'X-Parse-REST-API-Key': 'rest'
|
||||||
}
|
}
|
||||||
@@ -1546,13 +1546,13 @@ describe_only_db('mongo')('legacy _acl', () => {
|
|||||||
},
|
},
|
||||||
json: true
|
json: true
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
let adapter = config.database.adapter;
|
const adapter = config.database.adapter;
|
||||||
return adapter._adaptiveCollection("Report")
|
return adapter._adaptiveCollection("Report")
|
||||||
.then(collection => collection.find({}))
|
.then(collection => collection.find({}))
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let result = results[0];
|
const result = results[0];
|
||||||
expect(result.name).toEqual('My Report');
|
expect(result.name).toEqual('My Report');
|
||||||
expect(result._wperm).toEqual([]);
|
expect(result._wperm).toEqual([]);
|
||||||
expect(result._rperm).toEqual([]);
|
expect(result._rperm).toEqual([]);
|
||||||
|
|||||||
@@ -563,7 +563,7 @@ describe('Parse.File testing', () => {
|
|||||||
var query = new Parse.Query('FileTest');
|
var query = new Parse.Query('FileTest');
|
||||||
return query.first();
|
return query.first();
|
||||||
}).then(result => {
|
}).then(result => {
|
||||||
let fileAgain = result.get('file');
|
const fileAgain = result.get('file');
|
||||||
expect(fileAgain.url()).toMatch(/123.txt$/);
|
expect(fileAgain.url()).toMatch(/123.txt$/);
|
||||||
done();
|
done();
|
||||||
}).catch((e) => {
|
}).catch((e) => {
|
||||||
@@ -587,7 +587,7 @@ describe('Parse.File testing', () => {
|
|||||||
var query = new Parse.Query('FileTest');
|
var query = new Parse.Query('FileTest');
|
||||||
return query.first();
|
return query.first();
|
||||||
}).then(result => {
|
}).then(result => {
|
||||||
let fileAgain = result.get('file');
|
const fileAgain = result.get('file');
|
||||||
expect(fileAgain.url().indexOf('https://mydomain/parse')).toBe(0);
|
expect(fileAgain.url().indexOf('https://mydomain/parse')).toBe(0);
|
||||||
done();
|
done();
|
||||||
}).catch((e) => {
|
}).catch((e) => {
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
var request = require('request');
|
var request = require('request');
|
||||||
let Config = require('../src/Config');
|
const Config = require('../src/Config');
|
||||||
|
|
||||||
describe('a GlobalConfig', () => {
|
describe('a GlobalConfig', () => {
|
||||||
beforeEach(done => {
|
beforeEach(done => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
let query = on_db('mongo', () => {
|
const query = on_db('mongo', () => {
|
||||||
// Legacy is with an int...
|
// Legacy is with an int...
|
||||||
return { objectId: 1 };
|
return { objectId: 1 };
|
||||||
}, () => {
|
}, () => {
|
||||||
@@ -104,7 +104,7 @@ describe('a GlobalConfig', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('failed getting config when it is missing', (done) => {
|
it('failed getting config when it is missing', (done) => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
config.database.adapter.deleteObjectsByQuery(
|
config.database.adapter.deleteObjectsByQuery(
|
||||||
'_GlobalConfig',
|
'_GlobalConfig',
|
||||||
{ fields: { params: { __type: 'String' } } },
|
{ fields: { params: { __type: 'String' } } },
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ var bodyParser = require('body-parser');
|
|||||||
|
|
||||||
var port = 12345;
|
var port = 12345;
|
||||||
var hookServerURL = "http://localhost:"+port;
|
var hookServerURL = "http://localhost:"+port;
|
||||||
let AppCache = require('../src/cache').AppCache;
|
const AppCache = require('../src/cache').AppCache;
|
||||||
|
|
||||||
var app = express();
|
var app = express();
|
||||||
app.use(bodyParser.json({ 'type': '*/*' }))
|
app.use(bodyParser.json({ 'type': '*/*' }))
|
||||||
|
|||||||
@@ -2,15 +2,15 @@
|
|||||||
// These tests check the Installations functionality of the REST API.
|
// These tests check the Installations functionality of the REST API.
|
||||||
// Ported from installation_collection_test.go
|
// Ported from installation_collection_test.go
|
||||||
|
|
||||||
let auth = require('../src/Auth');
|
const auth = require('../src/Auth');
|
||||||
let Config = require('../src/Config');
|
const Config = require('../src/Config');
|
||||||
let Parse = require('parse/node').Parse;
|
const Parse = require('parse/node').Parse;
|
||||||
let rest = require('../src/rest');
|
const rest = require('../src/rest');
|
||||||
let request = require("request");
|
const request = require("request");
|
||||||
|
|
||||||
let config;
|
let config;
|
||||||
let database;
|
let database;
|
||||||
let defaultColumns = require('../src/Controllers/SchemaController').defaultColumns;
|
const defaultColumns = require('../src/Controllers/SchemaController').defaultColumns;
|
||||||
|
|
||||||
const installationSchema = { fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation) };
|
const installationSchema = { fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation) };
|
||||||
|
|
||||||
@@ -130,7 +130,7 @@ describe('Installations', () => {
|
|||||||
};
|
};
|
||||||
rest.create(config, auth.nobody(config), '_Installation', input)
|
rest.create(config, auth.nobody(config), '_Installation', input)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let query = new Parse.Query(Parse.Installation);
|
const query = new Parse.Query(Parse.Installation);
|
||||||
return query.find()
|
return query.find()
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
fail('Should not succeed!');
|
fail('Should not succeed!');
|
||||||
@@ -151,7 +151,7 @@ describe('Installations', () => {
|
|||||||
};
|
};
|
||||||
rest.create(config, auth.nobody(config), '_Installation', input)
|
rest.create(config, auth.nobody(config), '_Installation', input)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let query = new Parse.Query(Parse.Installation);
|
const query = new Parse.Query(Parse.Installation);
|
||||||
return query.find({useMasterKey: true});
|
return query.find({useMasterKey: true});
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
@@ -842,15 +842,15 @@ describe('Installations', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('allows you to get your own installation (regression test for #1718)', done => {
|
it('allows you to get your own installation (regression test for #1718)', done => {
|
||||||
let installId = '12345678-abcd-abcd-abcd-123456789abc';
|
const installId = '12345678-abcd-abcd-abcd-123456789abc';
|
||||||
let device = 'android';
|
const device = 'android';
|
||||||
let input = {
|
const input = {
|
||||||
'installationId': installId,
|
'installationId': installId,
|
||||||
'deviceType': device
|
'deviceType': device
|
||||||
};
|
};
|
||||||
rest.create(config, auth.nobody(config), '_Installation', input)
|
rest.create(config, auth.nobody(config), '_Installation', input)
|
||||||
.then(createResult => {
|
.then(createResult => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest',
|
'X-Parse-REST-API-Key': 'rest',
|
||||||
};
|
};
|
||||||
@@ -871,15 +871,15 @@ describe('Installations', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('allows you to update installation from header (#2090)', done => {
|
it('allows you to update installation from header (#2090)', done => {
|
||||||
let installId = '12345678-abcd-abcd-abcd-123456789abc';
|
const installId = '12345678-abcd-abcd-abcd-123456789abc';
|
||||||
let device = 'android';
|
const device = 'android';
|
||||||
let input = {
|
const input = {
|
||||||
'installationId': installId,
|
'installationId': installId,
|
||||||
'deviceType': device
|
'deviceType': device
|
||||||
};
|
};
|
||||||
rest.create(config, auth.nobody(config), '_Installation', input)
|
rest.create(config, auth.nobody(config), '_Installation', input)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let headers = {
|
const headers = {
|
||||||
'X-Parse-Application-Id': 'test',
|
'X-Parse-Application-Id': 'test',
|
||||||
'X-Parse-REST-API-Key': 'rest',
|
'X-Parse-REST-API-Key': 'rest',
|
||||||
'X-Parse-Installation-Id': installId
|
'X-Parse-Installation-Id': installId
|
||||||
@@ -905,15 +905,15 @@ describe('Installations', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('allows you to update installation with masterKey', done => {
|
it('allows you to update installation with masterKey', done => {
|
||||||
let installId = '12345678-abcd-abcd-abcd-123456789abc';
|
const installId = '12345678-abcd-abcd-abcd-123456789abc';
|
||||||
let device = 'android';
|
const device = 'android';
|
||||||
let input = {
|
const input = {
|
||||||
'installationId': installId,
|
'installationId': installId,
|
||||||
'deviceType': device
|
'deviceType': device
|
||||||
};
|
};
|
||||||
rest.create(config, auth.nobody(config), '_Installation', input)
|
rest.create(config, auth.nobody(config), '_Installation', input)
|
||||||
.then(createResult => {
|
.then(createResult => {
|
||||||
let installationObj = Parse.Installation.createWithoutData(createResult.response.objectId);
|
const installationObj = Parse.Installation.createWithoutData(createResult.response.objectId);
|
||||||
installationObj.set('customField', 'custom value');
|
installationObj.set('customField', 'custom value');
|
||||||
return installationObj.save(null, {useMasterKey: true});
|
return installationObj.save(null, {useMasterKey: true});
|
||||||
}).then(updateResult => {
|
}).then(updateResult => {
|
||||||
@@ -928,14 +928,14 @@ describe('Installations', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should properly handle installation save #2780', done => {
|
it('should properly handle installation save #2780', done => {
|
||||||
let installId = '12345678-abcd-abcd-abcd-123456789abc';
|
const installId = '12345678-abcd-abcd-abcd-123456789abc';
|
||||||
let device = 'android';
|
const device = 'android';
|
||||||
let input = {
|
const input = {
|
||||||
'installationId': installId,
|
'installationId': installId,
|
||||||
'deviceType': device
|
'deviceType': device
|
||||||
};
|
};
|
||||||
rest.create(config, auth.nobody(config), '_Installation', input).then(() => {
|
rest.create(config, auth.nobody(config), '_Installation', input).then(() => {
|
||||||
let query = new Parse.Query(Parse.Installation);
|
const query = new Parse.Query(Parse.Installation);
|
||||||
query.equalTo('installationId', installId);
|
query.equalTo('installationId', installId);
|
||||||
query.first({useMasterKey: true}).then((installation) => {
|
query.first({useMasterKey: true}).then((installation) => {
|
||||||
return installation.save({
|
return installation.save({
|
||||||
@@ -951,14 +951,14 @@ describe('Installations', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should properly reject updating installationId', done => {
|
it('should properly reject updating installationId', done => {
|
||||||
let installId = '12345678-abcd-abcd-abcd-123456789abc';
|
const installId = '12345678-abcd-abcd-abcd-123456789abc';
|
||||||
let device = 'android';
|
const device = 'android';
|
||||||
let input = {
|
const input = {
|
||||||
'installationId': installId,
|
'installationId': installId,
|
||||||
'deviceType': device
|
'deviceType': device
|
||||||
};
|
};
|
||||||
rest.create(config, auth.nobody(config), '_Installation', input).then(() => {
|
rest.create(config, auth.nobody(config), '_Installation', input).then(() => {
|
||||||
let query = new Parse.Query(Parse.Installation);
|
const query = new Parse.Query(Parse.Installation);
|
||||||
query.equalTo('installationId', installId);
|
query.equalTo('installationId', installId);
|
||||||
query.first({useMasterKey: true}).then((installation) => {
|
query.first({useMasterKey: true}).then((installation) => {
|
||||||
return installation.save({
|
return installation.save({
|
||||||
|
|||||||
@@ -358,7 +358,7 @@ describe('ParseLiveQueryServer', function() {
|
|||||||
expect(args[0]).toBe(parseWebSocket);
|
expect(args[0]).toBe(parseWebSocket);
|
||||||
expect(JSON.stringify(args[1])).toBe(updateRequest);
|
expect(JSON.stringify(args[1])).toBe(updateRequest);
|
||||||
expect(parseLiveQueryServer._handleUnsubscribe).toHaveBeenCalled();
|
expect(parseLiveQueryServer._handleUnsubscribe).toHaveBeenCalled();
|
||||||
let unsubArgs = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args;
|
const unsubArgs = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args;
|
||||||
expect(unsubArgs.length).toBe(3);
|
expect(unsubArgs.length).toBe(3);
|
||||||
expect(unsubArgs[2]).toBe(false);
|
expect(unsubArgs[2]).toBe(false);
|
||||||
expect(parseLiveQueryServer._handleSubscribe).toHaveBeenCalled();
|
expect(parseLiveQueryServer._handleSubscribe).toHaveBeenCalled();
|
||||||
|
|||||||
@@ -596,8 +596,8 @@ describe('Parse.Object testing', () => {
|
|||||||
var query = new Parse.Query('X');
|
var query = new Parse.Query('X');
|
||||||
return query.get(x1.id);
|
return query.get(x1.id);
|
||||||
}).then((x3) => {
|
}).then((x3) => {
|
||||||
let stuff = x3.get('stuff');
|
const stuff = x3.get('stuff');
|
||||||
let expected = [1, 2, 4];
|
const expected = [1, 2, 4];
|
||||||
expect(stuff.length).toBe(expected.length);
|
expect(stuff.length).toBe(expected.length);
|
||||||
for (var i of stuff) {
|
for (var i of stuff) {
|
||||||
expect(expected.indexOf(i) >= 0).toBe(true);
|
expect(expected.indexOf(i) >= 0).toBe(true);
|
||||||
@@ -628,12 +628,12 @@ describe('Parse.Object testing', () => {
|
|||||||
var query = new Parse.Query('X');
|
var query = new Parse.Query('X');
|
||||||
return query.get(x1.id);
|
return query.get(x1.id);
|
||||||
}).then((x3) => {
|
}).then((x3) => {
|
||||||
let stuff = x3.get('stuff');
|
const stuff = x3.get('stuff');
|
||||||
let target = [1, {'hello': 'world'}, {'foo': 'bar'}, {'bar': 'baz'}];
|
const target = [1, {'hello': 'world'}, {'foo': 'bar'}, {'bar': 'baz'}];
|
||||||
expect(stuff.length).toEqual(target.length);
|
expect(stuff.length).toEqual(target.length);
|
||||||
let found = 0;
|
let found = 0;
|
||||||
for (let thing in target) {
|
for (const thing in target) {
|
||||||
for (let st in stuff) {
|
for (const st in stuff) {
|
||||||
if (st == thing) {
|
if (st == thing) {
|
||||||
found++;
|
found++;
|
||||||
}
|
}
|
||||||
@@ -1861,15 +1861,15 @@ describe('Parse.Object testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should have undefined includes when object is missing', (done) => {
|
it('should have undefined includes when object is missing', (done) => {
|
||||||
let obj1 = new Parse.Object("AnObject");
|
const obj1 = new Parse.Object("AnObject");
|
||||||
let obj2 = new Parse.Object("AnObject");
|
const obj2 = new Parse.Object("AnObject");
|
||||||
|
|
||||||
Parse.Object.saveAll([obj1, obj2]).then(() => {
|
Parse.Object.saveAll([obj1, obj2]).then(() => {
|
||||||
obj1.set("obj", obj2);
|
obj1.set("obj", obj2);
|
||||||
// Save the pointer, delete the pointee
|
// Save the pointer, delete the pointee
|
||||||
return obj1.save().then(() => { return obj2.destroy() });
|
return obj1.save().then(() => { return obj2.destroy() });
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query("AnObject");
|
const query = new Parse.Query("AnObject");
|
||||||
query.include("obj");
|
query.include("obj");
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
@@ -1877,7 +1877,7 @@ describe('Parse.Object testing', () => {
|
|||||||
if (res[0]) {
|
if (res[0]) {
|
||||||
expect(res[0].get("obj")).toBe(undefined);
|
expect(res[0].get("obj")).toBe(undefined);
|
||||||
}
|
}
|
||||||
let query = new Parse.Query("AnObject");
|
const query = new Parse.Query("AnObject");
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
expect(res.length).toBe(1);
|
expect(res.length).toBe(1);
|
||||||
@@ -1896,16 +1896,16 @@ describe('Parse.Object testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should have undefined includes when object is missing on deeper path', (done) => {
|
it('should have undefined includes when object is missing on deeper path', (done) => {
|
||||||
let obj1 = new Parse.Object("AnObject");
|
const obj1 = new Parse.Object("AnObject");
|
||||||
let obj2 = new Parse.Object("AnObject");
|
const obj2 = new Parse.Object("AnObject");
|
||||||
let obj3 = new Parse.Object("AnObject");
|
const obj3 = new Parse.Object("AnObject");
|
||||||
Parse.Object.saveAll([obj1, obj2, obj3]).then(() => {
|
Parse.Object.saveAll([obj1, obj2, obj3]).then(() => {
|
||||||
obj1.set("obj", obj2);
|
obj1.set("obj", obj2);
|
||||||
obj2.set("obj", obj3);
|
obj2.set("obj", obj3);
|
||||||
// Save the pointer, delete the pointee
|
// Save the pointer, delete the pointee
|
||||||
return Parse.Object.saveAll([obj1, obj2]).then(() => { return obj3.destroy() });
|
return Parse.Object.saveAll([obj1, obj2]).then(() => { return obj3.destroy() });
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query("AnObject");
|
const query = new Parse.Query("AnObject");
|
||||||
query.include("obj.obj");
|
query.include("obj.obj");
|
||||||
return query.get(obj1.id);
|
return query.get(obj1.id);
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
@@ -1919,9 +1919,9 @@ describe('Parse.Object testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle includes on null arrays #2752', (done) => {
|
it('should handle includes on null arrays #2752', (done) => {
|
||||||
let obj1 = new Parse.Object("AnObject");
|
const obj1 = new Parse.Object("AnObject");
|
||||||
let obj2 = new Parse.Object("AnotherObject");
|
const obj2 = new Parse.Object("AnotherObject");
|
||||||
let obj3 = new Parse.Object("NestedObject");
|
const obj3 = new Parse.Object("NestedObject");
|
||||||
obj3.set({
|
obj3.set({
|
||||||
"foo": "bar"
|
"foo": "bar"
|
||||||
})
|
})
|
||||||
@@ -1933,13 +1933,13 @@ describe('Parse.Object testing', () => {
|
|||||||
obj1.set("objects", [null, null, obj2]);
|
obj1.set("objects", [null, null, obj2]);
|
||||||
return obj1.save();
|
return obj1.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query("AnObject");
|
const query = new Parse.Query("AnObject");
|
||||||
query.include("objects.key");
|
query.include("objects.key");
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
let obj = res[0];
|
const obj = res[0];
|
||||||
expect(obj.get("objects")).not.toBe(undefined);
|
expect(obj.get("objects")).not.toBe(undefined);
|
||||||
let array = obj.get("objects");
|
const array = obj.get("objects");
|
||||||
expect(Array.isArray(array)).toBe(true);
|
expect(Array.isArray(array)).toBe(true);
|
||||||
expect(array[0]).toBe(null);
|
expect(array[0]).toBe(null);
|
||||||
expect(array[1]).toBe(null);
|
expect(array[1]).toBe(null);
|
||||||
@@ -1952,8 +1952,8 @@ describe('Parse.Object testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle select and include #2786', (done) => {
|
it('should handle select and include #2786', (done) => {
|
||||||
let score = new Parse.Object("GameScore");
|
const score = new Parse.Object("GameScore");
|
||||||
let player = new Parse.Object("Player");
|
const player = new Parse.Object("Player");
|
||||||
score.set({
|
score.set({
|
||||||
"score": 1234
|
"score": 1234
|
||||||
});
|
});
|
||||||
@@ -1963,14 +1963,14 @@ describe('Parse.Object testing', () => {
|
|||||||
player.set("other", "value");
|
player.set("other", "value");
|
||||||
return player.save();
|
return player.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query("Player");
|
const query = new Parse.Query("Player");
|
||||||
query.include("gameScore");
|
query.include("gameScore");
|
||||||
query.select("gameScore");
|
query.select("gameScore");
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
let obj = res[0];
|
const obj = res[0];
|
||||||
let gameScore = obj.get("gameScore");
|
const gameScore = obj.get("gameScore");
|
||||||
let other = obj.get("other");
|
const other = obj.get("other");
|
||||||
expect(other).toBeUndefined();
|
expect(other).toBeUndefined();
|
||||||
expect(gameScore).not.toBeUndefined();
|
expect(gameScore).not.toBeUndefined();
|
||||||
expect(gameScore.get("score")).toBe(1234);
|
expect(gameScore.get("score")).toBe(1234);
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ describe('ParsePubSub', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('can create publisher/sub with custom adapter', function() {
|
it('can create publisher/sub with custom adapter', function() {
|
||||||
let adapter = {
|
const adapter = {
|
||||||
createPublisher: jasmine.createSpy('createPublisher'),
|
createPublisher: jasmine.createSpy('createPublisher'),
|
||||||
createSubscriber: jasmine.createSpy('createSubscriber')
|
createSubscriber: jasmine.createSpy('createSubscriber')
|
||||||
}
|
}
|
||||||
@@ -82,7 +82,7 @@ describe('ParsePubSub', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('can create publisher/sub with custom function adapter', function() {
|
it('can create publisher/sub with custom function adapter', function() {
|
||||||
let adapter = {
|
const adapter = {
|
||||||
createPublisher: jasmine.createSpy('createPublisher'),
|
createPublisher: jasmine.createSpy('createPublisher'),
|
||||||
createSubscriber: jasmine.createSpy('createSubscriber')
|
createSubscriber: jasmine.createSpy('createSubscriber')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ describe('Parse.Query testing', () => {
|
|||||||
// Only cake3 is liked only by user1
|
// Only cake3 is liked only by user1
|
||||||
return query.find().then(function(results){
|
return query.find().then(function(results){
|
||||||
equal(results.length, 1);
|
equal(results.length, 1);
|
||||||
let cake = results[0];
|
const cake = results[0];
|
||||||
expect(cake.id).toBe(cake3.id);
|
expect(cake.id).toBe(cake3.id);
|
||||||
});
|
});
|
||||||
}).then(function(){
|
}).then(function(){
|
||||||
@@ -864,7 +864,7 @@ describe('Parse.Query testing', () => {
|
|||||||
return new BoxedNumber({ number: num, string: strings[i] });
|
return new BoxedNumber({ number: num, string: strings[i] });
|
||||||
};
|
};
|
||||||
|
|
||||||
let objects = [3, 1, 3, 2].map(makeBoxedNumber);
|
const objects = [3, 1, 3, 2].map(makeBoxedNumber);
|
||||||
Parse.Object.saveAll(objects)
|
Parse.Object.saveAll(objects)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
var query = new Parse.Query(BoxedNumber);
|
var query = new Parse.Query(BoxedNumber);
|
||||||
@@ -1566,26 +1566,26 @@ describe('Parse.Query testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly includes array', (done) => {
|
it('properly includes array', (done) => {
|
||||||
let objects = [];
|
const objects = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
while(objects.length != 5) {
|
while(objects.length != 5) {
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('key', objects.length);
|
object.set('key', objects.length);
|
||||||
total += objects.length;
|
total += objects.length;
|
||||||
objects.push(object);
|
objects.push(object);
|
||||||
}
|
}
|
||||||
Parse.Object.saveAll(objects).then(() => {
|
Parse.Object.saveAll(objects).then(() => {
|
||||||
let object = new Parse.Object("AContainer");
|
const object = new Parse.Object("AContainer");
|
||||||
object.set('objects', objects);
|
object.set('objects', objects);
|
||||||
return object.save();
|
return object.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AContainer');
|
const query = new Parse.Query('AContainer');
|
||||||
query.include('objects');
|
query.include('objects');
|
||||||
return query.find()
|
return query.find()
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let res = results[0];
|
const res = results[0];
|
||||||
let objects = res.get('objects');
|
const objects = res.get('objects');
|
||||||
expect(objects.length).toBe(5);
|
expect(objects.length).toBe(5);
|
||||||
objects.forEach((object) => {
|
objects.forEach((object) => {
|
||||||
total -= object.get('key');
|
total -= object.get('key');
|
||||||
@@ -1599,32 +1599,32 @@ describe('Parse.Query testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly includes array of mixed objects', (done) => {
|
it('properly includes array of mixed objects', (done) => {
|
||||||
let objects = [];
|
const objects = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
while(objects.length != 5) {
|
while(objects.length != 5) {
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('key', objects.length);
|
object.set('key', objects.length);
|
||||||
total += objects.length;
|
total += objects.length;
|
||||||
objects.push(object);
|
objects.push(object);
|
||||||
}
|
}
|
||||||
while(objects.length != 10) {
|
while(objects.length != 10) {
|
||||||
let object = new Parse.Object('AnotherObject');
|
const object = new Parse.Object('AnotherObject');
|
||||||
object.set('key', objects.length);
|
object.set('key', objects.length);
|
||||||
total += objects.length;
|
total += objects.length;
|
||||||
objects.push(object);
|
objects.push(object);
|
||||||
}
|
}
|
||||||
Parse.Object.saveAll(objects).then(() => {
|
Parse.Object.saveAll(objects).then(() => {
|
||||||
let object = new Parse.Object("AContainer");
|
const object = new Parse.Object("AContainer");
|
||||||
object.set('objects', objects);
|
object.set('objects', objects);
|
||||||
return object.save();
|
return object.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AContainer');
|
const query = new Parse.Query('AContainer');
|
||||||
query.include('objects');
|
query.include('objects');
|
||||||
return query.find()
|
return query.find()
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let res = results[0];
|
const res = results[0];
|
||||||
let objects = res.get('objects');
|
const objects = res.get('objects');
|
||||||
expect(objects.length).toBe(10);
|
expect(objects.length).toBe(10);
|
||||||
objects.forEach((object) => {
|
objects.forEach((object) => {
|
||||||
total -= object.get('key');
|
total -= object.get('key');
|
||||||
@@ -1638,20 +1638,20 @@ describe('Parse.Query testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly nested array of mixed objects with bad ids', (done) => {
|
it('properly nested array of mixed objects with bad ids', (done) => {
|
||||||
let objects = [];
|
const objects = [];
|
||||||
let total = 0;
|
let total = 0;
|
||||||
while(objects.length != 5) {
|
while(objects.length != 5) {
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('key', objects.length);
|
object.set('key', objects.length);
|
||||||
objects.push(object);
|
objects.push(object);
|
||||||
}
|
}
|
||||||
while(objects.length != 10) {
|
while(objects.length != 10) {
|
||||||
let object = new Parse.Object('AnotherObject');
|
const object = new Parse.Object('AnotherObject');
|
||||||
object.set('key', objects.length);
|
object.set('key', objects.length);
|
||||||
objects.push(object);
|
objects.push(object);
|
||||||
}
|
}
|
||||||
Parse.Object.saveAll(objects).then(() => {
|
Parse.Object.saveAll(objects).then(() => {
|
||||||
let object = new Parse.Object("AContainer");
|
const object = new Parse.Object("AContainer");
|
||||||
for (var i=0; i<objects.length; i++) {
|
for (var i=0; i<objects.length; i++) {
|
||||||
if (i%2 == 0) {
|
if (i%2 == 0) {
|
||||||
objects[i].id = 'randomThing'
|
objects[i].id = 'randomThing'
|
||||||
@@ -1662,13 +1662,13 @@ describe('Parse.Query testing', () => {
|
|||||||
object.set('objects', objects);
|
object.set('objects', objects);
|
||||||
return object.save();
|
return object.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AContainer');
|
const query = new Parse.Query('AContainer');
|
||||||
query.include('objects');
|
query.include('objects');
|
||||||
return query.find()
|
return query.find()
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let res = results[0];
|
const res = results[0];
|
||||||
let objects = res.get('objects');
|
const objects = res.get('objects');
|
||||||
expect(objects.length).toBe(5);
|
expect(objects.length).toBe(5);
|
||||||
objects.forEach((object) => {
|
objects.forEach((object) => {
|
||||||
total -= object.get('key');
|
total -= object.get('key');
|
||||||
@@ -1683,25 +1683,25 @@ describe('Parse.Query testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('properly fetches nested pointers', (done) => {
|
it('properly fetches nested pointers', (done) => {
|
||||||
let color = new Parse.Object('Color');
|
const color = new Parse.Object('Color');
|
||||||
color.set('hex','#133733');
|
color.set('hex','#133733');
|
||||||
let circle = new Parse.Object('Circle');
|
const circle = new Parse.Object('Circle');
|
||||||
circle.set('radius', 1337);
|
circle.set('radius', 1337);
|
||||||
|
|
||||||
Parse.Object.saveAll([color, circle]).then(() => {
|
Parse.Object.saveAll([color, circle]).then(() => {
|
||||||
circle.set('color', color);
|
circle.set('color', color);
|
||||||
let badCircle = new Parse.Object('Circle');
|
const badCircle = new Parse.Object('Circle');
|
||||||
badCircle.id = 'badId';
|
badCircle.id = 'badId';
|
||||||
let complexFigure = new Parse.Object('ComplexFigure');
|
const complexFigure = new Parse.Object('ComplexFigure');
|
||||||
complexFigure.set('consistsOf', [circle, badCircle]);
|
complexFigure.set('consistsOf', [circle, badCircle]);
|
||||||
return complexFigure.save();
|
return complexFigure.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('ComplexFigure');
|
const q = new Parse.Query('ComplexFigure');
|
||||||
q.include('consistsOf.color');
|
q.include('consistsOf.color');
|
||||||
return q.find()
|
return q.find()
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let figure = results[0];
|
const figure = results[0];
|
||||||
expect(figure.get('consistsOf').length).toBe(1);
|
expect(figure.get('consistsOf').length).toBe(1);
|
||||||
expect(figure.get('consistsOf')[0].get('color').get('hex')).toBe('#133733');
|
expect(figure.get('consistsOf')[0].get('color').get('hex')).toBe('#133733');
|
||||||
done();
|
done();
|
||||||
@@ -2357,15 +2357,15 @@ describe('Parse.Query testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('supports include on the wrong key type (#2262)', function(done) {
|
it('supports include on the wrong key type (#2262)', function(done) {
|
||||||
let childObject = new Parse.Object('TestChildObject');
|
const childObject = new Parse.Object('TestChildObject');
|
||||||
childObject.set('hello', 'world');
|
childObject.set('hello', 'world');
|
||||||
childObject.save().then(() => {
|
childObject.save().then(() => {
|
||||||
let obj = new Parse.Object('TestObject');
|
const obj = new Parse.Object('TestObject');
|
||||||
obj.set('foo', 'bar');
|
obj.set('foo', 'bar');
|
||||||
obj.set('child', childObject);
|
obj.set('child', childObject);
|
||||||
return obj.save();
|
return obj.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('TestObject');
|
const q = new Parse.Query('TestObject');
|
||||||
q.include('child');
|
q.include('child');
|
||||||
q.include('child.parent');
|
q.include('child.parent');
|
||||||
q.include('createdAt');
|
q.include('createdAt');
|
||||||
@@ -2485,13 +2485,13 @@ describe('Parse.Query testing', () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
container.set('objects', pointers);
|
container.set('objects', pointers);
|
||||||
let container2 = new Parse.Object('Container');
|
const container2 = new Parse.Object('Container');
|
||||||
container2.set('objects', pointers.slice(2, 3));
|
container2.set('objects', pointers.slice(2, 3));
|
||||||
return Parse.Object.saveAll([container, container2]);
|
return Parse.Object.saveAll([container, container2]);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let inQuery = new Parse.Query('ContainedObject');
|
const inQuery = new Parse.Query('ContainedObject');
|
||||||
inQuery.greaterThanOrEqualTo('index', 1);
|
inQuery.greaterThanOrEqualTo('index', 1);
|
||||||
let query = new Parse.Query('Container');
|
const query = new Parse.Query('Container');
|
||||||
query.matchesQuery('objects', inQuery);
|
query.matchesQuery('objects', inQuery);
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
@@ -2507,16 +2507,16 @@ describe('Parse.Query testing', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('query with two OR subqueries (regression test #1259)', done => {
|
it('query with two OR subqueries (regression test #1259)', done => {
|
||||||
let relatedObject = new Parse.Object('Class2');
|
const relatedObject = new Parse.Object('Class2');
|
||||||
relatedObject.save().then(relatedObject => {
|
relatedObject.save().then(relatedObject => {
|
||||||
let anObject = new Parse.Object('Class1');
|
const anObject = new Parse.Object('Class1');
|
||||||
let relation = anObject.relation('relation');
|
const relation = anObject.relation('relation');
|
||||||
relation.add(relatedObject);
|
relation.add(relatedObject);
|
||||||
return anObject.save();
|
return anObject.save();
|
||||||
}).then(anObject => {
|
}).then(anObject => {
|
||||||
let q1 = anObject.relation('relation').query();
|
const q1 = anObject.relation('relation').query();
|
||||||
q1.doesNotExist('nonExistantKey1');
|
q1.doesNotExist('nonExistantKey1');
|
||||||
let q2 = anObject.relation('relation').query();
|
const q2 = anObject.relation('relation').query();
|
||||||
q2.doesNotExist('nonExistantKey2');
|
q2.doesNotExist('nonExistantKey2');
|
||||||
Parse.Query.or(q1, q2).find().then(results => {
|
Parse.Query.or(q1, q2).find().then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
@@ -2529,14 +2529,14 @@ describe('Parse.Query testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('objectId containedIn with multiple large array', done => {
|
it('objectId containedIn with multiple large array', done => {
|
||||||
let obj = new Parse.Object('MyClass');
|
const obj = new Parse.Object('MyClass');
|
||||||
obj.save().then(obj => {
|
obj.save().then(obj => {
|
||||||
let longListOfStrings = [];
|
const longListOfStrings = [];
|
||||||
for (let i = 0; i < 130; i++) {
|
for (let i = 0; i < 130; i++) {
|
||||||
longListOfStrings.push(i.toString());
|
longListOfStrings.push(i.toString());
|
||||||
}
|
}
|
||||||
longListOfStrings.push(obj.id);
|
longListOfStrings.push(obj.id);
|
||||||
let q = new Parse.Query('MyClass');
|
const q = new Parse.Query('MyClass');
|
||||||
q.containedIn('objectId', longListOfStrings);
|
q.containedIn('objectId', longListOfStrings);
|
||||||
q.containedIn('objectId', longListOfStrings);
|
q.containedIn('objectId', longListOfStrings);
|
||||||
return q.find();
|
return q.find();
|
||||||
@@ -2703,13 +2703,13 @@ describe('Parse.Query testing', () => {
|
|||||||
objects.push(obj)
|
objects.push(obj)
|
||||||
}
|
}
|
||||||
Parse.Object.saveAll(objects).then(() => {
|
Parse.Object.saveAll(objects).then(() => {
|
||||||
let q0 = new Parse.Query('Object');
|
const q0 = new Parse.Query('Object');
|
||||||
q0.equalTo('x', 0);
|
q0.equalTo('x', 0);
|
||||||
let q1 = new Parse.Query('Object');
|
const q1 = new Parse.Query('Object');
|
||||||
q1.equalTo('x', 1);
|
q1.equalTo('x', 1);
|
||||||
let q2 = new Parse.Query('Object');
|
const q2 = new Parse.Query('Object');
|
||||||
q2.equalTo('x', 2);
|
q2.equalTo('x', 2);
|
||||||
let or01 = Parse.Query.or(q0,q1);
|
const or01 = Parse.Query.or(q0,q1);
|
||||||
return Parse.Query.or(or01, q2).find();
|
return Parse.Query.or(or01, q2).find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(3);
|
expect(results.length).toBe(3);
|
||||||
|
|||||||
@@ -249,35 +249,35 @@ describe('Parse.Relation testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("queries on relation fields with multiple containedIn (regression test for #1271)", (done) => {
|
it("queries on relation fields with multiple containedIn (regression test for #1271)", (done) => {
|
||||||
let ChildObject = Parse.Object.extend("ChildObject");
|
const ChildObject = Parse.Object.extend("ChildObject");
|
||||||
let childObjects = [];
|
const childObjects = [];
|
||||||
for (let i = 0; i < 10; i++) {
|
for (let i = 0; i < 10; i++) {
|
||||||
childObjects.push(new ChildObject({x: i}));
|
childObjects.push(new ChildObject({x: i}));
|
||||||
}
|
}
|
||||||
|
|
||||||
Parse.Object.saveAll(childObjects).then(() => {
|
Parse.Object.saveAll(childObjects).then(() => {
|
||||||
let ParentObject = Parse.Object.extend("ParentObject");
|
const ParentObject = Parse.Object.extend("ParentObject");
|
||||||
let parent = new ParentObject();
|
const parent = new ParentObject();
|
||||||
parent.set("x", 4);
|
parent.set("x", 4);
|
||||||
let parent1Children = parent.relation("child");
|
const parent1Children = parent.relation("child");
|
||||||
parent1Children.add(childObjects[0]);
|
parent1Children.add(childObjects[0]);
|
||||||
parent1Children.add(childObjects[1]);
|
parent1Children.add(childObjects[1]);
|
||||||
parent1Children.add(childObjects[2]);
|
parent1Children.add(childObjects[2]);
|
||||||
let parent2 = new ParentObject();
|
const parent2 = new ParentObject();
|
||||||
parent2.set("x", 3);
|
parent2.set("x", 3);
|
||||||
let parent2Children = parent2.relation("child");
|
const parent2Children = parent2.relation("child");
|
||||||
parent2Children.add(childObjects[4]);
|
parent2Children.add(childObjects[4]);
|
||||||
parent2Children.add(childObjects[5]);
|
parent2Children.add(childObjects[5]);
|
||||||
parent2Children.add(childObjects[6]);
|
parent2Children.add(childObjects[6]);
|
||||||
|
|
||||||
let parent2OtherChildren = parent2.relation("otherChild");
|
const parent2OtherChildren = parent2.relation("otherChild");
|
||||||
parent2OtherChildren.add(childObjects[0]);
|
parent2OtherChildren.add(childObjects[0]);
|
||||||
parent2OtherChildren.add(childObjects[1]);
|
parent2OtherChildren.add(childObjects[1]);
|
||||||
parent2OtherChildren.add(childObjects[2]);
|
parent2OtherChildren.add(childObjects[2]);
|
||||||
|
|
||||||
return Parse.Object.saveAll([parent, parent2]);
|
return Parse.Object.saveAll([parent, parent2]);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let objectsWithChild0InBothChildren = new Parse.Query(ParentObject);
|
const objectsWithChild0InBothChildren = new Parse.Query(ParentObject);
|
||||||
objectsWithChild0InBothChildren.containedIn("child", [childObjects[0]]);
|
objectsWithChild0InBothChildren.containedIn("child", [childObjects[0]]);
|
||||||
objectsWithChild0InBothChildren.containedIn("otherChild", [childObjects[0]]);
|
objectsWithChild0InBothChildren.containedIn("otherChild", [childObjects[0]]);
|
||||||
return objectsWithChild0InBothChildren.find();
|
return objectsWithChild0InBothChildren.find();
|
||||||
@@ -285,7 +285,7 @@ describe('Parse.Relation testing', () => {
|
|||||||
//No parent has child 0 in both it's "child" and "otherChild" field;
|
//No parent has child 0 in both it's "child" and "otherChild" field;
|
||||||
expect(objectsWithChild0InBothChildren.length).toEqual(0);
|
expect(objectsWithChild0InBothChildren.length).toEqual(0);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let objectsWithChild4andOtherChild1 = new Parse.Query(ParentObject);
|
const objectsWithChild4andOtherChild1 = new Parse.Query(ParentObject);
|
||||||
objectsWithChild4andOtherChild1.containedIn("child", [childObjects[4]]);
|
objectsWithChild4andOtherChild1.containedIn("child", [childObjects[4]]);
|
||||||
objectsWithChild4andOtherChild1.containedIn("otherChild", [childObjects[1]]);
|
objectsWithChild4andOtherChild1.containedIn("otherChild", [childObjects[1]]);
|
||||||
return objectsWithChild4andOtherChild1.find();
|
return objectsWithChild4andOtherChild1.find();
|
||||||
@@ -510,24 +510,24 @@ describe('Parse.Relation testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should properly get related objects with unfetched queries', (done) => {
|
it('should properly get related objects with unfetched queries', (done) => {
|
||||||
let objects = [];
|
const objects = [];
|
||||||
let owners = [];
|
const owners = [];
|
||||||
let allObjects = [];
|
const allObjects = [];
|
||||||
// Build 10 Objects and 10 owners
|
// Build 10 Objects and 10 owners
|
||||||
while (objects.length != 10) {
|
while (objects.length != 10) {
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set({
|
object.set({
|
||||||
index: objects.length,
|
index: objects.length,
|
||||||
even: objects.length % 2 == 0
|
even: objects.length % 2 == 0
|
||||||
});
|
});
|
||||||
objects.push(object);
|
objects.push(object);
|
||||||
let owner = new Parse.Object('AnOwner');
|
const owner = new Parse.Object('AnOwner');
|
||||||
owners.push(owner);
|
owners.push(owner);
|
||||||
allObjects.push(object);
|
allObjects.push(object);
|
||||||
allObjects.push(owner);
|
allObjects.push(owner);
|
||||||
}
|
}
|
||||||
|
|
||||||
let anotherOwner = new Parse.Object('AnotherOwner');
|
const anotherOwner = new Parse.Object('AnotherOwner');
|
||||||
|
|
||||||
return Parse.Object.saveAll(allObjects.concat([anotherOwner])).then(() => {
|
return Parse.Object.saveAll(allObjects.concat([anotherOwner])).then(() => {
|
||||||
// put all the AnObject into the anotherOwner relationKey
|
// put all the AnObject into the anotherOwner relationKey
|
||||||
@@ -539,13 +539,13 @@ describe('Parse.Relation testing', () => {
|
|||||||
return Parse.Object.saveAll(owners.concat([anotherOwner]));
|
return Parse.Object.saveAll(owners.concat([anotherOwner]));
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
// Query on the relation of another owner
|
// Query on the relation of another owner
|
||||||
let object = new Parse.Object('AnotherOwner');
|
const object = new Parse.Object('AnotherOwner');
|
||||||
object.id = anotherOwner.id;
|
object.id = anotherOwner.id;
|
||||||
let relationQuery = object.relation('relationKey').query();
|
const relationQuery = object.relation('relationKey').query();
|
||||||
// Just get the even ones
|
// Just get the even ones
|
||||||
relationQuery.equalTo('even', true);
|
relationQuery.equalTo('even', true);
|
||||||
// Make the query on anOwner
|
// Make the query on anOwner
|
||||||
let query = new Parse.Query('AnOwner');
|
const query = new Parse.Query('AnOwner');
|
||||||
// where key match the relation query.
|
// where key match the relation query.
|
||||||
query.matchesQuery('key', relationQuery);
|
query.matchesQuery('key', relationQuery);
|
||||||
query.include('key');
|
query.include('key');
|
||||||
@@ -558,13 +558,13 @@ describe('Parse.Relation testing', () => {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
// Query on the relation of another owner
|
// Query on the relation of another owner
|
||||||
let object = new Parse.Object('AnotherOwner');
|
const object = new Parse.Object('AnotherOwner');
|
||||||
object.id = anotherOwner.id;
|
object.id = anotherOwner.id;
|
||||||
let relationQuery = object.relation('relationKey').query();
|
const relationQuery = object.relation('relationKey').query();
|
||||||
// Just get the even ones
|
// Just get the even ones
|
||||||
relationQuery.equalTo('even', true);
|
relationQuery.equalTo('even', true);
|
||||||
// Make the query on anOwner
|
// Make the query on anOwner
|
||||||
let query = new Parse.Query('AnOwner');
|
const query = new Parse.Query('AnOwner');
|
||||||
// where key match the relation query.
|
// where key match the relation query.
|
||||||
query.doesNotMatchQuery('key', relationQuery);
|
query.doesNotMatchQuery('key', relationQuery);
|
||||||
query.include('key');
|
query.include('key');
|
||||||
@@ -586,19 +586,19 @@ describe('Parse.Relation testing', () => {
|
|||||||
new RestaurantObject({ ratings: 5, location: "Djibouti" }),
|
new RestaurantObject({ ratings: 5, location: "Djibouti" }),
|
||||||
new RestaurantObject({ ratings: 3, location: "Ouagadougou" }),
|
new RestaurantObject({ ratings: 3, location: "Ouagadougou" }),
|
||||||
];
|
];
|
||||||
let persons = [
|
const persons = [
|
||||||
new PersonObject({ name: "Bob", hometown: "Djibouti" }),
|
new PersonObject({ name: "Bob", hometown: "Djibouti" }),
|
||||||
new PersonObject({ name: "Tom", hometown: "Ouagadougou" }),
|
new PersonObject({ name: "Tom", hometown: "Ouagadougou" }),
|
||||||
new PersonObject({ name: "Billy", hometown: "Detroit" }),
|
new PersonObject({ name: "Billy", hometown: "Detroit" }),
|
||||||
];
|
];
|
||||||
let owner = new OwnerObject({name: 'Joe'});
|
const owner = new OwnerObject({name: 'Joe'});
|
||||||
let allObjects = [owner].concat(restaurants).concat(persons);
|
const allObjects = [owner].concat(restaurants).concat(persons);
|
||||||
expect(allObjects.length).toEqual(6);
|
expect(allObjects.length).toEqual(6);
|
||||||
Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() {
|
Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() {
|
||||||
owner.relation('restaurants').add(restaurants);
|
owner.relation('restaurants').add(restaurants);
|
||||||
return owner.save()
|
return owner.save()
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let unfetchedOwner = new OwnerObject();
|
const unfetchedOwner = new OwnerObject();
|
||||||
unfetchedOwner.id = owner.id;
|
unfetchedOwner.id = owner.id;
|
||||||
var query = unfetchedOwner.relation('restaurants').query();
|
var query = unfetchedOwner.relation('restaurants').query();
|
||||||
query.greaterThan("ratings", 4);
|
query.greaterThan("ratings", 4);
|
||||||
@@ -624,19 +624,19 @@ describe('Parse.Relation testing', () => {
|
|||||||
new RestaurantObject({ ratings: 5, location: "Djibouti" }),
|
new RestaurantObject({ ratings: 5, location: "Djibouti" }),
|
||||||
new RestaurantObject({ ratings: 3, location: "Ouagadougou" }),
|
new RestaurantObject({ ratings: 3, location: "Ouagadougou" }),
|
||||||
];
|
];
|
||||||
let persons = [
|
const persons = [
|
||||||
new PersonObject({ name: "Bob", hometown: "Djibouti" }),
|
new PersonObject({ name: "Bob", hometown: "Djibouti" }),
|
||||||
new PersonObject({ name: "Tom", hometown: "Ouagadougou" }),
|
new PersonObject({ name: "Tom", hometown: "Ouagadougou" }),
|
||||||
new PersonObject({ name: "Billy", hometown: "Detroit" }),
|
new PersonObject({ name: "Billy", hometown: "Detroit" }),
|
||||||
];
|
];
|
||||||
let owner = new OwnerObject({name: 'Joe'});
|
const owner = new OwnerObject({name: 'Joe'});
|
||||||
let allObjects = [owner].concat(restaurants).concat(persons);
|
const allObjects = [owner].concat(restaurants).concat(persons);
|
||||||
expect(allObjects.length).toEqual(6);
|
expect(allObjects.length).toEqual(6);
|
||||||
Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() {
|
Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() {
|
||||||
owner.relation('restaurants').add(restaurants);
|
owner.relation('restaurants').add(restaurants);
|
||||||
return owner.save()
|
return owner.save()
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let unfetchedOwner = new OwnerObject();
|
const unfetchedOwner = new OwnerObject();
|
||||||
unfetchedOwner.id = owner.id;
|
unfetchedOwner.id = owner.id;
|
||||||
var query = unfetchedOwner.relation('restaurants').query();
|
var query = unfetchedOwner.relation('restaurants').query();
|
||||||
query.greaterThan("ratings", 4);
|
query.greaterThan("ratings", 4);
|
||||||
@@ -657,21 +657,21 @@ describe('Parse.Relation testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('relations are not bidirectional (regression test for #871)', done => {
|
it('relations are not bidirectional (regression test for #871)', done => {
|
||||||
let PersonObject = Parse.Object.extend("Person");
|
const PersonObject = Parse.Object.extend("Person");
|
||||||
let p1 = new PersonObject();
|
const p1 = new PersonObject();
|
||||||
let p2 = new PersonObject();
|
const p2 = new PersonObject();
|
||||||
Parse.Object.saveAll([p1, p2]).then(results => {
|
Parse.Object.saveAll([p1, p2]).then(results => {
|
||||||
let p1 = results[0];
|
const p1 = results[0];
|
||||||
let p2 = results[1];
|
const p2 = results[1];
|
||||||
let relation = p1.relation('relation');
|
const relation = p1.relation('relation');
|
||||||
relation.add(p2);
|
relation.add(p2);
|
||||||
p1.save().then(() => {
|
p1.save().then(() => {
|
||||||
let query = new Parse.Query(PersonObject);
|
const query = new Parse.Query(PersonObject);
|
||||||
query.equalTo('relation', p1);
|
query.equalTo('relation', p1);
|
||||||
query.find().then(results => {
|
query.find().then(results => {
|
||||||
expect(results.length).toEqual(0);
|
expect(results.length).toEqual(0);
|
||||||
|
|
||||||
let query = new Parse.Query(PersonObject);
|
const query = new Parse.Query(PersonObject);
|
||||||
query.equalTo('relation', p2);
|
query.equalTo('relation', p2);
|
||||||
query.find().then(results => {
|
query.find().then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
@@ -685,12 +685,12 @@ describe('Parse.Relation testing', () => {
|
|||||||
|
|
||||||
it('can query roles in Cloud Code (regession test #1489)', done => {
|
it('can query roles in Cloud Code (regession test #1489)', done => {
|
||||||
Parse.Cloud.define('isAdmin', (request, response) => {
|
Parse.Cloud.define('isAdmin', (request, response) => {
|
||||||
let query = new Parse.Query(Parse.Role);
|
const query = new Parse.Query(Parse.Role);
|
||||||
query.equalTo('name', 'admin');
|
query.equalTo('name', 'admin');
|
||||||
query.first({ useMasterKey: true })
|
query.first({ useMasterKey: true })
|
||||||
.then(role => {
|
.then(role => {
|
||||||
let relation = new Parse.Relation(role, 'users');
|
const relation = new Parse.Relation(role, 'users');
|
||||||
let admins = relation.query();
|
const admins = relation.query();
|
||||||
admins.equalTo('username', request.user.get('username'));
|
admins.equalTo('username', request.user.get('username'));
|
||||||
admins.first({ useMasterKey: true })
|
admins.first({ useMasterKey: true })
|
||||||
.then(user => {
|
.then(user => {
|
||||||
@@ -712,16 +712,16 @@ describe('Parse.Relation testing', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
let adminUser = new Parse.User();
|
const adminUser = new Parse.User();
|
||||||
adminUser.set('username', 'name');
|
adminUser.set('username', 'name');
|
||||||
adminUser.set('password', 'pass');
|
adminUser.set('password', 'pass');
|
||||||
adminUser.signUp()
|
adminUser.signUp()
|
||||||
.then(adminUser => {
|
.then(adminUser => {
|
||||||
let adminACL = new Parse.ACL();
|
const adminACL = new Parse.ACL();
|
||||||
adminACL.setPublicReadAccess(true);
|
adminACL.setPublicReadAccess(true);
|
||||||
|
|
||||||
// Create admin role
|
// Create admin role
|
||||||
let adminRole = new Parse.Role('admin', adminACL);
|
const adminRole = new Parse.Role('admin', adminACL);
|
||||||
adminRole.getUsers().add(adminUser);
|
adminRole.getUsers().add(adminUser);
|
||||||
adminRole.save()
|
adminRole.save()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
@@ -739,13 +739,13 @@ describe('Parse.Relation testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('can be saved without error', done => {
|
it('can be saved without error', done => {
|
||||||
let obj1 = new Parse.Object('PPAP');
|
const obj1 = new Parse.Object('PPAP');
|
||||||
obj1.save()
|
obj1.save()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let newRelation = obj1.relation('aRelation');
|
const newRelation = obj1.relation('aRelation');
|
||||||
newRelation.add(obj1);
|
newRelation.add(obj1);
|
||||||
obj1.save().then(() => {
|
obj1.save().then(() => {
|
||||||
let relation = obj1.get('aRelation');
|
const relation = obj1.get('aRelation');
|
||||||
obj1.set('aRelation', relation);
|
obj1.set('aRelation', relation);
|
||||||
obj1.save().then(() => {
|
obj1.save().then(() => {
|
||||||
done();
|
done();
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ describe('Parse Role testing', () => {
|
|||||||
|
|
||||||
createTestUser().then((x) => {
|
createTestUser().then((x) => {
|
||||||
user = x;
|
user = x;
|
||||||
let acl = new Parse.ACL();
|
const acl = new Parse.ACL();
|
||||||
acl.setPublicReadAccess(true);
|
acl.setPublicReadAccess(true);
|
||||||
acl.setPublicWriteAccess(false);
|
acl.setPublicWriteAccess(false);
|
||||||
role = new Parse.Object('_Role');
|
role = new Parse.Object('_Role');
|
||||||
@@ -193,11 +193,11 @@ describe('Parse Role testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("Should properly resolve roles", (done) => {
|
it("Should properly resolve roles", (done) => {
|
||||||
let admin = new Parse.Role("Admin", new Parse.ACL());
|
const admin = new Parse.Role("Admin", new Parse.ACL());
|
||||||
let moderator = new Parse.Role("Moderator", new Parse.ACL());
|
const moderator = new Parse.Role("Moderator", new Parse.ACL());
|
||||||
let superModerator = new Parse.Role("SuperModerator", new Parse.ACL());
|
const superModerator = new Parse.Role("SuperModerator", new Parse.ACL());
|
||||||
let contentManager = new Parse.Role('ContentManager', new Parse.ACL());
|
const contentManager = new Parse.Role('ContentManager', new Parse.ACL());
|
||||||
let superContentManager = new Parse.Role('SuperContentManager', new Parse.ACL());
|
const superContentManager = new Parse.Role('SuperContentManager', new Parse.ACL());
|
||||||
Parse.Object.saveAll([admin, moderator, contentManager, superModerator, superContentManager], {useMasterKey: true}).then(() => {
|
Parse.Object.saveAll([admin, moderator, contentManager, superModerator, superContentManager], {useMasterKey: true}).then(() => {
|
||||||
contentManager.getRoles().add([moderator, superContentManager]);
|
contentManager.getRoles().add([moderator, superContentManager]);
|
||||||
moderator.getRoles().add([admin, superModerator]);
|
moderator.getRoles().add([admin, superModerator]);
|
||||||
@@ -207,7 +207,7 @@ describe('Parse Role testing', () => {
|
|||||||
var auth = new Auth({ config: new Config("test"), isMaster: true });
|
var auth = new Auth({ config: new Config("test"), isMaster: true });
|
||||||
// For each role, fetch their sibling, what they inherit
|
// For each role, fetch their sibling, what they inherit
|
||||||
// return with result and roleId for later comparison
|
// return with result and roleId for later comparison
|
||||||
let promises = [admin, moderator, contentManager, superModerator].map((role) => {
|
const promises = [admin, moderator, contentManager, superModerator].map((role) => {
|
||||||
return auth._getAllRolesNamesForRoleIds([role.id]).then((result) => {
|
return auth._getAllRolesNamesForRoleIds([role.id]).then((result) => {
|
||||||
return Parse.Promise.as({
|
return Parse.Promise.as({
|
||||||
id: role.id,
|
id: role.id,
|
||||||
@@ -220,8 +220,8 @@ describe('Parse Role testing', () => {
|
|||||||
return Parse.Promise.when(promises);
|
return Parse.Promise.when(promises);
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
results.forEach((result) => {
|
results.forEach((result) => {
|
||||||
let id = result.id;
|
const id = result.id;
|
||||||
let roleNames = result.roleNames;
|
const roleNames = result.roleNames;
|
||||||
if (id == admin.id) {
|
if (id == admin.id) {
|
||||||
expect(roleNames.length).toBe(2);
|
expect(roleNames.length).toBe(2);
|
||||||
expect(roleNames.indexOf("Moderator")).not.toBe(-1);
|
expect(roleNames.indexOf("Moderator")).not.toBe(-1);
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ describe('ParseServerRESTController', () => {
|
|||||||
let userId;
|
let userId;
|
||||||
Parse.User.signUp('user', 'pass').then((user) => {
|
Parse.User.signUp('user', 'pass').then((user) => {
|
||||||
userId = user.id;
|
userId = user.id;
|
||||||
let sessionToken = user.getSessionToken();
|
const sessionToken = user.getSessionToken();
|
||||||
return RESTController.request("GET", "/users/me", undefined, {sessionToken});
|
return RESTController.request("GET", "/users/me", undefined, {sessionToken});
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
// Result is in JSON format
|
// Result is in JSON format
|
||||||
@@ -106,7 +106,7 @@ describe('ParseServerRESTController', () => {
|
|||||||
it('ensures no session token is created on creating users', (done) => {
|
it('ensures no session token is created on creating users', (done) => {
|
||||||
RESTController.request("POST", "/classes/_User", {username: "hello", password: "world"}).then((user) => {
|
RESTController.request("POST", "/classes/_User", {username: "hello", password: "world"}).then((user) => {
|
||||||
expect(user.sessionToken).toBeUndefined();
|
expect(user.sessionToken).toBeUndefined();
|
||||||
let query = new Parse.Query('_Session');
|
const query = new Parse.Query('_Session');
|
||||||
return query.find({useMasterKey: true});
|
return query.find({useMasterKey: true});
|
||||||
}).then(sessions => {
|
}).then(sessions => {
|
||||||
expect(sessions.length).toBe(0);
|
expect(sessions.length).toBe(0);
|
||||||
@@ -120,7 +120,7 @@ describe('ParseServerRESTController', () => {
|
|||||||
it('ensures a session token is created when passing installationId != cloud', (done) => {
|
it('ensures a session token is created when passing installationId != cloud', (done) => {
|
||||||
RESTController.request("POST", "/classes/_User", {username: "hello", password: "world"}, {installationId: 'my-installation'}).then((user) => {
|
RESTController.request("POST", "/classes/_User", {username: "hello", password: "world"}, {installationId: 'my-installation'}).then((user) => {
|
||||||
expect(user.sessionToken).not.toBeUndefined();
|
expect(user.sessionToken).not.toBeUndefined();
|
||||||
let query = new Parse.Query('_Session');
|
const query = new Parse.Query('_Session');
|
||||||
return query.find({useMasterKey: true});
|
return query.find({useMasterKey: true});
|
||||||
}).then(sessions => {
|
}).then(sessions => {
|
||||||
expect(sessions.length).toBe(1);
|
expect(sessions.length).toBe(1);
|
||||||
|
|||||||
@@ -141,8 +141,8 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should respect ACL without locking user out', (done) => {
|
it('should respect ACL without locking user out', (done) => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let ACL = new Parse.ACL();
|
const ACL = new Parse.ACL();
|
||||||
ACL.setPublicReadAccess(false);
|
ACL.setPublicReadAccess(false);
|
||||||
ACL.setPublicWriteAccess(false);
|
ACL.setPublicWriteAccess(false);
|
||||||
user.setUsername('asdf');
|
user.setUsername('asdf');
|
||||||
@@ -163,7 +163,7 @@ describe('Parse.User testing', () => {
|
|||||||
expect(perms[user.id].write).toBe(true);
|
expect(perms[user.id].write).toBe(true);
|
||||||
expect(perms['*']).toBeUndefined();
|
expect(perms['*']).toBeUndefined();
|
||||||
// Try to lock out user
|
// Try to lock out user
|
||||||
let newACL = new Parse.ACL();
|
const newACL = new Parse.ACL();
|
||||||
newACL.setReadAccess(user.id, false);
|
newACL.setReadAccess(user.id, false);
|
||||||
newACL.setWriteAccess(user.id, false);
|
newACL.setWriteAccess(user.id, false);
|
||||||
user.setACL(newACL);
|
user.setACL(newACL);
|
||||||
@@ -190,13 +190,13 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("user login with files", (done) => {
|
it("user login with files", (done) => {
|
||||||
let file = new Parse.File("yolo.txt", [1,2,3], "text/plain");
|
const file = new Parse.File("yolo.txt", [1,2,3], "text/plain");
|
||||||
file.save().then((file) => {
|
file.save().then((file) => {
|
||||||
return Parse.User.signUp("asdf", "zxcv", { "file" : file });
|
return Parse.User.signUp("asdf", "zxcv", { "file" : file });
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn("asdf", "zxcv");
|
return Parse.User.logIn("asdf", "zxcv");
|
||||||
}).then((user) => {
|
}).then((user) => {
|
||||||
let fileAgain = user.get('file');
|
const fileAgain = user.get('file');
|
||||||
ok(fileAgain.name());
|
ok(fileAgain.name());
|
||||||
ok(fileAgain.url());
|
ok(fileAgain.url());
|
||||||
done();
|
done();
|
||||||
@@ -1153,11 +1153,11 @@ describe('Parse.User testing', () => {
|
|||||||
|
|
||||||
it('returns authData when authed and logged in with provider (regression test for #1498)', done => {
|
it('returns authData when authed and logged in with provider (regression test for #1498)', done => {
|
||||||
Parse.Object.enableSingleInstance();
|
Parse.Object.enableSingleInstance();
|
||||||
let provider = getMockFacebookProvider();
|
const provider = getMockFacebookProvider();
|
||||||
Parse.User._registerAuthenticationProvider(provider);
|
Parse.User._registerAuthenticationProvider(provider);
|
||||||
Parse.User._logInWith('facebook', {
|
Parse.User._logInWith('facebook', {
|
||||||
success: user => {
|
success: user => {
|
||||||
let userQuery = new Parse.Query(Parse.User);
|
const userQuery = new Parse.Query(Parse.User);
|
||||||
userQuery.get(user.id)
|
userQuery.get(user.id)
|
||||||
.then(user => {
|
.then(user => {
|
||||||
expect(user.get('authData')).not.toBeUndefined();
|
expect(user.get('authData')).not.toBeUndefined();
|
||||||
@@ -1169,18 +1169,18 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('log in with provider with files', done => {
|
it('log in with provider with files', done => {
|
||||||
let provider = getMockFacebookProvider();
|
const provider = getMockFacebookProvider();
|
||||||
Parse.User._registerAuthenticationProvider(provider);
|
Parse.User._registerAuthenticationProvider(provider);
|
||||||
let file = new Parse.File("yolo.txt", [1, 2, 3], "text/plain");
|
const file = new Parse.File("yolo.txt", [1, 2, 3], "text/plain");
|
||||||
file.save().then(file => {
|
file.save().then(file => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.set('file', file);
|
user.set('file', file);
|
||||||
return user._linkWith('facebook', {});
|
return user._linkWith('facebook', {});
|
||||||
}).then(user => {
|
}).then(user => {
|
||||||
expect(user._isLinked("facebook")).toBeTruthy();
|
expect(user._isLinked("facebook")).toBeTruthy();
|
||||||
return Parse.User._logInWith('facebook', {});
|
return Parse.User._logInWith('facebook', {});
|
||||||
}).then(user => {
|
}).then(user => {
|
||||||
let fileAgain = user.get('file');
|
const fileAgain = user.get('file');
|
||||||
expect(fileAgain.name()).toMatch(/yolo.txt$/);
|
expect(fileAgain.name()).toMatch(/yolo.txt$/);
|
||||||
expect(fileAgain.url()).toMatch(/yolo.txt$/);
|
expect(fileAgain.url()).toMatch(/yolo.txt$/);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -1535,7 +1535,7 @@ describe('Parse.User testing', () => {
|
|||||||
strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);
|
strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);
|
||||||
ok(model._isLinked("facebook"), "User should be linked to facebook");
|
ok(model._isLinked("facebook"), "User should be linked to facebook");
|
||||||
Parse.User._registerAuthenticationProvider(mockProvider);
|
Parse.User._registerAuthenticationProvider(mockProvider);
|
||||||
let objectId = model.id;
|
const objectId = model.id;
|
||||||
model._linkWith("myoauth", {
|
model._linkWith("myoauth", {
|
||||||
success: function(model) {
|
success: function(model) {
|
||||||
expect(model.id).toEqual(objectId);
|
expect(model.id).toEqual(objectId);
|
||||||
@@ -1571,7 +1571,7 @@ describe('Parse.User testing', () => {
|
|||||||
Parse.User._logInWith("facebook", {
|
Parse.User._logInWith("facebook", {
|
||||||
success: function(model) {
|
success: function(model) {
|
||||||
Parse.User._registerAuthenticationProvider(mockProvider);
|
Parse.User._registerAuthenticationProvider(mockProvider);
|
||||||
let objectId = model.id;
|
const objectId = model.id;
|
||||||
model._linkWith("myoauth", {
|
model._linkWith("myoauth", {
|
||||||
success: function() {
|
success: function() {
|
||||||
Parse.User._registerAuthenticationProvider(secondProvider);
|
Parse.User._registerAuthenticationProvider(secondProvider);
|
||||||
@@ -1612,7 +1612,7 @@ describe('Parse.User testing', () => {
|
|||||||
strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);
|
strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);
|
||||||
ok(model._isLinked("facebook"), "User should be linked to facebook");
|
ok(model._isLinked("facebook"), "User should be linked to facebook");
|
||||||
Parse.User._registerAuthenticationProvider(mockProvider);
|
Parse.User._registerAuthenticationProvider(mockProvider);
|
||||||
let objectId = model.id;
|
const objectId = model.id;
|
||||||
model._linkWith("myoauth", {
|
model._linkWith("myoauth", {
|
||||||
success: function(model) {
|
success: function(model) {
|
||||||
expect(model.id).toEqual(objectId);
|
expect(model.id).toEqual(objectId);
|
||||||
@@ -1650,7 +1650,7 @@ describe('Parse.User testing', () => {
|
|||||||
Parse.User._logInWith("facebook", {
|
Parse.User._logInWith("facebook", {
|
||||||
success: function() {
|
success: function() {
|
||||||
Parse.User.logOut().then(() => {
|
Parse.User.logOut().then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('user');
|
user.setUsername('user');
|
||||||
user.setPassword('password');
|
user.setPassword('password');
|
||||||
return user.signUp().then(() => {
|
return user.signUp().then(() => {
|
||||||
@@ -1675,7 +1675,7 @@ describe('Parse.User testing', () => {
|
|||||||
Parse.User._registerAuthenticationProvider(provider);
|
Parse.User._registerAuthenticationProvider(provider);
|
||||||
Parse.User._logInWith("facebook", {
|
Parse.User._logInWith("facebook", {
|
||||||
success: function(model) {
|
success: function(model) {
|
||||||
let userId = model.id;
|
const userId = model.id;
|
||||||
Parse.User.logOut().then(() => {
|
Parse.User.logOut().then(() => {
|
||||||
request.post({
|
request.post({
|
||||||
url:Parse.serverURL+'/classes/_User',
|
url:Parse.serverURL+'/classes/_User',
|
||||||
@@ -1722,7 +1722,7 @@ describe('Parse.User testing', () => {
|
|||||||
it('should have authData in beforeSave and afterSave', (done) => {
|
it('should have authData in beforeSave and afterSave', (done) => {
|
||||||
|
|
||||||
Parse.Cloud.beforeSave('_User', (request, response) => {
|
Parse.Cloud.beforeSave('_User', (request, response) => {
|
||||||
let authData = request.object.get('authData');
|
const authData = request.object.get('authData');
|
||||||
expect(authData).not.toBeUndefined();
|
expect(authData).not.toBeUndefined();
|
||||||
if (authData) {
|
if (authData) {
|
||||||
expect(authData.facebook.id).toEqual('8675309');
|
expect(authData.facebook.id).toEqual('8675309');
|
||||||
@@ -1734,7 +1734,7 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Parse.Cloud.afterSave('_User', (request, response) => {
|
Parse.Cloud.afterSave('_User', (request, response) => {
|
||||||
let authData = request.object.get('authData');
|
const authData = request.object.get('authData');
|
||||||
expect(authData).not.toBeUndefined();
|
expect(authData).not.toBeUndefined();
|
||||||
if (authData) {
|
if (authData) {
|
||||||
expect(authData.facebook.id).toEqual('8675309');
|
expect(authData.facebook.id).toEqual('8675309');
|
||||||
@@ -2326,7 +2326,7 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it_exclude_dbs(['postgres'])('should cleanup null authData keys (regression test for #935)', (done) => {
|
it_exclude_dbs(['postgres'])('should cleanup null authData keys (regression test for #935)', (done) => {
|
||||||
let database = new Config(Parse.applicationId).database;
|
const database = new Config(Parse.applicationId).database;
|
||||||
database.create('_User', {
|
database.create('_User', {
|
||||||
username: 'user',
|
username: 'user',
|
||||||
_hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',
|
_hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',
|
||||||
@@ -2349,7 +2349,7 @@ describe('Parse.User testing', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
}).then((user) => {
|
}).then((user) => {
|
||||||
let authData = user.authData;
|
const authData = user.authData;
|
||||||
expect(user.username).toEqual('user');
|
expect(user.username).toEqual('user');
|
||||||
expect(authData).toBeUndefined();
|
expect(authData).toBeUndefined();
|
||||||
done();
|
done();
|
||||||
@@ -2360,7 +2360,7 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it_exclude_dbs(['postgres'])('should not serve null authData keys', (done) => {
|
it_exclude_dbs(['postgres'])('should not serve null authData keys', (done) => {
|
||||||
let database = new Config(Parse.applicationId).database;
|
const database = new Config(Parse.applicationId).database;
|
||||||
database.create('_User', {
|
database.create('_User', {
|
||||||
username: 'user',
|
username: 'user',
|
||||||
_hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',
|
_hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie',
|
||||||
@@ -2370,7 +2370,7 @@ describe('Parse.User testing', () => {
|
|||||||
.equalTo('username', 'user')
|
.equalTo('username', 'user')
|
||||||
.first({useMasterKey: true});
|
.first({useMasterKey: true});
|
||||||
}).then((user) => {
|
}).then((user) => {
|
||||||
let authData = user.get('authData');
|
const authData = user.get('authData');
|
||||||
expect(user.get('username')).toEqual('user');
|
expect(user.get('username')).toEqual('user');
|
||||||
expect(authData).toBeUndefined();
|
expect(authData).toBeUndefined();
|
||||||
done();
|
done();
|
||||||
@@ -2570,7 +2570,7 @@ describe('Parse.User testing', () => {
|
|||||||
expect(req.object.get('username')).toEqual('User');
|
expect(req.object.get('username')).toEqual('User');
|
||||||
res.success();
|
res.success();
|
||||||
});
|
});
|
||||||
let user = new Parse.User()
|
const user = new Parse.User()
|
||||||
user.setUsername('User');
|
user.setUsername('User');
|
||||||
user.setPassword('pass');
|
user.setPassword('pass');
|
||||||
user.signUp().then(()=> {
|
user.signUp().then(()=> {
|
||||||
@@ -2587,7 +2587,7 @@ describe('Parse.User testing', () => {
|
|||||||
expect(req.user.get('han')).toEqual('solo');
|
expect(req.user.get('han')).toEqual('solo');
|
||||||
res.success({});
|
res.success({});
|
||||||
});
|
});
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('harrison');
|
user.setUsername('harrison');
|
||||||
user.setPassword('ford');
|
user.setPassword('ford');
|
||||||
user.signUp().then(() => {
|
user.signUp().then(() => {
|
||||||
@@ -2645,19 +2645,19 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should not create extraneous session tokens', (done) => {
|
it('should not create extraneous session tokens', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
config.database.loadSchema().then((s) => {
|
config.database.loadSchema().then((s) => {
|
||||||
// Lock down the _User class for creation
|
// Lock down the _User class for creation
|
||||||
return s.addClassIfNotExists('_User', {}, {create: {}})
|
return s.addClassIfNotExists('_User', {}, {create: {}})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
return user.save({'username': 'user', 'password': 'pass'});
|
return user.save({'username': 'user', 'password': 'pass'});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
fail('should not be able to save the user');
|
fail('should not be able to save the user');
|
||||||
}, () => {
|
}, () => {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('_Session');
|
const q = new Parse.Query('_Session');
|
||||||
return q.find({useMasterKey: true})
|
return q.find({useMasterKey: true})
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
// We should have no session created
|
// We should have no session created
|
||||||
@@ -2713,7 +2713,7 @@ describe('Parse.User testing', () => {
|
|||||||
}, (err, res, body) => {
|
}, (err, res, body) => {
|
||||||
Parse.User.become(body.sessionToken)
|
Parse.User.become(body.sessionToken)
|
||||||
.then(user => {
|
.then(user => {
|
||||||
let obj = new Parse.Object('TestObject');
|
const obj = new Parse.Object('TestObject');
|
||||||
obj.setACL(new Parse.ACL(user));
|
obj.setACL(new Parse.ACL(user));
|
||||||
return obj.save()
|
return obj.save()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
@@ -2751,7 +2751,7 @@ describe('Parse.User testing', () => {
|
|||||||
}, (err, res, body) => {
|
}, (err, res, body) => {
|
||||||
Parse.User.become(body.sessionToken)
|
Parse.User.become(body.sessionToken)
|
||||||
.then(user => {
|
.then(user => {
|
||||||
let obj = new Parse.Object('TestObject');
|
const obj = new Parse.Object('TestObject');
|
||||||
obj.setACL(new Parse.ACL(user));
|
obj.setACL(new Parse.ACL(user));
|
||||||
return obj.save()
|
return obj.save()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
@@ -2769,7 +2769,7 @@ describe('Parse.User testing', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should not fail querying non existing relations', done => {
|
it('should not fail querying non existing relations', done => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'hello',
|
username: 'hello',
|
||||||
password: 'world'
|
password: 'world'
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should work with find', (done) => {
|
it('should work with find', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -19,8 +19,8 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
let obj2 = new Parse.Object('AnObject');
|
const obj2 = new Parse.Object('AnObject');
|
||||||
|
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
obj.set('owner', user);
|
obj.set('owner', user);
|
||||||
@@ -33,7 +33,7 @@ describe('Pointer Permissions', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user1', 'password');
|
return Parse.User.logIn('user1', 'password');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.find();
|
return q.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
expect(res.length).toBe(1);
|
expect(res.length).toBe(1);
|
||||||
@@ -47,9 +47,9 @@ describe('Pointer Permissions', () => {
|
|||||||
|
|
||||||
|
|
||||||
it('should work with write', (done) => {
|
it('should work with write', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -58,8 +58,8 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
let obj2 = new Parse.Object('AnObject');
|
const obj2 = new Parse.Object('AnObject');
|
||||||
|
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
obj.set('owner', user);
|
obj.set('owner', user);
|
||||||
@@ -91,7 +91,7 @@ describe('Pointer Permissions', () => {
|
|||||||
fail('User should be able to update');
|
fail('User should be able to update');
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.find();
|
return q.find();
|
||||||
}, () => {
|
}, () => {
|
||||||
fail('should login with user 2');
|
fail('should login with user 2');
|
||||||
@@ -112,9 +112,9 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should let a proper user find', (done) => {
|
it('should let a proper user find', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -123,8 +123,8 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
let obj2 = new Parse.Object('AnObject');
|
const obj2 = new Parse.Object('AnObject');
|
||||||
user.signUp().then(() => {
|
user.signUp().then(() => {
|
||||||
return user2.signUp()
|
return user2.signUp()
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -137,18 +137,18 @@ describe('Pointer Permissions', () => {
|
|||||||
return schema.updateClass('AnObject', {}, {find: {}, get:{}, readUserFields: ['owner']})
|
return schema.updateClass('AnObject', {}, {find: {}, get:{}, readUserFields: ['owner']})
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.find();
|
return q.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
expect(res.length).toBe(0);
|
expect(res.length).toBe(0);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user2', 'password');
|
return Parse.User.logIn('user2', 'password');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.find();
|
return q.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
expect(res.length).toBe(0);
|
expect(res.length).toBe(0);
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.get(obj.id);
|
return q.get(obj.id);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
fail('User 2 should not get the obj1 object');
|
fail('User 2 should not get the obj1 object');
|
||||||
@@ -159,7 +159,7 @@ describe('Pointer Permissions', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user1', 'password');
|
return Parse.User.logIn('user1', 'password');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.find();
|
return q.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
expect(res.length).toBe(1);
|
expect(res.length).toBe(1);
|
||||||
@@ -172,13 +172,13 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should not allow creating objects', (done) => {
|
it('should not allow creating objects', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
user.save().then(() => {
|
user.save().then(() => {
|
||||||
return config.database.loadSchema().then((schema) => {
|
return config.database.loadSchema().then((schema) => {
|
||||||
return schema.addClassIfNotExists('AnObject', {owner: {type:'Pointer', targetClass: '_User'}}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']});
|
return schema.addClassIfNotExists('AnObject', {owner: {type:'Pointer', targetClass: '_User'}}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']});
|
||||||
@@ -198,9 +198,9 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should handle multiple writeUserFields', done => {
|
it('should handle multiple writeUserFields', done => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -209,7 +209,7 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, user2])
|
Parse.Object.saveAll([user, user2])
|
||||||
.then(() => {
|
.then(() => {
|
||||||
obj.set('owner', user);
|
obj.set('owner', user);
|
||||||
@@ -224,7 +224,7 @@ describe('Pointer Permissions', () => {
|
|||||||
.then(() => obj.save({hello: 'fromUser2'}))
|
.then(() => obj.save({hello: 'fromUser2'}))
|
||||||
.then(() => Parse.User.logOut())
|
.then(() => Parse.User.logOut())
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.first();
|
return q.first();
|
||||||
})
|
})
|
||||||
.then(result => {
|
.then(result => {
|
||||||
@@ -237,7 +237,7 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should prevent creating pointer permission on missing field', (done) => {
|
it('should prevent creating pointer permission on missing field', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
config.database.loadSchema().then((schema) => {
|
config.database.loadSchema().then((schema) => {
|
||||||
return schema.addClassIfNotExists('AnObject', {}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']});
|
return schema.addClassIfNotExists('AnObject', {}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -250,7 +250,7 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should prevent creating pointer permission on bad field', (done) => {
|
it('should prevent creating pointer permission on bad field', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
config.database.loadSchema().then((schema) => {
|
config.database.loadSchema().then((schema) => {
|
||||||
return schema.addClassIfNotExists('AnObject', {owner: {type: 'String'}}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']});
|
return schema.addClassIfNotExists('AnObject', {owner: {type: 'String'}}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -263,8 +263,8 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should prevent creating pointer permission on bad field', (done) => {
|
it('should prevent creating pointer permission on bad field', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('owner', 'value');
|
object.set('owner', 'value');
|
||||||
object.save().then(() => {
|
object.save().then(() => {
|
||||||
return config.database.loadSchema();
|
return config.database.loadSchema();
|
||||||
@@ -288,9 +288,9 @@ describe('Pointer Permissions', () => {
|
|||||||
|
|
||||||
The owner is another user than the ACL
|
The owner is another user than the ACL
|
||||||
*/
|
*/
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -299,9 +299,9 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
let ACL = new Parse.ACL();
|
const ACL = new Parse.ACL();
|
||||||
ACL.setReadAccess(user, true);
|
ACL.setReadAccess(user, true);
|
||||||
ACL.setWriteAccess(user, true);
|
ACL.setWriteAccess(user, true);
|
||||||
obj.setACL(ACL);
|
obj.setACL(ACL);
|
||||||
@@ -333,9 +333,9 @@ describe('Pointer Permissions', () => {
|
|||||||
PointerPerm: "owner"
|
PointerPerm: "owner"
|
||||||
ACL: logged in user has access
|
ACL: logged in user has access
|
||||||
*/
|
*/
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -344,9 +344,9 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
let ACL = new Parse.ACL();
|
const ACL = new Parse.ACL();
|
||||||
ACL.setReadAccess(user, true);
|
ACL.setReadAccess(user, true);
|
||||||
ACL.setWriteAccess(user, true);
|
ACL.setWriteAccess(user, true);
|
||||||
obj.setACL(ACL);
|
obj.setACL(ACL);
|
||||||
@@ -378,9 +378,9 @@ describe('Pointer Permissions', () => {
|
|||||||
PointerPerm: "owner"
|
PointerPerm: "owner"
|
||||||
ACL: logged in user has access
|
ACL: logged in user has access
|
||||||
*/
|
*/
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -389,9 +389,9 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
let ACL = new Parse.ACL();
|
const ACL = new Parse.ACL();
|
||||||
ACL.setWriteAccess(user, true);
|
ACL.setWriteAccess(user, true);
|
||||||
ACL.setWriteAccess(user2, true);
|
ACL.setWriteAccess(user2, true);
|
||||||
obj.setACL(ACL);
|
obj.setACL(ACL);
|
||||||
@@ -425,9 +425,9 @@ describe('Pointer Permissions', () => {
|
|||||||
|
|
||||||
The owner is another user than the ACL
|
The owner is another user than the ACL
|
||||||
*/
|
*/
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -436,9 +436,9 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
let ACL = new Parse.ACL();
|
const ACL = new Parse.ACL();
|
||||||
ACL.setReadAccess(user, true);
|
ACL.setReadAccess(user, true);
|
||||||
ACL.setWriteAccess(user, true);
|
ACL.setWriteAccess(user, true);
|
||||||
obj.setACL(ACL);
|
obj.setACL(ACL);
|
||||||
@@ -470,9 +470,9 @@ describe('Pointer Permissions', () => {
|
|||||||
PointerPerm: "owner" : read
|
PointerPerm: "owner" : read
|
||||||
ACL: logged in user has access
|
ACL: logged in user has access
|
||||||
*/
|
*/
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -481,9 +481,9 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
let ACL = new Parse.ACL();
|
const ACL = new Parse.ACL();
|
||||||
ACL.setReadAccess(user, true);
|
ACL.setReadAccess(user, true);
|
||||||
ACL.setWriteAccess(user, true);
|
ACL.setWriteAccess(user, true);
|
||||||
ACL.setReadAccess(user2, true);
|
ACL.setReadAccess(user2, true);
|
||||||
@@ -517,9 +517,9 @@ describe('Pointer Permissions', () => {
|
|||||||
PointerPerm: "owner" : read // proper owner
|
PointerPerm: "owner" : read // proper owner
|
||||||
ACL: logged in user has not access
|
ACL: logged in user has not access
|
||||||
*/
|
*/
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user.set({
|
user.set({
|
||||||
username: 'user1',
|
username: 'user1',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
@@ -528,9 +528,9 @@ describe('Pointer Permissions', () => {
|
|||||||
username: 'user2',
|
username: 'user2',
|
||||||
password: 'password'
|
password: 'password'
|
||||||
});
|
});
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, user2]).then(() => {
|
Parse.Object.saveAll([user, user2]).then(() => {
|
||||||
let ACL = new Parse.ACL();
|
const ACL = new Parse.ACL();
|
||||||
ACL.setReadAccess(user, true);
|
ACL.setReadAccess(user, true);
|
||||||
ACL.setWriteAccess(user, true);
|
ACL.setWriteAccess(user, true);
|
||||||
obj.setACL(ACL);
|
obj.setACL(ACL);
|
||||||
@@ -556,8 +556,8 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should let master key find objects', (done) => {
|
it('should let master key find objects', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('hello', 'world');
|
object.set('hello', 'world');
|
||||||
return object.save().then(() => {
|
return object.save().then(() => {
|
||||||
return config.database.loadSchema().then((schema) => {
|
return config.database.loadSchema().then((schema) => {
|
||||||
@@ -565,7 +565,7 @@ describe('Pointer Permissions', () => {
|
|||||||
return schema.updateClass('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {find: {}, get: {}, readUserFields: ['owner']});
|
return schema.updateClass('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {find: {}, get: {}, readUserFields: ['owner']});
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.find();
|
return q.find();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
|
|
||||||
@@ -573,7 +573,7 @@ describe('Pointer Permissions', () => {
|
|||||||
expect(err.code).toBe(101);
|
expect(err.code).toBe(101);
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.find({useMasterKey: true});
|
return q.find({useMasterKey: true});
|
||||||
}).then((objects) => {
|
}).then((objects) => {
|
||||||
expect(objects.length).toBe(1);
|
expect(objects.length).toBe(1);
|
||||||
@@ -585,8 +585,8 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should let master key get objects', (done) => {
|
it('should let master key get objects', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('hello', 'world');
|
object.set('hello', 'world');
|
||||||
return object.save().then(() => {
|
return object.save().then(() => {
|
||||||
return config.database.loadSchema().then((schema) => {
|
return config.database.loadSchema().then((schema) => {
|
||||||
@@ -594,7 +594,7 @@ describe('Pointer Permissions', () => {
|
|||||||
return schema.updateClass('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {find: {}, get: {}, readUserFields: ['owner']});
|
return schema.updateClass('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {find: {}, get: {}, readUserFields: ['owner']});
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.get(object.id);
|
return q.get(object.id);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
|
|
||||||
@@ -602,7 +602,7 @@ describe('Pointer Permissions', () => {
|
|||||||
expect(err.code).toBe(101);
|
expect(err.code).toBe(101);
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let q = new Parse.Query('AnObject');
|
const q = new Parse.Query('AnObject');
|
||||||
return q.get(object.id, {useMasterKey: true});
|
return q.get(object.id, {useMasterKey: true});
|
||||||
}).then((objectAgain) => {
|
}).then((objectAgain) => {
|
||||||
expect(objectAgain).not.toBeUndefined();
|
expect(objectAgain).not.toBeUndefined();
|
||||||
@@ -616,8 +616,8 @@ describe('Pointer Permissions', () => {
|
|||||||
|
|
||||||
|
|
||||||
it('should let master key update objects', (done) => {
|
it('should let master key update objects', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('hello', 'world');
|
object.set('hello', 'world');
|
||||||
return object.save().then(() => {
|
return object.save().then(() => {
|
||||||
return config.database.loadSchema().then((schema) => {
|
return config.database.loadSchema().then((schema) => {
|
||||||
@@ -643,8 +643,8 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should let master key delete objects', (done) => {
|
it('should let master key delete objects', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
object.set('hello', 'world');
|
object.set('hello', 'world');
|
||||||
return object.save().then(() => {
|
return object.save().then(() => {
|
||||||
return config.database.loadSchema().then((schema) => {
|
return config.database.loadSchema().then((schema) => {
|
||||||
@@ -669,7 +669,7 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should fail with invalid pointer perms', (done) => {
|
it('should fail with invalid pointer perms', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
config.database.loadSchema().then((schema) => {
|
config.database.loadSchema().then((schema) => {
|
||||||
// Lock the update, and let only owner write
|
// Lock the update, and let only owner write
|
||||||
return schema.addClassIfNotExists('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {delete: {}, writeUserFields: 'owner'});
|
return schema.addClassIfNotExists('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {delete: {}, writeUserFields: 'owner'});
|
||||||
@@ -680,7 +680,7 @@ describe('Pointer Permissions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should fail with invalid pointer perms', (done) => {
|
it('should fail with invalid pointer perms', (done) => {
|
||||||
let config = new Config(Parse.applicationId);
|
const config = new Config(Parse.applicationId);
|
||||||
config.database.loadSchema().then((schema) => {
|
config.database.loadSchema().then((schema) => {
|
||||||
// Lock the update, and let only owner write
|
// Lock the update, and let only owner write
|
||||||
return schema.addClassIfNotExists('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {delete: {}, writeUserFields: ['owner', 'invalid']});
|
return schema.addClassIfNotExists('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {delete: {}, writeUserFields: ['owner', 'invalid']});
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ var Config = require('../src/Config');
|
|||||||
|
|
||||||
const successfulTransmissions = function(body, installations) {
|
const successfulTransmissions = function(body, installations) {
|
||||||
|
|
||||||
let promises = installations.map((device) => {
|
const promises = installations.map((device) => {
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
transmitted: true,
|
transmitted: true,
|
||||||
device: device,
|
device: device,
|
||||||
@@ -17,7 +17,7 @@ const successfulTransmissions = function(body, installations) {
|
|||||||
|
|
||||||
const successfulIOS = function(body, installations) {
|
const successfulIOS = function(body, installations) {
|
||||||
|
|
||||||
let promises = installations.map((device) => {
|
const promises = installations.map((device) => {
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
transmitted: device.deviceType == "ios",
|
transmitted: device.deviceType == "ios",
|
||||||
device: device,
|
device: device,
|
||||||
@@ -138,7 +138,7 @@ describe('PushController', () => {
|
|||||||
}}
|
}}
|
||||||
var installations = [];
|
var installations = [];
|
||||||
while(installations.length != 10) {
|
while(installations.length != 10) {
|
||||||
let installation = new Parse.Object("_Installation");
|
const installation = new Parse.Object("_Installation");
|
||||||
installation.set("installationId", "installation_"+installations.length);
|
installation.set("installationId", "installation_"+installations.length);
|
||||||
installation.set("deviceToken","device_token_"+installations.length)
|
installation.set("deviceToken","device_token_"+installations.length)
|
||||||
installation.set("badge", installations.length);
|
installation.set("badge", installations.length);
|
||||||
@@ -148,7 +148,7 @@ describe('PushController', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
while(installations.length != 15) {
|
while(installations.length != 15) {
|
||||||
let installation = new Parse.Object("_Installation");
|
const installation = new Parse.Object("_Installation");
|
||||||
installation.set("installationId", "installation_"+installations.length);
|
installation.set("installationId", "installation_"+installations.length);
|
||||||
installation.set("deviceToken","device_token_"+installations.length)
|
installation.set("deviceToken","device_token_"+installations.length)
|
||||||
installation.set("deviceType", "android");
|
installation.set("deviceType", "android");
|
||||||
@@ -279,16 +279,16 @@ describe('PushController', () => {
|
|||||||
|
|
||||||
var pushController = new PushController(pushAdapter, Parse.applicationId, defaultConfiguration.push);
|
var pushController = new PushController(pushAdapter, Parse.applicationId, defaultConfiguration.push);
|
||||||
Parse.Object.saveAll(installations).then((installations) => {
|
Parse.Object.saveAll(installations).then((installations) => {
|
||||||
let objectIds = installations.map(installation => {
|
const objectIds = installations.map(installation => {
|
||||||
return installation.id;
|
return installation.id;
|
||||||
})
|
})
|
||||||
let where = {
|
const where = {
|
||||||
objectId: {'$in': objectIds.slice(0, 5)}
|
objectId: {'$in': objectIds.slice(0, 5)}
|
||||||
}
|
}
|
||||||
return pushController.sendPush(payload, where, config, auth);
|
return pushController.sendPush(payload, where, config, auth);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
expect(matchedInstallationsCount).toBe(5);
|
expect(matchedInstallationsCount).toBe(5);
|
||||||
let query = new Parse.Query(Parse.Installation);
|
const query = new Parse.Query(Parse.Installation);
|
||||||
query.equalTo('badge', 1);
|
query.equalTo('badge', 1);
|
||||||
return query.find({useMasterKey: true});
|
return query.find({useMasterKey: true});
|
||||||
}).then((installations) => {
|
}).then((installations) => {
|
||||||
@@ -304,7 +304,7 @@ describe('PushController', () => {
|
|||||||
|
|
||||||
var installations = [];
|
var installations = [];
|
||||||
while(installations.length != 10) {
|
while(installations.length != 10) {
|
||||||
let installation = new Parse.Object("_Installation");
|
const installation = new Parse.Object("_Installation");
|
||||||
installation.set("installationId", "installation_"+installations.length);
|
installation.set("installationId", "installation_"+installations.length);
|
||||||
installation.set("deviceToken","device_token_"+installations.length)
|
installation.set("deviceToken","device_token_"+installations.length)
|
||||||
installation.set("badge", installations.length);
|
installation.set("badge", installations.length);
|
||||||
@@ -314,7 +314,7 @@ describe('PushController', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
while(installations.length != 15) {
|
while(installations.length != 15) {
|
||||||
let installation = new Parse.Object("_Installation");
|
const installation = new Parse.Object("_Installation");
|
||||||
installation.set("installationId", "installation_"+installations.length);
|
installation.set("installationId", "installation_"+installations.length);
|
||||||
installation.set("deviceToken","device_token_"+installations.length)
|
installation.set("deviceToken","device_token_"+installations.length)
|
||||||
installation.set("deviceType", "android");
|
installation.set("deviceType", "android");
|
||||||
@@ -349,11 +349,11 @@ describe('PushController', () => {
|
|||||||
}, 1000);
|
}, 1000);
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('_PushStatus');
|
const query = new Parse.Query('_PushStatus');
|
||||||
return query.find({useMasterKey: true});
|
return query.find({useMasterKey: true});
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let result = results[0];
|
const result = results[0];
|
||||||
expect(result.createdAt instanceof Date).toBe(true);
|
expect(result.createdAt instanceof Date).toBe(true);
|
||||||
expect(result.updatedAt instanceof Date).toBe(true);
|
expect(result.updatedAt instanceof Date).toBe(true);
|
||||||
expect(result.id.length).toBe(10);
|
expect(result.id.length).toBe(10);
|
||||||
@@ -371,7 +371,7 @@ describe('PushController', () => {
|
|||||||
'android': 5 // android
|
'android': 5 // android
|
||||||
});
|
});
|
||||||
// Try to get it without masterKey
|
// Try to get it without masterKey
|
||||||
let query = new Parse.Query('_PushStatus');
|
const query = new Parse.Query('_PushStatus');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(0);
|
expect(results.length).toBe(0);
|
||||||
@@ -393,7 +393,7 @@ describe('PushController', () => {
|
|||||||
return ["ios"];
|
return ["ios"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let where = { 'channels': {
|
const where = { 'channels': {
|
||||||
'$ins': ['Giants', 'Mets']
|
'$ins': ['Giants', 'Mets']
|
||||||
}};
|
}};
|
||||||
var payload = {data: {
|
var payload = {data: {
|
||||||
@@ -409,10 +409,10 @@ describe('PushController', () => {
|
|||||||
fail('should not succeed');
|
fail('should not succeed');
|
||||||
done();
|
done();
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
let query = new Parse.Query('_PushStatus');
|
const query = new Parse.Query('_PushStatus');
|
||||||
query.find({useMasterKey: true}).then((results) => {
|
query.find({useMasterKey: true}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
let pushStatus = results[0];
|
const pushStatus = results[0];
|
||||||
expect(pushStatus.get('status')).toBe('failed');
|
expect(pushStatus.get('status')).toBe('failed');
|
||||||
done();
|
done();
|
||||||
});
|
});
|
||||||
@@ -439,7 +439,7 @@ describe('PushController', () => {
|
|||||||
isMaster: true
|
isMaster: true
|
||||||
}
|
}
|
||||||
|
|
||||||
let where = {
|
const where = {
|
||||||
'deviceToken': {
|
'deviceToken': {
|
||||||
'$inQuery': {
|
'$inQuery': {
|
||||||
'where': {
|
'where': {
|
||||||
@@ -480,7 +480,7 @@ describe('PushController', () => {
|
|||||||
isMaster: true
|
isMaster: true
|
||||||
}
|
}
|
||||||
|
|
||||||
let where = {
|
const where = {
|
||||||
'deviceToken': {
|
'deviceToken': {
|
||||||
'$inQuery': {
|
'$inQuery': {
|
||||||
'where': {
|
'where': {
|
||||||
|
|||||||
@@ -173,7 +173,7 @@ describe('rest query', () => {
|
|||||||
'X-Parse-REST-API-Key': 'rest'
|
'X-Parse-REST-API-Key': 'rest'
|
||||||
};
|
};
|
||||||
|
|
||||||
let p0 = rp.get({
|
const p0 = rp.get({
|
||||||
headers: headers,
|
headers: headers,
|
||||||
url: 'http://localhost:8378/1/classes/TestParameterEncode?'
|
url: 'http://localhost:8378/1/classes/TestParameterEncode?'
|
||||||
+ querystring.stringify({
|
+ querystring.stringify({
|
||||||
@@ -181,19 +181,19 @@ describe('rest query', () => {
|
|||||||
limit: 1
|
limit: 1
|
||||||
}).replace('=', '%3D'),
|
}).replace('=', '%3D'),
|
||||||
}).then(fail, (response) => {
|
}).then(fail, (response) => {
|
||||||
let error = response.error;
|
const error = response.error;
|
||||||
var b = JSON.parse(error);
|
var b = JSON.parse(error);
|
||||||
expect(b.code).toEqual(Parse.Error.INVALID_QUERY);
|
expect(b.code).toEqual(Parse.Error.INVALID_QUERY);
|
||||||
});
|
});
|
||||||
|
|
||||||
let p1 = rp.get({
|
const p1 = rp.get({
|
||||||
headers: headers,
|
headers: headers,
|
||||||
url: 'http://localhost:8378/1/classes/TestParameterEncode?'
|
url: 'http://localhost:8378/1/classes/TestParameterEncode?'
|
||||||
+ querystring.stringify({
|
+ querystring.stringify({
|
||||||
limit: 1
|
limit: 1
|
||||||
}).replace('=', '%3D'),
|
}).replace('=', '%3D'),
|
||||||
}).then(fail, (response) => {
|
}).then(fail, (response) => {
|
||||||
let error = response.error;
|
const error = response.error;
|
||||||
var b = JSON.parse(error);
|
var b = JSON.parse(error);
|
||||||
expect(b.code).toEqual(Parse.Error.INVALID_QUERY);
|
expect(b.code).toEqual(Parse.Error.INVALID_QUERY);
|
||||||
});
|
});
|
||||||
@@ -235,21 +235,21 @@ describe('rest query', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('makes sure null pointers are handed correctly #2189', done => {
|
it('makes sure null pointers are handed correctly #2189', done => {
|
||||||
let object = new Parse.Object('AnObject');
|
const object = new Parse.Object('AnObject');
|
||||||
let anotherObject = new Parse.Object('AnotherObject');
|
const anotherObject = new Parse.Object('AnotherObject');
|
||||||
anotherObject.save().then(() => {
|
anotherObject.save().then(() => {
|
||||||
object.set('values', [null, null, anotherObject]);
|
object.set('values', [null, null, anotherObject]);
|
||||||
return object.save();
|
return object.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AnObject');
|
const query = new Parse.Query('AnObject');
|
||||||
query.include('values');
|
query.include('values');
|
||||||
return query.first();
|
return query.first();
|
||||||
}).then((result) => {
|
}).then((result) => {
|
||||||
let values = result.get('values');
|
const values = result.get('values');
|
||||||
expect(values.length).toBe(3);
|
expect(values.length).toBe(3);
|
||||||
let anotherObjectFound = false;
|
let anotherObjectFound = false;
|
||||||
let nullCounts = 0;
|
let nullCounts = 0;
|
||||||
for(let value of values) {
|
for(const value of values) {
|
||||||
if (value === null) {
|
if (value === null) {
|
||||||
nullCounts++;
|
nullCounts++;
|
||||||
} else if (value instanceof Parse.Object) {
|
} else if (value instanceof Parse.Object) {
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ describe_only_db('mongo')('revocable sessions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should upgrade legacy session token', done => {
|
it('should upgrade legacy session token', done => {
|
||||||
let user = Parse.Object.fromJSON({
|
const user = Parse.Object.fromJSON({
|
||||||
className: '_User',
|
className: '_User',
|
||||||
objectId: '1234567890',
|
objectId: '1234567890',
|
||||||
sessionToken: sessionToken
|
sessionToken: sessionToken
|
||||||
@@ -49,7 +49,7 @@ describe_only_db('mongo')('revocable sessions', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should be able to become with revocable session token', done => {
|
it('should be able to become with revocable session token', done => {
|
||||||
let user = Parse.Object.fromJSON({
|
const user = Parse.Object.fromJSON({
|
||||||
className: '_User',
|
className: '_User',
|
||||||
objectId: '1234567890',
|
objectId: '1234567890',
|
||||||
sessionToken: sessionToken
|
sessionToken: sessionToken
|
||||||
|
|||||||
@@ -824,9 +824,9 @@ describe('SchemaController', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('yields a proper schema mismatch error (#2661)', done => {
|
it('yields a proper schema mismatch error (#2661)', done => {
|
||||||
let anObject = new Parse.Object('AnObject');
|
const anObject = new Parse.Object('AnObject');
|
||||||
let anotherObject = new Parse.Object('AnotherObject');
|
const anotherObject = new Parse.Object('AnotherObject');
|
||||||
let someObject = new Parse.Object('SomeObject');
|
const someObject = new Parse.Object('SomeObject');
|
||||||
Parse.Object.saveAll([anObject, anotherObject, someObject]).then(() => {
|
Parse.Object.saveAll([anObject, anotherObject, someObject]).then(() => {
|
||||||
anObject.set('pointer', anotherObject);
|
anObject.set('pointer', anotherObject);
|
||||||
return anObject.save();
|
return anObject.save();
|
||||||
@@ -844,8 +844,8 @@ describe('SchemaController', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('yields a proper schema mismatch error bis (#2661)', done => {
|
it('yields a proper schema mismatch error bis (#2661)', done => {
|
||||||
let anObject = new Parse.Object('AnObject');
|
const anObject = new Parse.Object('AnObject');
|
||||||
let someObject = new Parse.Object('SomeObject');
|
const someObject = new Parse.Object('SomeObject');
|
||||||
Parse.Object.saveAll([anObject, someObject]).then(() => {
|
Parse.Object.saveAll([anObject, someObject]).then(() => {
|
||||||
anObject.set('number', 1);
|
anObject.set('number', 1);
|
||||||
return anObject.save();
|
return anObject.save();
|
||||||
@@ -863,8 +863,8 @@ describe('SchemaController', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('yields a proper schema mismatch error ter (#2661)', done => {
|
it('yields a proper schema mismatch error ter (#2661)', done => {
|
||||||
let anObject = new Parse.Object('AnObject');
|
const anObject = new Parse.Object('AnObject');
|
||||||
let someObject = new Parse.Object('SomeObject');
|
const someObject = new Parse.Object('SomeObject');
|
||||||
Parse.Object.saveAll([anObject, someObject]).then(() => {
|
Parse.Object.saveAll([anObject, someObject]).then(() => {
|
||||||
anObject.set('pointer', someObject);
|
anObject.set('pointer', someObject);
|
||||||
return anObject.save();
|
return anObject.save();
|
||||||
@@ -889,7 +889,7 @@ describe('SchemaController', () => {
|
|||||||
}
|
}
|
||||||
function validateSchemaDataStructure(schemaData) {
|
function validateSchemaDataStructure(schemaData) {
|
||||||
Object.keys(schemaData).forEach(className => {
|
Object.keys(schemaData).forEach(className => {
|
||||||
let schema = schemaData[className];
|
const schema = schemaData[className];
|
||||||
// Hooks has className...
|
// Hooks has className...
|
||||||
if (className != '_Hooks') {
|
if (className != '_Hooks') {
|
||||||
expect(schema.hasOwnProperty('className')).toBe(false);
|
expect(schema.hasOwnProperty('className')).toBe(false);
|
||||||
@@ -921,7 +921,7 @@ describe('Class Level Permissions for requiredAuth', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
function createUser() {
|
function createUser() {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.set("username", "hello");
|
user.set("username", "hello");
|
||||||
user.set("password", "world");
|
user.set("password", "world");
|
||||||
return user.signUp(null);
|
return user.signUp(null);
|
||||||
@@ -987,7 +987,7 @@ describe('Class Level Permissions for requiredAuth', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return createUser();
|
return createUser();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let stuff = new Parse.Object('Stuff');
|
const stuff = new Parse.Object('Stuff');
|
||||||
stuff.set('foo', 'bar');
|
stuff.set('foo', 'bar');
|
||||||
return stuff.save();
|
return stuff.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -1010,7 +1010,7 @@ describe('Class Level Permissions for requiredAuth', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let stuff = new Parse.Object('Stuff');
|
const stuff = new Parse.Object('Stuff');
|
||||||
stuff.set('foo', 'bar');
|
stuff.set('foo', 'bar');
|
||||||
return stuff.save();
|
return stuff.save();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -1044,10 +1044,10 @@ describe('Class Level Permissions for requiredAuth', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return createUser();
|
return createUser();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let stuff = new Parse.Object('Stuff');
|
const stuff = new Parse.Object('Stuff');
|
||||||
stuff.set('foo', 'bar');
|
stuff.set('foo', 'bar');
|
||||||
return stuff.save().then(() => {
|
return stuff.save().then(() => {
|
||||||
let query = new Parse.Query('Stuff');
|
const query = new Parse.Query('Stuff');
|
||||||
return query.get(stuff.id);
|
return query.get(stuff.id);
|
||||||
});
|
});
|
||||||
}).then((gotStuff) => {
|
}).then((gotStuff) => {
|
||||||
@@ -1083,10 +1083,10 @@ describe('Class Level Permissions for requiredAuth', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let stuff = new Parse.Object('Stuff');
|
const stuff = new Parse.Object('Stuff');
|
||||||
stuff.set('foo', 'bar');
|
stuff.set('foo', 'bar');
|
||||||
return stuff.save().then(() => {
|
return stuff.save().then(() => {
|
||||||
let query = new Parse.Query('Stuff');
|
const query = new Parse.Query('Stuff');
|
||||||
return query.get(stuff.id);
|
return query.get(stuff.id);
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -1121,15 +1121,15 @@ describe('Class Level Permissions for requiredAuth', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let stuff = new Parse.Object('Stuff');
|
const stuff = new Parse.Object('Stuff');
|
||||||
stuff.set('foo', 'bar');
|
stuff.set('foo', 'bar');
|
||||||
return stuff.save().then(() => {
|
return stuff.save().then(() => {
|
||||||
let query = new Parse.Query('Stuff');
|
const query = new Parse.Query('Stuff');
|
||||||
return query.get(stuff.id);
|
return query.get(stuff.id);
|
||||||
})
|
})
|
||||||
}).then((result) => {
|
}).then((result) => {
|
||||||
expect(result.get('foo')).toEqual('bar');
|
expect(result.get('foo')).toEqual('bar');
|
||||||
let query = new Parse.Query('Stuff');
|
const query = new Parse.Query('Stuff');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
fail("Should not succeed!");
|
fail("Should not succeed!");
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
let twitter = require('../src/Adapters/Auth/twitter');
|
const twitter = require('../src/Adapters/Auth/twitter');
|
||||||
|
|
||||||
describe('Twitter Auth', () => {
|
describe('Twitter Auth', () => {
|
||||||
it('should use the proper configuration', () => {
|
it('should use the proper configuration', () => {
|
||||||
|
|||||||
@@ -1,19 +1,19 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
const Parse = require("parse/node");
|
const Parse = require("parse/node");
|
||||||
let Config = require('../src/Config');
|
const Config = require('../src/Config');
|
||||||
|
|
||||||
describe('Uniqueness', function() {
|
describe('Uniqueness', function() {
|
||||||
it('fail when create duplicate value in unique field', done => {
|
it('fail when create duplicate value in unique field', done => {
|
||||||
let obj = new Parse.Object('UniqueField');
|
const obj = new Parse.Object('UniqueField');
|
||||||
obj.set('unique', 'value');
|
obj.set('unique', 'value');
|
||||||
obj.save().then(() => {
|
obj.save().then(() => {
|
||||||
expect(obj.id).not.toBeUndefined();
|
expect(obj.id).not.toBeUndefined();
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
return config.database.adapter.ensureUniqueness('UniqueField', { fields: { unique: { __type: 'String' } } }, ['unique'])
|
return config.database.adapter.ensureUniqueness('UniqueField', { fields: { unique: { __type: 'String' } } }, ['unique'])
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let obj = new Parse.Object('UniqueField');
|
const obj = new Parse.Object('UniqueField');
|
||||||
obj.set('unique', 'value');
|
obj.set('unique', 'value');
|
||||||
return obj.save()
|
return obj.save()
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -26,18 +26,18 @@ describe('Uniqueness', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('unique indexing works on pointer fields', done => {
|
it('unique indexing works on pointer fields', done => {
|
||||||
let obj = new Parse.Object('UniquePointer');
|
const obj = new Parse.Object('UniquePointer');
|
||||||
obj.save({ string: 'who cares' })
|
obj.save({ string: 'who cares' })
|
||||||
.then(() => obj.save({ ptr: obj }))
|
.then(() => obj.save({ ptr: obj }))
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
return config.database.adapter.ensureUniqueness('UniquePointer', { fields: {
|
return config.database.adapter.ensureUniqueness('UniquePointer', { fields: {
|
||||||
string: { __type: 'String' },
|
string: { __type: 'String' },
|
||||||
ptr: { __type: 'Pointer', targetClass: 'UniquePointer' }
|
ptr: { __type: 'Pointer', targetClass: 'UniquePointer' }
|
||||||
} }, ['ptr']);
|
} }, ['ptr']);
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let newObj = new Parse.Object('UniquePointer')
|
const newObj = new Parse.Object('UniquePointer')
|
||||||
newObj.set('ptr', obj)
|
newObj.set('ptr', obj)
|
||||||
return newObj.save()
|
return newObj.save()
|
||||||
})
|
})
|
||||||
@@ -52,13 +52,13 @@ describe('Uniqueness', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('fails when attempting to ensure uniqueness of fields that are not currently unique', done => {
|
it('fails when attempting to ensure uniqueness of fields that are not currently unique', done => {
|
||||||
let o1 = new Parse.Object('UniqueFail');
|
const o1 = new Parse.Object('UniqueFail');
|
||||||
o1.set('key', 'val');
|
o1.set('key', 'val');
|
||||||
let o2 = new Parse.Object('UniqueFail');
|
const o2 = new Parse.Object('UniqueFail');
|
||||||
o2.set('key', 'val');
|
o2.set('key', 'val');
|
||||||
Parse.Object.saveAll([o1, o2])
|
Parse.Object.saveAll([o1, o2])
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
return config.database.adapter.ensureUniqueness('UniqueFail', { fields: { key: { __type: 'String' } } }, ['key']);
|
return config.database.adapter.ensureUniqueness('UniqueFail', { fields: { key: { __type: 'String' } } }, ['key']);
|
||||||
})
|
})
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
@@ -68,28 +68,28 @@ describe('Uniqueness', function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it_exclude_dbs(['postgres'])('can do compound uniqueness', done => {
|
it_exclude_dbs(['postgres'])('can do compound uniqueness', done => {
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
config.database.adapter.ensureUniqueness('CompoundUnique', { fields: { k1: { __type: 'String' }, k2: { __type: 'String' } } }, ['k1', 'k2'])
|
config.database.adapter.ensureUniqueness('CompoundUnique', { fields: { k1: { __type: 'String' }, k2: { __type: 'String' } } }, ['k1', 'k2'])
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let o1 = new Parse.Object('CompoundUnique');
|
const o1 = new Parse.Object('CompoundUnique');
|
||||||
o1.set('k1', 'v1');
|
o1.set('k1', 'v1');
|
||||||
o1.set('k2', 'v2');
|
o1.set('k2', 'v2');
|
||||||
return o1.save();
|
return o1.save();
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let o2 = new Parse.Object('CompoundUnique');
|
const o2 = new Parse.Object('CompoundUnique');
|
||||||
o2.set('k1', 'v1');
|
o2.set('k1', 'v1');
|
||||||
o2.set('k2', 'not a dupe');
|
o2.set('k2', 'not a dupe');
|
||||||
return o2.save();
|
return o2.save();
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let o3 = new Parse.Object('CompoundUnique');
|
const o3 = new Parse.Object('CompoundUnique');
|
||||||
o3.set('k1', 'not a dupe');
|
o3.set('k1', 'not a dupe');
|
||||||
o3.set('k2', 'v2');
|
o3.set('k2', 'v2');
|
||||||
return o3.save();
|
return o3.save();
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let o4 = new Parse.Object('CompoundUnique');
|
const o4 = new Parse.Object('CompoundUnique');
|
||||||
o4.set('k1', 'v1');
|
o4.set('k1', 'v1');
|
||||||
o4.set('k2', 'v2');
|
o4.set('k2', 'v2');
|
||||||
return o4.save();
|
return o4.save();
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
let MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions');
|
const MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions');
|
||||||
let request = require('request');
|
const request = require('request');
|
||||||
let Config = require("../src/Config");
|
const Config = require("../src/Config");
|
||||||
|
|
||||||
describe("Custom Pages, Email Verification, Password Reset", () => {
|
describe("Custom Pages, Email Verification, Password Reset", () => {
|
||||||
it("should set the custom pages", (done) => {
|
it("should set the custom pages", (done) => {
|
||||||
@@ -251,7 +251,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword("asdf");
|
user.setPassword("asdf");
|
||||||
user.setUsername("zxcv");
|
user.setUsername("zxcv");
|
||||||
user.set("email", "testInvalidConfig@parse.com");
|
user.set("email", "testInvalidConfig@parse.com");
|
||||||
@@ -338,7 +338,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword("asdf");
|
user.setPassword("asdf");
|
||||||
user.setUsername("zxcv");
|
user.setUsername("zxcv");
|
||||||
user.set("email", "testInvalidConfig@parse.com");
|
user.set("email", "testInvalidConfig@parse.com");
|
||||||
@@ -370,7 +370,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword("asdf");
|
user.setPassword("asdf");
|
||||||
user.setUsername("zxcv");
|
user.setUsername("zxcv");
|
||||||
user.set("email", "testInvalidConfig@parse.com");
|
user.set("email", "testInvalidConfig@parse.com");
|
||||||
@@ -401,7 +401,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword("asdf");
|
user.setPassword("asdf");
|
||||||
user.setUsername("zxcv");
|
user.setUsername("zxcv");
|
||||||
user.set("email", "testInvalidConfig@parse.com");
|
user.set("email", "testInvalidConfig@parse.com");
|
||||||
@@ -429,7 +429,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
emailAdapter: undefined,
|
emailAdapter: undefined,
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword("asdf");
|
user.setPassword("asdf");
|
||||||
user.setUsername("zxcv");
|
user.setUsername("zxcv");
|
||||||
user.set("email", "testInvalidConfig@parse.com");
|
user.set("email", "testInvalidConfig@parse.com");
|
||||||
@@ -461,7 +461,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
}),
|
}),
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword("asdf");
|
user.setPassword("asdf");
|
||||||
user.setUsername("zxcv");
|
user.setUsername("zxcv");
|
||||||
user.set("email", "testInvalidConfig@parse.com");
|
user.set("email", "testInvalidConfig@parse.com");
|
||||||
@@ -480,7 +480,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('succeeds sending a password reset username if appName, publicServerURL, and email adapter are prodvided', done => {
|
it('succeeds sending a password reset username if appName, publicServerURL, and email adapter are prodvided', done => {
|
||||||
let adapter = MockEmailAdapterWithOptions({
|
const adapter = MockEmailAdapterWithOptions({
|
||||||
fromAddress: 'parse@example.com',
|
fromAddress: 'parse@example.com',
|
||||||
apiKey: 'k',
|
apiKey: 'k',
|
||||||
domain: 'd',
|
domain: 'd',
|
||||||
@@ -500,7 +500,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
emailAdapter: adapter
|
emailAdapter: adapter
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setPassword("asdf");
|
user.setPassword("asdf");
|
||||||
user.setUsername("testValidConfig@parse.com");
|
user.setUsername("testValidConfig@parse.com");
|
||||||
user.signUp(null)
|
user.signUp(null)
|
||||||
@@ -819,7 +819,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
|
|||||||
expect(response.body).toEqual('Found. Redirecting to http://localhost:8378/1/apps/password_reset_success.html?username=zxcv');
|
expect(response.body).toEqual('Found. Redirecting to http://localhost:8378/1/apps/password_reset_success.html?username=zxcv');
|
||||||
|
|
||||||
Parse.User.logIn("zxcv", "hello").then(function(){
|
Parse.User.logIn("zxcv", "hello").then(function(){
|
||||||
let config = new Config('test');
|
const config = new Config('test');
|
||||||
config.database.adapter.find('_User', { fields: {} }, { 'username': 'zxcv' }, { limit: 1 })
|
config.database.adapter.find('_User', { fields: {} }, { 'username': 'zxcv' }, { limit: 1 })
|
||||||
.then(results => {
|
.then(results => {
|
||||||
// _perishable_token should be unset after reset password
|
// _perishable_token should be unset after reset password
|
||||||
|
|||||||
@@ -60,14 +60,14 @@ describe('verbose logs', () => {
|
|||||||
reconfigureServer({ verbose: true })
|
reconfigureServer({ verbose: true })
|
||||||
.then(() => createTestUser())
|
.then(() => createTestUser())
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let winstonLoggerAdapter = new WinstonLoggerAdapter();
|
const winstonLoggerAdapter = new WinstonLoggerAdapter();
|
||||||
return winstonLoggerAdapter.query({
|
return winstonLoggerAdapter.query({
|
||||||
from: new Date(Date.now() - 500),
|
from: new Date(Date.now() - 500),
|
||||||
size: 100,
|
size: 100,
|
||||||
level: 'verbose'
|
level: 'verbose'
|
||||||
});
|
});
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
let logString = JSON.stringify(results);
|
const logString = JSON.stringify(results);
|
||||||
expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0);
|
expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0);
|
||||||
expect(logString.match(/moon-y/g)).toBe(null);
|
expect(logString.match(/moon-y/g)).toBe(null);
|
||||||
|
|
||||||
@@ -79,13 +79,13 @@ describe('verbose logs', () => {
|
|||||||
headers: headers,
|
headers: headers,
|
||||||
url: 'http://localhost:8378/1/login?username=test&password=moon-y'
|
url: 'http://localhost:8378/1/login?username=test&password=moon-y'
|
||||||
}, () => {
|
}, () => {
|
||||||
let winstonLoggerAdapter = new WinstonLoggerAdapter();
|
const winstonLoggerAdapter = new WinstonLoggerAdapter();
|
||||||
return winstonLoggerAdapter.query({
|
return winstonLoggerAdapter.query({
|
||||||
from: new Date(Date.now() - 500),
|
from: new Date(Date.now() - 500),
|
||||||
size: 100,
|
size: 100,
|
||||||
level: 'verbose'
|
level: 'verbose'
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
let logString = JSON.stringify(results);
|
const logString = JSON.stringify(results);
|
||||||
expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0);
|
expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0);
|
||||||
expect(logString.match(/moon-y/g)).toBe(null);
|
expect(logString.match(/moon-y/g)).toBe(null);
|
||||||
done();
|
done();
|
||||||
|
|||||||
@@ -9,35 +9,35 @@ const publicServerURLNaked = 'http://domain.com/';
|
|||||||
|
|
||||||
describe('batch', () => {
|
describe('batch', () => {
|
||||||
it('should return the proper url', () => {
|
it('should return the proper url', () => {
|
||||||
let internalURL = batch.makeBatchRoutingPathFunction(originalURL)('/parse/classes/Object');
|
const internalURL = batch.makeBatchRoutingPathFunction(originalURL)('/parse/classes/Object');
|
||||||
|
|
||||||
expect(internalURL).toEqual('/classes/Object');
|
expect(internalURL).toEqual('/classes/Object');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return the proper url same public/local endpoint', () => {
|
it('should return the proper url same public/local endpoint', () => {
|
||||||
let originalURL = '/parse/batch';
|
const originalURL = '/parse/batch';
|
||||||
let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURL)('/parse/classes/Object');
|
const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURL)('/parse/classes/Object');
|
||||||
|
|
||||||
expect(internalURL).toEqual('/classes/Object');
|
expect(internalURL).toEqual('/classes/Object');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return the proper url with different public/local mount', () => {
|
it('should return the proper url with different public/local mount', () => {
|
||||||
let originalURL = '/parse/batch';
|
const originalURL = '/parse/batch';
|
||||||
let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL1, publicServerURL)('/parse/classes/Object');
|
const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL1, publicServerURL)('/parse/classes/Object');
|
||||||
|
|
||||||
expect(internalURL).toEqual('/classes/Object');
|
expect(internalURL).toEqual('/classes/Object');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return the proper url with naked public', () => {
|
it('should return the proper url with naked public', () => {
|
||||||
let originalURL = '/batch';
|
const originalURL = '/batch';
|
||||||
let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURLNaked)('/classes/Object');
|
const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURLNaked)('/classes/Object');
|
||||||
|
|
||||||
expect(internalURL).toEqual('/classes/Object');
|
expect(internalURL).toEqual('/classes/Object');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return the proper url with naked local', () => {
|
it('should return the proper url with naked local', () => {
|
||||||
let originalURL = '/parse/batch';
|
const originalURL = '/parse/batch';
|
||||||
let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURLNaked, publicServerURL)('/parse/classes/Object');
|
const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURLNaked, publicServerURL)('/parse/classes/Object');
|
||||||
|
|
||||||
expect(internalURL).toEqual('/classes/Object');
|
expect(internalURL).toEqual('/classes/Object');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -114,7 +114,7 @@ if (process.env.PARSE_SERVER_TEST_CACHE === 'redis') {
|
|||||||
defaultConfiguration.cacheAdapter = new RedisCacheAdapter();
|
defaultConfiguration.cacheAdapter = new RedisCacheAdapter();
|
||||||
}
|
}
|
||||||
|
|
||||||
let openConnections = {};
|
const openConnections = {};
|
||||||
|
|
||||||
// Set up a default API server for testing with default configuration.
|
// Set up a default API server for testing with default configuration.
|
||||||
var app = express();
|
var app = express();
|
||||||
@@ -125,7 +125,7 @@ app.use('/1', () => {
|
|||||||
});
|
});
|
||||||
var server = app.listen(port);
|
var server = app.listen(port);
|
||||||
server.on('connection', connection => {
|
server.on('connection', connection => {
|
||||||
let key = `${connection.remoteAddress}:${connection.remotePort}`;
|
const key = `${connection.remoteAddress}:${connection.remotePort}`;
|
||||||
openConnections[key] = connection;
|
openConnections[key] = connection;
|
||||||
connection.on('close', () => { delete openConnections[key] });
|
connection.on('close', () => { delete openConnections[key] });
|
||||||
});
|
});
|
||||||
@@ -134,7 +134,7 @@ const reconfigureServer = changedConfiguration => {
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
server.close(() => {
|
server.close(() => {
|
||||||
try {
|
try {
|
||||||
let newConfiguration = Object.assign({}, defaultConfiguration, changedConfiguration, {
|
const newConfiguration = Object.assign({}, defaultConfiguration, changedConfiguration, {
|
||||||
__indexBuildCompletionCallbackForTests: indexBuildPromise => indexBuildPromise.then(resolve, reject)
|
__indexBuildCompletionCallbackForTests: indexBuildPromise => indexBuildPromise.then(resolve, reject)
|
||||||
});
|
});
|
||||||
cache.clear();
|
cache.clear();
|
||||||
@@ -147,7 +147,7 @@ const reconfigureServer = changedConfiguration => {
|
|||||||
});
|
});
|
||||||
server = app.listen(port);
|
server = app.listen(port);
|
||||||
server.on('connection', connection => {
|
server.on('connection', connection => {
|
||||||
let key = `${connection.remoteAddress}:${connection.remotePort}`;
|
const key = `${connection.remoteAddress}:${connection.remotePort}`;
|
||||||
openConnections[key] = connection;
|
openConnections[key] = connection;
|
||||||
connection.on('close', () => { delete openConnections[key] });
|
connection.on('close', () => { delete openConnections[key] });
|
||||||
});
|
});
|
||||||
@@ -203,7 +203,7 @@ beforeEach(done => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
afterEach(function(done) {
|
afterEach(function(done) {
|
||||||
let afterLogOut = () => {
|
const afterLogOut = () => {
|
||||||
if (Object.keys(openConnections).length > 0) {
|
if (Object.keys(openConnections).length > 0) {
|
||||||
fail('There were open connections to the server left after the test finished');
|
fail('There were open connections to the server left after the test finished');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -207,7 +207,7 @@ describe('server', () => {
|
|||||||
it('can create a parse-server v2', done => {
|
it('can create a parse-server v2', done => {
|
||||||
let objId;
|
let objId;
|
||||||
let server
|
let server
|
||||||
let parseServer = ParseServer.ParseServer(Object.assign({},
|
const parseServer = ParseServer.ParseServer(Object.assign({},
|
||||||
defaultConfiguration, {
|
defaultConfiguration, {
|
||||||
appId: "anOtherTestApp",
|
appId: "anOtherTestApp",
|
||||||
masterKey: "anOtherTestMasterKey",
|
masterKey: "anOtherTestMasterKey",
|
||||||
@@ -216,16 +216,16 @@ describe('server', () => {
|
|||||||
promise
|
promise
|
||||||
.then(() => {
|
.then(() => {
|
||||||
expect(Parse.applicationId).toEqual("anOtherTestApp");
|
expect(Parse.applicationId).toEqual("anOtherTestApp");
|
||||||
let app = express();
|
const app = express();
|
||||||
app.use('/parse', parseServer);
|
app.use('/parse', parseServer);
|
||||||
|
|
||||||
server = app.listen(12667);
|
server = app.listen(12667);
|
||||||
let obj = new Parse.Object("AnObject");
|
const obj = new Parse.Object("AnObject");
|
||||||
return obj.save()
|
return obj.save()
|
||||||
})
|
})
|
||||||
.then(obj => {
|
.then(obj => {
|
||||||
objId = obj.id;
|
objId = obj.id;
|
||||||
let q = new Parse.Query("AnObject");
|
const q = new Parse.Query("AnObject");
|
||||||
return q.first();
|
return q.first();
|
||||||
})
|
})
|
||||||
.then(obj => {
|
.then(obj => {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ var rest = require('../src/rest');
|
|||||||
var request = require('request');
|
var request = require('request');
|
||||||
|
|
||||||
var config = new Config('test');
|
var config = new Config('test');
|
||||||
let database = config.database;
|
const database = config.database;
|
||||||
|
|
||||||
describe('rest create', () => {
|
describe('rest create', () => {
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ describe('rest create', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('handles array, object, date', (done) => {
|
it('handles array, object, date', (done) => {
|
||||||
let now = new Date();
|
const now = new Date();
|
||||||
var obj = {
|
var obj = {
|
||||||
array: [1, 2, 3],
|
array: [1, 2, 3],
|
||||||
object: {foo: 'bar'},
|
object: {foo: 'bar'},
|
||||||
@@ -52,23 +52,23 @@ describe('rest create', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('handles object and subdocument', done => {
|
it('handles object and subdocument', done => {
|
||||||
let obj = { subdoc: {foo: 'bar', wu: 'tan'} };
|
const obj = { subdoc: {foo: 'bar', wu: 'tan'} };
|
||||||
rest.create(config, auth.nobody(config), 'MyClass', obj)
|
rest.create(config, auth.nobody(config), 'MyClass', obj)
|
||||||
.then(() => database.adapter.find('MyClass', { fields: {} }, {}, {}))
|
.then(() => database.adapter.find('MyClass', { fields: {} }, {}, {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let mob = results[0];
|
const mob = results[0];
|
||||||
expect(typeof mob.subdoc).toBe('object');
|
expect(typeof mob.subdoc).toBe('object');
|
||||||
expect(mob.subdoc.foo).toBe('bar');
|
expect(mob.subdoc.foo).toBe('bar');
|
||||||
expect(mob.subdoc.wu).toBe('tan');
|
expect(mob.subdoc.wu).toBe('tan');
|
||||||
expect(typeof mob.objectId).toEqual('string');
|
expect(typeof mob.objectId).toEqual('string');
|
||||||
let obj = { 'subdoc.wu': 'clan' };
|
const obj = { 'subdoc.wu': 'clan' };
|
||||||
return rest.update(config, auth.nobody(config), 'MyClass', mob.objectId, obj)
|
return rest.update(config, auth.nobody(config), 'MyClass', mob.objectId, obj)
|
||||||
})
|
})
|
||||||
.then(() => database.adapter.find('MyClass', { fields: {} }, {}, {}))
|
.then(() => database.adapter.find('MyClass', { fields: {} }, {}, {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let mob = results[0];
|
const mob = results[0];
|
||||||
expect(typeof mob.subdoc).toBe('object');
|
expect(typeof mob.subdoc).toBe('object');
|
||||||
expect(mob.subdoc.foo).toBe('bar');
|
expect(mob.subdoc.foo).toBe('bar');
|
||||||
expect(mob.subdoc.wu).toBe('clan');
|
expect(mob.subdoc.wu).toBe('clan');
|
||||||
@@ -267,7 +267,7 @@ describe('rest create', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('stores pointers', done => {
|
it('stores pointers', done => {
|
||||||
let obj = {
|
const obj = {
|
||||||
foo: 'bar',
|
foo: 'bar',
|
||||||
aPointer: {
|
aPointer: {
|
||||||
__type: 'Pointer',
|
__type: 'Pointer',
|
||||||
@@ -282,7 +282,7 @@ describe('rest create', () => {
|
|||||||
}}, {}, {}))
|
}}, {}, {}))
|
||||||
.then(results => {
|
.then(results => {
|
||||||
expect(results.length).toEqual(1);
|
expect(results.length).toEqual(1);
|
||||||
let output = results[0];
|
const output = results[0];
|
||||||
expect(typeof output.foo).toEqual('string');
|
expect(typeof output.foo).toEqual('string');
|
||||||
expect(typeof output._p_aPointer).toEqual('undefined');
|
expect(typeof output._p_aPointer).toEqual('undefined');
|
||||||
expect(output._p_aPointer).toBeUndefined();
|
expect(output._p_aPointer).toBeUndefined();
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ var hasAllPODobject = () => {
|
|||||||
return obj;
|
return obj;
|
||||||
};
|
};
|
||||||
|
|
||||||
let defaultClassLevelPermissions = {
|
const defaultClassLevelPermissions = {
|
||||||
find: {
|
find: {
|
||||||
'*': true
|
'*': true
|
||||||
},
|
},
|
||||||
@@ -1008,7 +1008,7 @@ describe('schemas', () => {
|
|||||||
|
|
||||||
it('should fail setting schema permissions with invalid key', done => {
|
it('should fail setting schema permissions with invalid key', done => {
|
||||||
|
|
||||||
let object = new Parse.Object('AClass');
|
const object = new Parse.Object('AClass');
|
||||||
object.save().then(() => {
|
object.save().then(() => {
|
||||||
request.put({
|
request.put({
|
||||||
url: 'http://localhost:8378/1/schemas/AClass',
|
url: 'http://localhost:8378/1/schemas/AClass',
|
||||||
@@ -1056,7 +1056,7 @@ describe('schemas', () => {
|
|||||||
}
|
}
|
||||||
}, (error) => {
|
}, (error) => {
|
||||||
expect(error).toEqual(null);
|
expect(error).toEqual(null);
|
||||||
let object = new Parse.Object('AClass');
|
const object = new Parse.Object('AClass');
|
||||||
object.set('hello', 'world');
|
object.set('hello', 'world');
|
||||||
return object.save().then(() => {
|
return object.save().then(() => {
|
||||||
fail('should not be able to add a field');
|
fail('should not be able to add a field');
|
||||||
@@ -1085,7 +1085,7 @@ describe('schemas', () => {
|
|||||||
}
|
}
|
||||||
}, (error) => {
|
}, (error) => {
|
||||||
expect(error).toEqual(null);
|
expect(error).toEqual(null);
|
||||||
let object = new Parse.Object('AClass');
|
const object = new Parse.Object('AClass');
|
||||||
object.set('hello', 'world');
|
object.set('hello', 'world');
|
||||||
return object.save().then(() => {
|
return object.save().then(() => {
|
||||||
done();
|
done();
|
||||||
@@ -1249,15 +1249,15 @@ describe('schemas', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
it('validate CLP 1', done => {
|
it('validate CLP 1', done => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('user');
|
user.setUsername('user');
|
||||||
user.setPassword('user');
|
user.setPassword('user');
|
||||||
|
|
||||||
let admin = new Parse.User();
|
const admin = new Parse.User();
|
||||||
admin.setUsername('admin');
|
admin.setUsername('admin');
|
||||||
admin.setPassword('admin');
|
admin.setPassword('admin');
|
||||||
|
|
||||||
let role = new Parse.Role('admin', new Parse.ACL());
|
const role = new Parse.Role('admin', new Parse.ACL());
|
||||||
|
|
||||||
setPermissionsOnClass('AClass', {
|
setPermissionsOnClass('AClass', {
|
||||||
'find': {
|
'find': {
|
||||||
@@ -1270,11 +1270,11 @@ describe('schemas', () => {
|
|||||||
return role.save(null, {useMasterKey: true});
|
return role.save(null, {useMasterKey: true});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user', 'user').then(() => {
|
return Parse.User.logIn('user', 'user').then(() => {
|
||||||
let obj = new Parse.Object('AClass');
|
const obj = new Parse.Object('AClass');
|
||||||
return obj.save(null, {useMasterKey: true});
|
return obj.save(null, {useMasterKey: true});
|
||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then(() => {
|
return query.find().then(() => {
|
||||||
fail('Use should hot be able to find!')
|
fail('Use should hot be able to find!')
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
@@ -1284,7 +1284,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('admin', 'admin');
|
return Parse.User.logIn('admin', 'admin');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
@@ -1296,15 +1296,15 @@ describe('schemas', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('validate CLP 2', done => {
|
it('validate CLP 2', done => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('user');
|
user.setUsername('user');
|
||||||
user.setPassword('user');
|
user.setPassword('user');
|
||||||
|
|
||||||
let admin = new Parse.User();
|
const admin = new Parse.User();
|
||||||
admin.setUsername('admin');
|
admin.setUsername('admin');
|
||||||
admin.setPassword('admin');
|
admin.setPassword('admin');
|
||||||
|
|
||||||
let role = new Parse.Role('admin', new Parse.ACL());
|
const role = new Parse.Role('admin', new Parse.ACL());
|
||||||
|
|
||||||
setPermissionsOnClass('AClass', {
|
setPermissionsOnClass('AClass', {
|
||||||
'find': {
|
'find': {
|
||||||
@@ -1317,11 +1317,11 @@ describe('schemas', () => {
|
|||||||
return role.save(null, {useMasterKey: true});
|
return role.save(null, {useMasterKey: true});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user', 'user').then(() => {
|
return Parse.User.logIn('user', 'user').then(() => {
|
||||||
let obj = new Parse.Object('AClass');
|
const obj = new Parse.Object('AClass');
|
||||||
return obj.save(null, {useMasterKey: true});
|
return obj.save(null, {useMasterKey: true});
|
||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then(() => {
|
return query.find().then(() => {
|
||||||
fail('User should not be able to find!')
|
fail('User should not be able to find!')
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
@@ -1337,7 +1337,7 @@ describe('schemas', () => {
|
|||||||
}
|
}
|
||||||
}, true);
|
}, true);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then((result) => {
|
return query.find().then((result) => {
|
||||||
expect(result.length).toBe(1);
|
expect(result.length).toBe(1);
|
||||||
}, () => {
|
}, () => {
|
||||||
@@ -1347,7 +1347,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('admin', 'admin');
|
return Parse.User.logIn('admin', 'admin');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
@@ -1359,15 +1359,15 @@ describe('schemas', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('validate CLP 3', done => {
|
it('validate CLP 3', done => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('user');
|
user.setUsername('user');
|
||||||
user.setPassword('user');
|
user.setPassword('user');
|
||||||
|
|
||||||
let admin = new Parse.User();
|
const admin = new Parse.User();
|
||||||
admin.setUsername('admin');
|
admin.setUsername('admin');
|
||||||
admin.setPassword('admin');
|
admin.setPassword('admin');
|
||||||
|
|
||||||
let role = new Parse.Role('admin', new Parse.ACL());
|
const role = new Parse.Role('admin', new Parse.ACL());
|
||||||
|
|
||||||
setPermissionsOnClass('AClass', {
|
setPermissionsOnClass('AClass', {
|
||||||
'find': {
|
'find': {
|
||||||
@@ -1380,11 +1380,11 @@ describe('schemas', () => {
|
|||||||
return role.save(null, {useMasterKey: true});
|
return role.save(null, {useMasterKey: true});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user', 'user').then(() => {
|
return Parse.User.logIn('user', 'user').then(() => {
|
||||||
let obj = new Parse.Object('AClass');
|
const obj = new Parse.Object('AClass');
|
||||||
return obj.save(null, {useMasterKey: true});
|
return obj.save(null, {useMasterKey: true});
|
||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then(() => {
|
return query.find().then(() => {
|
||||||
fail('User should not be able to find!')
|
fail('User should not be able to find!')
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
@@ -1395,7 +1395,7 @@ describe('schemas', () => {
|
|||||||
// delete all CLP
|
// delete all CLP
|
||||||
return setPermissionsOnClass('AClass', null, true);
|
return setPermissionsOnClass('AClass', null, true);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then((result) => {
|
return query.find().then((result) => {
|
||||||
expect(result.length).toBe(1);
|
expect(result.length).toBe(1);
|
||||||
}, () => {
|
}, () => {
|
||||||
@@ -1405,7 +1405,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('admin', 'admin');
|
return Parse.User.logIn('admin', 'admin');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
@@ -1417,15 +1417,15 @@ describe('schemas', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('validate CLP 4', done => {
|
it('validate CLP 4', done => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('user');
|
user.setUsername('user');
|
||||||
user.setPassword('user');
|
user.setPassword('user');
|
||||||
|
|
||||||
let admin = new Parse.User();
|
const admin = new Parse.User();
|
||||||
admin.setUsername('admin');
|
admin.setUsername('admin');
|
||||||
admin.setPassword('admin');
|
admin.setPassword('admin');
|
||||||
|
|
||||||
let role = new Parse.Role('admin', new Parse.ACL());
|
const role = new Parse.Role('admin', new Parse.ACL());
|
||||||
|
|
||||||
setPermissionsOnClass('AClass', {
|
setPermissionsOnClass('AClass', {
|
||||||
'find': {
|
'find': {
|
||||||
@@ -1438,11 +1438,11 @@ describe('schemas', () => {
|
|||||||
return role.save(null, {useMasterKey: true});
|
return role.save(null, {useMasterKey: true});
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user', 'user').then(() => {
|
return Parse.User.logIn('user', 'user').then(() => {
|
||||||
let obj = new Parse.Object('AClass');
|
const obj = new Parse.Object('AClass');
|
||||||
return obj.save(null, {useMasterKey: true});
|
return obj.save(null, {useMasterKey: true});
|
||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then(() => {
|
return query.find().then(() => {
|
||||||
fail('User should not be able to find!')
|
fail('User should not be able to find!')
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
@@ -1461,7 +1461,7 @@ describe('schemas', () => {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then(() => {
|
return query.find().then(() => {
|
||||||
fail('User should not be able to find!')
|
fail('User should not be able to find!')
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
@@ -1471,7 +1471,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('admin', 'admin');
|
return Parse.User.logIn('admin', 'admin');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(1);
|
expect(results.length).toBe(1);
|
||||||
@@ -1483,25 +1483,25 @@ describe('schemas', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('validate CLP 5', done => {
|
it('validate CLP 5', done => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('user');
|
user.setUsername('user');
|
||||||
user.setPassword('user');
|
user.setPassword('user');
|
||||||
|
|
||||||
let user2 = new Parse.User();
|
const user2 = new Parse.User();
|
||||||
user2.setUsername('user2');
|
user2.setUsername('user2');
|
||||||
user2.setPassword('user2');
|
user2.setPassword('user2');
|
||||||
let admin = new Parse.User();
|
const admin = new Parse.User();
|
||||||
admin.setUsername('admin');
|
admin.setUsername('admin');
|
||||||
admin.setPassword('admin');
|
admin.setPassword('admin');
|
||||||
|
|
||||||
let role = new Parse.Role('admin', new Parse.ACL());
|
const role = new Parse.Role('admin', new Parse.ACL());
|
||||||
|
|
||||||
Promise.resolve().then(() => {
|
Promise.resolve().then(() => {
|
||||||
return Parse.Object.saveAll([user, user2, admin, role], {useMasterKey: true});
|
return Parse.Object.saveAll([user, user2, admin, role], {useMasterKey: true});
|
||||||
}).then(()=> {
|
}).then(()=> {
|
||||||
role.relation('users').add(admin);
|
role.relation('users').add(admin);
|
||||||
return role.save(null, {useMasterKey: true}).then(() => {
|
return role.save(null, {useMasterKey: true}).then(() => {
|
||||||
let perm = {
|
const perm = {
|
||||||
find: {}
|
find: {}
|
||||||
};
|
};
|
||||||
// let the user find
|
// let the user find
|
||||||
@@ -1510,11 +1510,11 @@ describe('schemas', () => {
|
|||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user', 'user').then(() => {
|
return Parse.User.logIn('user', 'user').then(() => {
|
||||||
let obj = new Parse.Object('AClass');
|
const obj = new Parse.Object('AClass');
|
||||||
return obj.save();
|
return obj.save();
|
||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find().then((res) => {
|
return query.find().then((res) => {
|
||||||
expect(res.length).toEqual(1);
|
expect(res.length).toEqual(1);
|
||||||
}, () => {
|
}, () => {
|
||||||
@@ -1524,7 +1524,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('admin', 'admin');
|
return Parse.User.logIn('admin', 'admin');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
fail("should not be able to read!");
|
fail("should not be able to read!");
|
||||||
@@ -1535,7 +1535,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user2', 'user2');
|
return Parse.User.logIn('user2', 'user2');
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AClass');
|
const query = new Parse.Query('AClass');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
fail("should not be able to read!");
|
fail("should not be able to read!");
|
||||||
@@ -1557,13 +1557,13 @@ describe('schemas', () => {
|
|||||||
delete: {'*': true},
|
delete: {'*': true},
|
||||||
addField:{'*': true}
|
addField:{'*': true}
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
let anotherObject = new Parse.Object('AnotherObject');
|
const anotherObject = new Parse.Object('AnotherObject');
|
||||||
return obj.save({
|
return obj.save({
|
||||||
anotherObject
|
anotherObject
|
||||||
})
|
})
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AnObject');
|
const query = new Parse.Query('AnObject');
|
||||||
query.include('anotherObject');
|
query.include('anotherObject');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((res) => {
|
}).then((res) => {
|
||||||
@@ -1625,11 +1625,11 @@ describe('schemas', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("regression test for #1991", done => {
|
it("regression test for #1991", done => {
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
user.setUsername('user');
|
user.setUsername('user');
|
||||||
user.setPassword('user');
|
user.setPassword('user');
|
||||||
let role = new Parse.Role('admin', new Parse.ACL());
|
const role = new Parse.Role('admin', new Parse.ACL());
|
||||||
let obj = new Parse.Object('AnObject');
|
const obj = new Parse.Object('AnObject');
|
||||||
Parse.Object.saveAll([user, role]).then(() => {
|
Parse.Object.saveAll([user, role]).then(() => {
|
||||||
role.relation('users').add(user);
|
role.relation('users').add(user);
|
||||||
return role.save(null, {useMasterKey: true});
|
return role.save(null, {useMasterKey: true});
|
||||||
@@ -1648,7 +1648,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return obj.destroy();
|
return obj.destroy();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('AnObject');
|
const query = new Parse.Query('AnObject');
|
||||||
return query.find();
|
return query.find();
|
||||||
}).then((results) => {
|
}).then((results) => {
|
||||||
expect(results.length).toBe(0);
|
expect(results.length).toBe(0);
|
||||||
@@ -1661,8 +1661,8 @@ describe('schemas', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('regression test for #2246', done => {
|
it('regression test for #2246', done => {
|
||||||
let profile = new Parse.Object('UserProfile');
|
const profile = new Parse.Object('UserProfile');
|
||||||
let user = new Parse.User();
|
const user = new Parse.User();
|
||||||
function initialize() {
|
function initialize() {
|
||||||
return user.save({
|
return user.save({
|
||||||
username: 'user',
|
username: 'user',
|
||||||
@@ -1684,7 +1684,7 @@ describe('schemas', () => {
|
|||||||
}).then(() => {
|
}).then(() => {
|
||||||
return Parse.User.logIn('user', 'password')
|
return Parse.User.logIn('user', 'password')
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
let query = new Parse.Query('_User');
|
const query = new Parse.Query('_User');
|
||||||
query.include('userProfile');
|
query.include('userProfile');
|
||||||
return query.get(user.id);
|
return query.get(user.id);
|
||||||
}).then((user) => {
|
}).then((user) => {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export class AccountLockout {
|
|||||||
* set _failed_login_count to value
|
* set _failed_login_count to value
|
||||||
*/
|
*/
|
||||||
_setFailedLoginCount(value) {
|
_setFailedLoginCount(value) {
|
||||||
let query = {
|
const query = {
|
||||||
username: this._user.username
|
username: this._user.username
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -57,11 +57,11 @@ function authDataValidator(adapter, appIds, options) {
|
|||||||
|
|
||||||
module.exports = function(authOptions = {}, enableAnonymousUsers = true) {
|
module.exports = function(authOptions = {}, enableAnonymousUsers = true) {
|
||||||
let _enableAnonymousUsers = enableAnonymousUsers;
|
let _enableAnonymousUsers = enableAnonymousUsers;
|
||||||
let setEnableAnonymousUsers = function(enable) {
|
const setEnableAnonymousUsers = function(enable) {
|
||||||
_enableAnonymousUsers = enable;
|
_enableAnonymousUsers = enable;
|
||||||
}
|
}
|
||||||
// To handle the test cases on configuration
|
// To handle the test cases on configuration
|
||||||
let getValidatorForProvider = function(provider) {
|
const getValidatorForProvider = function(provider) {
|
||||||
|
|
||||||
if (provider === 'anonymous' && !_enableAnonymousUsers) {
|
if (provider === 'anonymous' && !_enableAnonymousUsers) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ function validateAppId() {
|
|||||||
|
|
||||||
function handleMultipleConfigurations(authData, options) {
|
function handleMultipleConfigurations(authData, options) {
|
||||||
if (Array.isArray(options)) {
|
if (Array.isArray(options)) {
|
||||||
let consumer_key = authData.consumer_key;
|
const consumer_key = authData.consumer_key;
|
||||||
if (!consumer_key) {
|
if (!consumer_key) {
|
||||||
logger.error('Twitter Auth', 'Multiple twitter configurations are available, by no consumer_key was sent by the client.');
|
logger.error('Twitter Auth', 'Multiple twitter configurations are available, by no consumer_key was sent by the client.');
|
||||||
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Twitter auth is invalid for this user.');
|
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Twitter auth is invalid for this user.');
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export class InMemoryCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get(key) {
|
get(key) {
|
||||||
let record = this.cache[key];
|
const record = this.cache[key];
|
||||||
if (record == null) {
|
if (record == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ export class InMemoryCacheAdapter {
|
|||||||
|
|
||||||
get(key) {
|
get(key) {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
let record = this.cache.get(key);
|
const record = this.cache.get(key);
|
||||||
if (record == null) {
|
if (record == null) {
|
||||||
return resolve(null);
|
return resolve(null);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ export class GridStoreAdapter extends FilesAdapter {
|
|||||||
// Returns a promise
|
// Returns a promise
|
||||||
createFile(filename: string, data) {
|
createFile(filename: string, data) {
|
||||||
return this._connect().then(database => {
|
return this._connect().then(database => {
|
||||||
let gridStore = new GridStore(database, filename, 'w');
|
const gridStore = new GridStore(database, filename, 'w');
|
||||||
return gridStore.open();
|
return gridStore.open();
|
||||||
}).then(gridStore => {
|
}).then(gridStore => {
|
||||||
return gridStore.write(data);
|
return gridStore.write(data);
|
||||||
@@ -41,7 +41,7 @@ export class GridStoreAdapter extends FilesAdapter {
|
|||||||
|
|
||||||
deleteFile(filename: string) {
|
deleteFile(filename: string) {
|
||||||
return this._connect().then(database => {
|
return this._connect().then(database => {
|
||||||
let gridStore = new GridStore(database, filename, 'r');
|
const gridStore = new GridStore(database, filename, 'r');
|
||||||
return gridStore.open();
|
return gridStore.open();
|
||||||
}).then((gridStore) => {
|
}).then((gridStore) => {
|
||||||
return gridStore.unlink();
|
return gridStore.unlink();
|
||||||
@@ -54,7 +54,7 @@ export class GridStoreAdapter extends FilesAdapter {
|
|||||||
return this._connect().then(database => {
|
return this._connect().then(database => {
|
||||||
return GridStore.exist(database, filename)
|
return GridStore.exist(database, filename)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let gridStore = new GridStore(database, filename, 'r');
|
const gridStore = new GridStore(database, filename, 'r');
|
||||||
return gridStore.open();
|
return gridStore.open();
|
||||||
});
|
});
|
||||||
}).then(gridStore => {
|
}).then(gridStore => {
|
||||||
@@ -69,7 +69,7 @@ export class GridStoreAdapter extends FilesAdapter {
|
|||||||
getFileStream(filename: string) {
|
getFileStream(filename: string) {
|
||||||
return this._connect().then(database => {
|
return this._connect().then(database => {
|
||||||
return GridStore.exist(database, filename).then(() => {
|
return GridStore.exist(database, filename).then(() => {
|
||||||
let gridStore = new GridStore(database, filename, 'r');
|
const gridStore = new GridStore(database, filename, 'r');
|
||||||
return gridStore.open();
|
return gridStore.open();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ const logger = new winston.Logger();
|
|||||||
const additionalTransports = [];
|
const additionalTransports = [];
|
||||||
|
|
||||||
function updateTransports(options) {
|
function updateTransports(options) {
|
||||||
let transports = Object.assign({}, logger.transports);
|
const transports = Object.assign({}, logger.transports);
|
||||||
if (options) {
|
if (options) {
|
||||||
let silent = options.silent;
|
const silent = options.silent;
|
||||||
delete options.silent;
|
delete options.silent;
|
||||||
if (_.isNull(options.dirname)) {
|
if (_.isNull(options.dirname)) {
|
||||||
delete transports['parse-server'];
|
delete transports['parse-server'];
|
||||||
@@ -84,8 +84,8 @@ export function addTransport(transport) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function removeTransport(transport) {
|
export function removeTransport(transport) {
|
||||||
let transportName = typeof transport == 'string' ? transport : transport.name;
|
const transportName = typeof transport == 'string' ? transport : transport.name;
|
||||||
let transports = Object.assign({}, logger.transports);
|
const transports = Object.assign({}, logger.transports);
|
||||||
delete transports[transportName];
|
delete transports[transportName];
|
||||||
logger.configure({
|
logger.configure({
|
||||||
transports: _.values(transports)
|
transports: _.values(transports)
|
||||||
|
|||||||
@@ -28,11 +28,11 @@ export class WinstonLoggerAdapter extends LoggerAdapter {
|
|||||||
options = {};
|
options = {};
|
||||||
}
|
}
|
||||||
// defaults to 7 days prior
|
// defaults to 7 days prior
|
||||||
let from = options.from || new Date(Date.now() - (7 * MILLISECONDS_IN_A_DAY));
|
const from = options.from || new Date(Date.now() - (7 * MILLISECONDS_IN_A_DAY));
|
||||||
let until = options.until || new Date();
|
const until = options.until || new Date();
|
||||||
let limit = options.size || 10;
|
const limit = options.size || 10;
|
||||||
let order = options.order || 'desc';
|
const order = options.order || 'desc';
|
||||||
let level = options.level || 'info';
|
const level = options.level || 'info';
|
||||||
|
|
||||||
const queryOptions = {
|
const queryOptions = {
|
||||||
from,
|
from,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import events from 'events';
|
import events from 'events';
|
||||||
|
|
||||||
let emitter = new events.EventEmitter();
|
const emitter = new events.EventEmitter();
|
||||||
|
|
||||||
class Publisher {
|
class Publisher {
|
||||||
emitter: any;
|
emitter: any;
|
||||||
@@ -25,7 +25,7 @@ class Subscriber extends events.EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
subscribe(channel: string): void {
|
subscribe(channel: string): void {
|
||||||
let handler = (message) => {
|
const handler = (message) => {
|
||||||
this.emit('message', channel, message);
|
this.emit('message', channel, message);
|
||||||
}
|
}
|
||||||
this.subscriptions.set(channel, handler);
|
this.subscriptions.set(channel, handler);
|
||||||
@@ -49,7 +49,7 @@ function createSubscriber(): any {
|
|||||||
return new Subscriber(emitter);
|
return new Subscriber(emitter);
|
||||||
}
|
}
|
||||||
|
|
||||||
let EventEmitterPubSub = {
|
const EventEmitterPubSub = {
|
||||||
createPublisher,
|
createPublisher,
|
||||||
createSubscriber
|
createSubscriber
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
let mongodb = require('mongodb');
|
const mongodb = require('mongodb');
|
||||||
let Collection = mongodb.Collection;
|
const Collection = mongodb.Collection;
|
||||||
|
|
||||||
export default class MongoCollection {
|
export default class MongoCollection {
|
||||||
_mongoCollection:Collection;
|
_mongoCollection:Collection;
|
||||||
@@ -21,7 +21,7 @@ export default class MongoCollection {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
// Figure out what key needs an index
|
// Figure out what key needs an index
|
||||||
let key = error.message.match(/field=([A-Za-z_0-9]+) /)[1];
|
const key = error.message.match(/field=([A-Za-z_0-9]+) /)[1];
|
||||||
if (!key) {
|
if (!key) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,7 @@ export default class MongoCollection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
count(query, { skip, limit, sort, maxTimeMS } = {}) {
|
count(query, { skip, limit, sort, maxTimeMS } = {}) {
|
||||||
let countOperation = this._mongoCollection.count(query, { skip, limit, sort, maxTimeMS });
|
const countOperation = this._mongoCollection.count(query, { skip, limit, sort, maxTimeMS });
|
||||||
|
|
||||||
return countOperation;
|
return countOperation;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ function mongoSchemaToParseSchema(mongoSchema) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function _mongoSchemaQueryFromNameQuery(name: string, query) {
|
function _mongoSchemaQueryFromNameQuery(name: string, query) {
|
||||||
let object = { _id: name };
|
const object = { _id: name };
|
||||||
if (query) {
|
if (query) {
|
||||||
Object.keys(query).forEach(key => {
|
Object.keys(query).forEach(key => {
|
||||||
object[key] = query[key];
|
object[key] = query[key];
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ import Parse from 'parse/node';
|
|||||||
import _ from 'lodash';
|
import _ from 'lodash';
|
||||||
import defaults from '../../../defaults';
|
import defaults from '../../../defaults';
|
||||||
|
|
||||||
let mongodb = require('mongodb');
|
const mongodb = require('mongodb');
|
||||||
let MongoClient = mongodb.MongoClient;
|
const MongoClient = mongodb.MongoClient;
|
||||||
|
|
||||||
const MongoSchemaCollectionName = '_SCHEMA';
|
const MongoSchemaCollectionName = '_SCHEMA';
|
||||||
|
|
||||||
@@ -53,14 +53,14 @@ const convertParseSchemaToMongoSchema = ({...schema}) => {
|
|||||||
// Returns { code, error } if invalid, or { result }, an object
|
// Returns { code, error } if invalid, or { result }, an object
|
||||||
// suitable for inserting into _SCHEMA collection, otherwise.
|
// suitable for inserting into _SCHEMA collection, otherwise.
|
||||||
const mongoSchemaFromFieldsAndClassNameAndCLP = (fields, className, classLevelPermissions) => {
|
const mongoSchemaFromFieldsAndClassNameAndCLP = (fields, className, classLevelPermissions) => {
|
||||||
let mongoObject = {
|
const mongoObject = {
|
||||||
_id: className,
|
_id: className,
|
||||||
objectId: 'string',
|
objectId: 'string',
|
||||||
updatedAt: 'string',
|
updatedAt: 'string',
|
||||||
createdAt: 'string'
|
createdAt: 'string'
|
||||||
};
|
};
|
||||||
|
|
||||||
for (let fieldName in fields) {
|
for (const fieldName in fields) {
|
||||||
mongoObject[fieldName] = MongoSchemaCollection.parseFieldTypeToMongoFieldType(fields[fieldName]);
|
mongoObject[fieldName] = MongoSchemaCollection.parseFieldTypeToMongoFieldType(fields[fieldName]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,7 +157,7 @@ export class MongoStorageAdapter {
|
|||||||
|
|
||||||
createClass(className, schema) {
|
createClass(className, schema) {
|
||||||
schema = convertParseSchemaToMongoSchema(schema);
|
schema = convertParseSchemaToMongoSchema(schema);
|
||||||
let mongoObject = mongoSchemaFromFieldsAndClassNameAndCLP(schema.fields, className, schema.classLevelPermissions);
|
const mongoObject = mongoSchemaFromFieldsAndClassNameAndCLP(schema.fields, className, schema.classLevelPermissions);
|
||||||
mongoObject._id = className;
|
mongoObject._id = className;
|
||||||
return this._schemaCollection()
|
return this._schemaCollection()
|
||||||
.then(schemaCollection => schemaCollection._collection.insertOne(mongoObject))
|
.then(schemaCollection => schemaCollection._collection.insertOne(mongoObject))
|
||||||
@@ -282,7 +282,7 @@ export class MongoStorageAdapter {
|
|||||||
schema = convertParseSchemaToMongoSchema(schema);
|
schema = convertParseSchemaToMongoSchema(schema);
|
||||||
return this._adaptiveCollection(className)
|
return this._adaptiveCollection(className)
|
||||||
.then(collection => {
|
.then(collection => {
|
||||||
let mongoWhere = transformWhere(className, query, schema);
|
const mongoWhere = transformWhere(className, query, schema);
|
||||||
return collection.deleteMany(mongoWhere)
|
return collection.deleteMany(mongoWhere)
|
||||||
})
|
})
|
||||||
.then(({ result }) => {
|
.then(({ result }) => {
|
||||||
@@ -327,9 +327,9 @@ export class MongoStorageAdapter {
|
|||||||
// Executes a find. Accepts: className, query in Parse format, and { skip, limit, sort }.
|
// Executes a find. Accepts: className, query in Parse format, and { skip, limit, sort }.
|
||||||
find(className, schema, query, { skip, limit, sort, keys }) {
|
find(className, schema, query, { skip, limit, sort, keys }) {
|
||||||
schema = convertParseSchemaToMongoSchema(schema);
|
schema = convertParseSchemaToMongoSchema(schema);
|
||||||
let mongoWhere = transformWhere(className, query, schema);
|
const mongoWhere = transformWhere(className, query, schema);
|
||||||
let mongoSort = _.mapKeys(sort, (value, fieldName) => transformKey(className, fieldName, schema));
|
const mongoSort = _.mapKeys(sort, (value, fieldName) => transformKey(className, fieldName, schema));
|
||||||
let mongoKeys = _.reduce(keys, (memo, key) => {
|
const mongoKeys = _.reduce(keys, (memo, key) => {
|
||||||
memo[transformKey(className, key, schema)] = 1;
|
memo[transformKey(className, key, schema)] = 1;
|
||||||
return memo;
|
return memo;
|
||||||
}, {});
|
}, {});
|
||||||
@@ -351,8 +351,8 @@ export class MongoStorageAdapter {
|
|||||||
// which is why we use sparse indexes.
|
// which is why we use sparse indexes.
|
||||||
ensureUniqueness(className, schema, fieldNames) {
|
ensureUniqueness(className, schema, fieldNames) {
|
||||||
schema = convertParseSchemaToMongoSchema(schema);
|
schema = convertParseSchemaToMongoSchema(schema);
|
||||||
let indexCreationRequest = {};
|
const indexCreationRequest = {};
|
||||||
let mongoFieldNames = fieldNames.map(fieldName => transformKey(className, fieldName, schema));
|
const mongoFieldNames = fieldNames.map(fieldName => transformKey(className, fieldName, schema));
|
||||||
mongoFieldNames.forEach(fieldName => {
|
mongoFieldNames.forEach(fieldName => {
|
||||||
indexCreationRequest[fieldName] = 1;
|
indexCreationRequest[fieldName] = 1;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -243,9 +243,9 @@ function transformQueryKeyValue(className, key, value, schema) {
|
|||||||
// restWhere is the "where" clause in REST API form.
|
// restWhere is the "where" clause in REST API form.
|
||||||
// Returns the mongo form of the query.
|
// Returns the mongo form of the query.
|
||||||
function transformWhere(className, restWhere, schema) {
|
function transformWhere(className, restWhere, schema) {
|
||||||
let mongoWhere = {};
|
const mongoWhere = {};
|
||||||
for (let restKey in restWhere) {
|
for (const restKey in restWhere) {
|
||||||
let out = transformQueryKeyValue(className, restKey, restWhere[restKey], schema);
|
const out = transformQueryKeyValue(className, restKey, restWhere[restKey], schema);
|
||||||
mongoWhere[out.key] = out.value;
|
mongoWhere[out.key] = out.value;
|
||||||
}
|
}
|
||||||
return mongoWhere;
|
return mongoWhere;
|
||||||
@@ -331,12 +331,12 @@ const parseObjectKeyValueToMongoObjectKeyValue = (restKey, restValue, schema) =>
|
|||||||
|
|
||||||
const parseObjectToMongoObjectForCreate = (className, restCreate, schema) => {
|
const parseObjectToMongoObjectForCreate = (className, restCreate, schema) => {
|
||||||
restCreate = addLegacyACL(restCreate);
|
restCreate = addLegacyACL(restCreate);
|
||||||
let mongoCreate = {}
|
const mongoCreate = {}
|
||||||
for (let restKey in restCreate) {
|
for (const restKey in restCreate) {
|
||||||
if (restCreate[restKey] && restCreate[restKey].__type === 'Relation') {
|
if (restCreate[restKey] && restCreate[restKey].__type === 'Relation') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let { key, value } = parseObjectKeyValueToMongoObjectKeyValue(
|
const { key, value } = parseObjectKeyValueToMongoObjectKeyValue(
|
||||||
restKey,
|
restKey,
|
||||||
restCreate[restKey],
|
restCreate[restKey],
|
||||||
schema
|
schema
|
||||||
@@ -361,8 +361,8 @@ const parseObjectToMongoObjectForCreate = (className, restCreate, schema) => {
|
|||||||
|
|
||||||
// Main exposed method to help update old objects.
|
// Main exposed method to help update old objects.
|
||||||
const transformUpdate = (className, restUpdate, parseFormatSchema) => {
|
const transformUpdate = (className, restUpdate, parseFormatSchema) => {
|
||||||
let mongoUpdate = {};
|
const mongoUpdate = {};
|
||||||
let acl = addLegacyACL(restUpdate);
|
const acl = addLegacyACL(restUpdate);
|
||||||
if (acl._rperm || acl._wperm || acl._acl) {
|
if (acl._rperm || acl._wperm || acl._acl) {
|
||||||
mongoUpdate.$set = {};
|
mongoUpdate.$set = {};
|
||||||
if (acl._rperm) {
|
if (acl._rperm) {
|
||||||
@@ -398,8 +398,8 @@ const transformUpdate = (className, restUpdate, parseFormatSchema) => {
|
|||||||
|
|
||||||
// Add the legacy _acl format.
|
// Add the legacy _acl format.
|
||||||
const addLegacyACL = restObject => {
|
const addLegacyACL = restObject => {
|
||||||
let restObjectCopy = {...restObject};
|
const restObjectCopy = {...restObject};
|
||||||
let _acl = {};
|
const _acl = {};
|
||||||
|
|
||||||
if (restObject._wperm) {
|
if (restObject._wperm) {
|
||||||
restObject._wperm.forEach(entry => {
|
restObject._wperm.forEach(entry => {
|
||||||
@@ -532,12 +532,12 @@ function transformConstraint(constraint, inArray) {
|
|||||||
|
|
||||||
case '$in':
|
case '$in':
|
||||||
case '$nin': {
|
case '$nin': {
|
||||||
let arr = constraint[key];
|
const arr = constraint[key];
|
||||||
if (!(arr instanceof Array)) {
|
if (!(arr instanceof Array)) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad ' + key + ' value');
|
throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad ' + key + ' value');
|
||||||
}
|
}
|
||||||
answer[key] = arr.map(value => {
|
answer[key] = arr.map(value => {
|
||||||
let result = inArray ? transformInteriorAtom(value) : transformTopLevelAtom(value);
|
const result = inArray ? transformInteriorAtom(value) : transformTopLevelAtom(value);
|
||||||
if (result === CannotTransform) {
|
if (result === CannotTransform) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad atom: ${value}`);
|
throw new Parse.Error(Parse.Error.INVALID_JSON, `bad atom: ${value}`);
|
||||||
}
|
}
|
||||||
@@ -546,7 +546,7 @@ function transformConstraint(constraint, inArray) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case '$all': {
|
case '$all': {
|
||||||
let arr = constraint[key];
|
const arr = constraint[key];
|
||||||
if (!(arr instanceof Array)) {
|
if (!(arr instanceof Array)) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_JSON,
|
throw new Parse.Error(Parse.Error.INVALID_JSON,
|
||||||
'bad ' + key + ' value');
|
'bad ' + key + ' value');
|
||||||
@@ -761,7 +761,7 @@ const mongoObjectToParseObject = (className, mongoObject, schema) => {
|
|||||||
return BytesCoder.databaseToJSON(mongoObject);
|
return BytesCoder.databaseToJSON(mongoObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
let restObject = {};
|
const restObject = {};
|
||||||
if (mongoObject._rperm || mongoObject._wperm) {
|
if (mongoObject._rperm || mongoObject._wperm) {
|
||||||
restObject._rperm = mongoObject._rperm || [];
|
restObject._rperm = mongoObject._rperm || [];
|
||||||
restObject._wperm = mongoObject._wperm || [];
|
restObject._wperm = mongoObject._wperm || [];
|
||||||
@@ -861,7 +861,7 @@ const mongoObjectToParseObject = (className, mongoObject, schema) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const relationFieldNames = Object.keys(schema.fields).filter(fieldName => schema.fields[fieldName].type === 'Relation');
|
const relationFieldNames = Object.keys(schema.fields).filter(fieldName => schema.fields[fieldName].type === 'Relation');
|
||||||
let relationFields = {};
|
const relationFields = {};
|
||||||
relationFieldNames.forEach(relationFieldName => {
|
relationFieldNames.forEach(relationFieldName => {
|
||||||
relationFields[relationFieldName] = {
|
relationFields[relationFieldName] = {
|
||||||
__type: 'Relation',
|
__type: 'Relation',
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ const pgp = require('pg-promise')();
|
|||||||
const parser = require('./PostgresConfigParser');
|
const parser = require('./PostgresConfigParser');
|
||||||
|
|
||||||
export function createClient(uri, databaseOptions) {
|
export function createClient(uri, databaseOptions) {
|
||||||
let client;
|
|
||||||
let dbOptions = {};
|
let dbOptions = {};
|
||||||
databaseOptions = databaseOptions || {};
|
databaseOptions = databaseOptions || {};
|
||||||
|
|
||||||
@@ -14,7 +13,7 @@ export function createClient(uri, databaseOptions) {
|
|||||||
dbOptions[key] = databaseOptions[key];
|
dbOptions[key] = databaseOptions[key];
|
||||||
}
|
}
|
||||||
|
|
||||||
client = pgp(dbOptions);
|
const client = pgp(dbOptions);
|
||||||
|
|
||||||
if (dbOptions.pgOptions) {
|
if (dbOptions.pgOptions) {
|
||||||
for (const key in dbOptions.pgOptions) {
|
for (const key in dbOptions.pgOptions) {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ const logger = require('../../../logger');
|
|||||||
const debug = function(){
|
const debug = function(){
|
||||||
let args = [...arguments];
|
let args = [...arguments];
|
||||||
args = ['PG: '+arguments[0]].concat(args.slice(1, args.length));
|
args = ['PG: '+arguments[0]].concat(args.slice(1, args.length));
|
||||||
let log = logger.getLogger();
|
const log = logger.getLogger();
|
||||||
log.debug.apply(log, args);
|
log.debug.apply(log, args);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,8 +116,8 @@ const toPostgresSchema = (schema) => {
|
|||||||
const handleDotFields = (object) => {
|
const handleDotFields = (object) => {
|
||||||
Object.keys(object).forEach(fieldName => {
|
Object.keys(object).forEach(fieldName => {
|
||||||
if (fieldName.indexOf('.') > -1) {
|
if (fieldName.indexOf('.') > -1) {
|
||||||
let components = fieldName.split('.');
|
const components = fieldName.split('.');
|
||||||
let first = components.shift();
|
const first = components.shift();
|
||||||
object[first] = object[first] || {};
|
object[first] = object[first] || {};
|
||||||
let currentObj = object[first];
|
let currentObj = object[first];
|
||||||
let next;
|
let next;
|
||||||
@@ -156,7 +156,7 @@ const validateKeys = (object) => {
|
|||||||
|
|
||||||
// Returns the list of join tables on a schema
|
// Returns the list of join tables on a schema
|
||||||
const joinTablesForSchema = (schema) => {
|
const joinTablesForSchema = (schema) => {
|
||||||
let list = [];
|
const list = [];
|
||||||
if (schema) {
|
if (schema) {
|
||||||
Object.keys(schema.fields).forEach((field) => {
|
Object.keys(schema.fields).forEach((field) => {
|
||||||
if (schema.fields[field].type === 'Relation') {
|
if (schema.fields[field].type === 'Relation') {
|
||||||
@@ -168,17 +168,17 @@ const joinTablesForSchema = (schema) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const buildWhereClause = ({ schema, query, index }) => {
|
const buildWhereClause = ({ schema, query, index }) => {
|
||||||
let patterns = [];
|
const patterns = [];
|
||||||
let values = [];
|
let values = [];
|
||||||
let sorts = [];
|
const sorts = [];
|
||||||
|
|
||||||
schema = toPostgresSchema(schema);
|
schema = toPostgresSchema(schema);
|
||||||
for (let fieldName in query) {
|
for (const fieldName in query) {
|
||||||
let isArrayField = schema.fields
|
const isArrayField = schema.fields
|
||||||
&& schema.fields[fieldName]
|
&& schema.fields[fieldName]
|
||||||
&& schema.fields[fieldName].type === 'Array';
|
&& schema.fields[fieldName].type === 'Array';
|
||||||
let initialPatternsLength = patterns.length;
|
const initialPatternsLength = patterns.length;
|
||||||
let fieldValue = query[fieldName];
|
const fieldValue = query[fieldName];
|
||||||
|
|
||||||
// nothingin the schema, it's gonna blow up
|
// nothingin the schema, it's gonna blow up
|
||||||
if (!schema.fields[fieldName]) {
|
if (!schema.fields[fieldName]) {
|
||||||
@@ -189,7 +189,7 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (fieldName.indexOf('.') >= 0) {
|
if (fieldName.indexOf('.') >= 0) {
|
||||||
let components = fieldName.split('.').map((cmpt, index) => {
|
const components = fieldName.split('.').map((cmpt, index) => {
|
||||||
if (index === 0) {
|
if (index === 0) {
|
||||||
return `"${cmpt}"`;
|
return `"${cmpt}"`;
|
||||||
}
|
}
|
||||||
@@ -211,17 +211,17 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
values.push(fieldName, fieldValue);
|
values.push(fieldName, fieldValue);
|
||||||
index += 2;
|
index += 2;
|
||||||
} else if (fieldName === '$or' || fieldName === '$and') {
|
} else if (fieldName === '$or' || fieldName === '$and') {
|
||||||
let clauses = [];
|
const clauses = [];
|
||||||
let clauseValues = [];
|
const clauseValues = [];
|
||||||
fieldValue.forEach((subQuery) => {
|
fieldValue.forEach((subQuery) => {
|
||||||
let clause = buildWhereClause({ schema, query: subQuery, index });
|
const clause = buildWhereClause({ schema, query: subQuery, index });
|
||||||
if (clause.pattern.length > 0) {
|
if (clause.pattern.length > 0) {
|
||||||
clauses.push(clause.pattern);
|
clauses.push(clause.pattern);
|
||||||
clauseValues.push(...clause.values);
|
clauseValues.push(...clause.values);
|
||||||
index += clause.values.length;
|
index += clause.values.length;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let orOrAnd = fieldName === '$or' ? ' OR ' : ' AND ';
|
const orOrAnd = fieldName === '$or' ? ' OR ' : ' AND ';
|
||||||
patterns.push(`(${clauses.join(orOrAnd)})`);
|
patterns.push(`(${clauses.join(orOrAnd)})`);
|
||||||
values.push(...clauseValues);
|
values.push(...clauseValues);
|
||||||
}
|
}
|
||||||
@@ -254,7 +254,7 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
isArrayField &&
|
isArrayField &&
|
||||||
schema.fields[fieldName].contents &&
|
schema.fields[fieldName].contents &&
|
||||||
schema.fields[fieldName].contents.type === 'String') {
|
schema.fields[fieldName].contents.type === 'String') {
|
||||||
let inPatterns = [];
|
const inPatterns = [];
|
||||||
let allowNull = false;
|
let allowNull = false;
|
||||||
values.push(fieldName);
|
values.push(fieldName);
|
||||||
fieldValue.$in.forEach((listElem, listIndex) => {
|
fieldValue.$in.forEach((listElem, listIndex) => {
|
||||||
@@ -274,13 +274,13 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
} else if (isInOrNin) {
|
} else if (isInOrNin) {
|
||||||
var createConstraint = (baseArray, notIn) => {
|
var createConstraint = (baseArray, notIn) => {
|
||||||
if (baseArray.length > 0) {
|
if (baseArray.length > 0) {
|
||||||
let not = notIn ? ' NOT ' : '';
|
const not = notIn ? ' NOT ' : '';
|
||||||
if (isArrayField) {
|
if (isArrayField) {
|
||||||
patterns.push(`${not} array_contains($${index}:name, $${index+1})`);
|
patterns.push(`${not} array_contains($${index}:name, $${index+1})`);
|
||||||
values.push(fieldName, JSON.stringify(baseArray));
|
values.push(fieldName, JSON.stringify(baseArray));
|
||||||
index += 2;
|
index += 2;
|
||||||
} else {
|
} else {
|
||||||
let inPatterns = [];
|
const inPatterns = [];
|
||||||
values.push(fieldName);
|
values.push(fieldName);
|
||||||
baseArray.forEach((listElem, listIndex) => {
|
baseArray.forEach((listElem, listIndex) => {
|
||||||
values.push(listElem);
|
values.push(listElem);
|
||||||
@@ -320,9 +320,9 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (fieldValue.$nearSphere) {
|
if (fieldValue.$nearSphere) {
|
||||||
let point = fieldValue.$nearSphere;
|
const point = fieldValue.$nearSphere;
|
||||||
let distance = fieldValue.$maxDistance;
|
const distance = fieldValue.$maxDistance;
|
||||||
let distanceInKM = distance*6371*1000;
|
const distanceInKM = distance*6371*1000;
|
||||||
patterns.push(`ST_distance_sphere($${index}:name::geometry, POINT($${index+1}, $${index+2})::geometry) <= $${index+3}`);
|
patterns.push(`ST_distance_sphere($${index}:name::geometry, POINT($${index+1}, $${index+2})::geometry) <= $${index+3}`);
|
||||||
sorts.push(`ST_distance_sphere($${index}:name::geometry, POINT($${index+1}, $${index+2})::geometry) ASC`)
|
sorts.push(`ST_distance_sphere($${index}:name::geometry, POINT($${index+1}, $${index+2})::geometry) ASC`)
|
||||||
values.push(fieldName, point.longitude, point.latitude, distanceInKM);
|
values.push(fieldName, point.longitude, point.latitude, distanceInKM);
|
||||||
@@ -330,11 +330,11 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (fieldValue.$within && fieldValue.$within.$box) {
|
if (fieldValue.$within && fieldValue.$within.$box) {
|
||||||
let box = fieldValue.$within.$box;
|
const box = fieldValue.$within.$box;
|
||||||
let left = box[0].longitude;
|
const left = box[0].longitude;
|
||||||
let bottom = box[0].latitude;
|
const bottom = box[0].latitude;
|
||||||
let right = box[1].longitude;
|
const right = box[1].longitude;
|
||||||
let top = box[1].latitude;
|
const top = box[1].latitude;
|
||||||
|
|
||||||
patterns.push(`$${index}:name::point <@ $${index+1}::box`);
|
patterns.push(`$${index}:name::point <@ $${index+1}::box`);
|
||||||
values.push(fieldName, `((${left}, ${bottom}), (${right}, ${top}))`);
|
values.push(fieldName, `((${left}, ${bottom}), (${right}, ${top}))`);
|
||||||
@@ -344,7 +344,7 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
if (fieldValue.$regex) {
|
if (fieldValue.$regex) {
|
||||||
let regex = fieldValue.$regex;
|
let regex = fieldValue.$regex;
|
||||||
let operator = '~';
|
let operator = '~';
|
||||||
let opts = fieldValue.$options;
|
const opts = fieldValue.$options;
|
||||||
if (opts) {
|
if (opts) {
|
||||||
if (opts.indexOf('i') >= 0) {
|
if (opts.indexOf('i') >= 0) {
|
||||||
operator = '~*';
|
operator = '~*';
|
||||||
@@ -381,7 +381,7 @@ const buildWhereClause = ({ schema, query, index }) => {
|
|||||||
|
|
||||||
Object.keys(ParseToPosgresComparator).forEach(cmp => {
|
Object.keys(ParseToPosgresComparator).forEach(cmp => {
|
||||||
if (fieldValue[cmp]) {
|
if (fieldValue[cmp]) {
|
||||||
let pgComparator = ParseToPosgresComparator[cmp];
|
const pgComparator = ParseToPosgresComparator[cmp];
|
||||||
patterns.push(`$${index}:name ${pgComparator} $${index + 1}`);
|
patterns.push(`$${index}:name ${pgComparator} $${index + 1}`);
|
||||||
values.push(fieldName, toPostgresValue(fieldValue[cmp]));
|
values.push(fieldName, toPostgresValue(fieldValue[cmp]));
|
||||||
index += 2;
|
index += 2;
|
||||||
@@ -461,9 +461,9 @@ export class PostgresStorageAdapter {
|
|||||||
createTable(className, schema, conn) {
|
createTable(className, schema, conn) {
|
||||||
conn = conn || this._client;
|
conn = conn || this._client;
|
||||||
debug('createTable', className, schema);
|
debug('createTable', className, schema);
|
||||||
let valuesArray = [];
|
const valuesArray = [];
|
||||||
let patternsArray = [];
|
const patternsArray = [];
|
||||||
let fields = Object.assign({}, schema.fields);
|
const fields = Object.assign({}, schema.fields);
|
||||||
if (className === '_User') {
|
if (className === '_User') {
|
||||||
fields._email_verify_token_expires_at = {type: 'Date'};
|
fields._email_verify_token_expires_at = {type: 'Date'};
|
||||||
fields._email_verify_token = {type: 'String'};
|
fields._email_verify_token = {type: 'String'};
|
||||||
@@ -475,9 +475,9 @@ export class PostgresStorageAdapter {
|
|||||||
fields._password_history = { type: 'Array'};
|
fields._password_history = { type: 'Array'};
|
||||||
}
|
}
|
||||||
let index = 2;
|
let index = 2;
|
||||||
let relations = [];
|
const relations = [];
|
||||||
Object.keys(fields).forEach((fieldName) => {
|
Object.keys(fields).forEach((fieldName) => {
|
||||||
let parseType = fields[fieldName];
|
const parseType = fields[fieldName];
|
||||||
// Skip when it's a relation
|
// Skip when it's a relation
|
||||||
// We'll create the tables later
|
// We'll create the tables later
|
||||||
if (parseType.type === 'Relation') {
|
if (parseType.type === 'Relation') {
|
||||||
@@ -557,7 +557,7 @@ export class PostgresStorageAdapter {
|
|||||||
// and resolves with false if it wasn't (eg. a join table). Rejects if deletion was impossible.
|
// and resolves with false if it wasn't (eg. a join table). Rejects if deletion was impossible.
|
||||||
deleteClass(className) {
|
deleteClass(className) {
|
||||||
return Promise.resolve().then(() => {
|
return Promise.resolve().then(() => {
|
||||||
let operations = [[`DROP TABLE IF EXISTS $1:name`, [className]],
|
const operations = [[`DROP TABLE IF EXISTS $1:name`, [className]],
|
||||||
[`DELETE FROM "_SCHEMA" WHERE "className"=$1`, [className]]];
|
[`DELETE FROM "_SCHEMA" WHERE "className"=$1`, [className]]];
|
||||||
return this._client.tx(t=>t.batch(operations.map(statement=>t.none(statement[0], statement[1]))));
|
return this._client.tx(t=>t.batch(operations.map(statement=>t.none(statement[0], statement[1]))));
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -568,11 +568,11 @@ export class PostgresStorageAdapter {
|
|||||||
|
|
||||||
// Delete all data known to this adapter. Used for testing.
|
// Delete all data known to this adapter. Used for testing.
|
||||||
deleteAllClasses() {
|
deleteAllClasses() {
|
||||||
let now = new Date().getTime();
|
const now = new Date().getTime();
|
||||||
debug('deleteAllClasses');
|
debug('deleteAllClasses');
|
||||||
return this._client.any('SELECT * FROM "_SCHEMA"')
|
return this._client.any('SELECT * FROM "_SCHEMA"')
|
||||||
.then(results => {
|
.then(results => {
|
||||||
let joins = results.reduce((list, schema) => {
|
const joins = results.reduce((list, schema) => {
|
||||||
return list.concat(joinTablesForSchema(schema.schema));
|
return list.concat(joinTablesForSchema(schema.schema));
|
||||||
}, []);
|
}, []);
|
||||||
const classes = ['_SCHEMA','_PushStatus','_JobStatus','_Hooks','_GlobalConfig', ...results.map(result => result.className), ...joins];
|
const classes = ['_SCHEMA','_PushStatus','_JobStatus','_Hooks','_GlobalConfig', ...results.map(result => result.className), ...joins];
|
||||||
@@ -607,7 +607,7 @@ export class PostgresStorageAdapter {
|
|||||||
return Promise.resolve()
|
return Promise.resolve()
|
||||||
.then(() => {
|
.then(() => {
|
||||||
fieldNames = fieldNames.reduce((list, fieldName) => {
|
fieldNames = fieldNames.reduce((list, fieldName) => {
|
||||||
let field = schema.fields[fieldName]
|
const field = schema.fields[fieldName]
|
||||||
if (field.type !== 'Relation') {
|
if (field.type !== 'Relation') {
|
||||||
list.push(fieldName);
|
list.push(fieldName);
|
||||||
}
|
}
|
||||||
@@ -615,13 +615,13 @@ export class PostgresStorageAdapter {
|
|||||||
return list;
|
return list;
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
let values = [className, ...fieldNames];
|
const values = [className, ...fieldNames];
|
||||||
let columns = fieldNames.map((name, idx) => {
|
const columns = fieldNames.map((name, idx) => {
|
||||||
return `$${idx+2}:name`;
|
return `$${idx+2}:name`;
|
||||||
}).join(',');
|
}).join(',');
|
||||||
|
|
||||||
let doBatch = (t) => {
|
const doBatch = (t) => {
|
||||||
let batch = [
|
const batch = [
|
||||||
t.none('UPDATE "_SCHEMA" SET "schema"=$<schema> WHERE "className"=$<className>', {schema, className})
|
t.none('UPDATE "_SCHEMA" SET "schema"=$<schema> WHERE "className"=$<className>', {schema, className})
|
||||||
];
|
];
|
||||||
if (values.length > 1) {
|
if (values.length > 1) {
|
||||||
@@ -663,9 +663,9 @@ export class PostgresStorageAdapter {
|
|||||||
createObject(className, schema, object) {
|
createObject(className, schema, object) {
|
||||||
debug('createObject', className, object);
|
debug('createObject', className, object);
|
||||||
let columnsArray = [];
|
let columnsArray = [];
|
||||||
let valuesArray = [];
|
const valuesArray = [];
|
||||||
schema = toPostgresSchema(schema);
|
schema = toPostgresSchema(schema);
|
||||||
let geoPoints = {};
|
const geoPoints = {};
|
||||||
|
|
||||||
object = handleDotFields(object);
|
object = handleDotFields(object);
|
||||||
|
|
||||||
@@ -747,9 +747,9 @@ export class PostgresStorageAdapter {
|
|||||||
});
|
});
|
||||||
|
|
||||||
columnsArray = columnsArray.concat(Object.keys(geoPoints));
|
columnsArray = columnsArray.concat(Object.keys(geoPoints));
|
||||||
let initialValues = valuesArray.map((val, index) => {
|
const initialValues = valuesArray.map((val, index) => {
|
||||||
let termination = '';
|
let termination = '';
|
||||||
let fieldName = columnsArray[index];
|
const fieldName = columnsArray[index];
|
||||||
if (['_rperm','_wperm'].indexOf(fieldName) >= 0) {
|
if (['_rperm','_wperm'].indexOf(fieldName) >= 0) {
|
||||||
termination = '::text[]';
|
termination = '::text[]';
|
||||||
} else if (schema.fields[fieldName] && schema.fields[fieldName].type === 'Array') {
|
} else if (schema.fields[fieldName] && schema.fields[fieldName].type === 'Array') {
|
||||||
@@ -757,18 +757,18 @@ export class PostgresStorageAdapter {
|
|||||||
}
|
}
|
||||||
return `$${index + 2 + columnsArray.length}${termination}`;
|
return `$${index + 2 + columnsArray.length}${termination}`;
|
||||||
});
|
});
|
||||||
let geoPointsInjects = Object.keys(geoPoints).map((key) => {
|
const geoPointsInjects = Object.keys(geoPoints).map((key) => {
|
||||||
let value = geoPoints[key];
|
const value = geoPoints[key];
|
||||||
valuesArray.push(value.longitude, value.latitude);
|
valuesArray.push(value.longitude, value.latitude);
|
||||||
let l = valuesArray.length + columnsArray.length;
|
const l = valuesArray.length + columnsArray.length;
|
||||||
return `POINT($${l}, $${l+1})`;
|
return `POINT($${l}, $${l+1})`;
|
||||||
});
|
});
|
||||||
|
|
||||||
let columnsPattern = columnsArray.map((col, index) => `$${index + 2}:name`).join(',');
|
const columnsPattern = columnsArray.map((col, index) => `$${index + 2}:name`).join(',');
|
||||||
let valuesPattern = initialValues.concat(geoPointsInjects).join(',')
|
const valuesPattern = initialValues.concat(geoPointsInjects).join(',')
|
||||||
|
|
||||||
let qs = `INSERT INTO $1:name (${columnsPattern}) VALUES (${valuesPattern})`
|
const qs = `INSERT INTO $1:name (${columnsPattern}) VALUES (${valuesPattern})`
|
||||||
let values = [className, ...columnsArray, ...valuesArray]
|
const values = [className, ...columnsArray, ...valuesArray]
|
||||||
debug(qs, values);
|
debug(qs, values);
|
||||||
return this._client.any(qs, values)
|
return this._client.any(qs, values)
|
||||||
.then(() => ({ ops: [object] }))
|
.then(() => ({ ops: [object] }))
|
||||||
@@ -786,14 +786,14 @@ export class PostgresStorageAdapter {
|
|||||||
// If there is some other error, reject with INTERNAL_SERVER_ERROR.
|
// If there is some other error, reject with INTERNAL_SERVER_ERROR.
|
||||||
deleteObjectsByQuery(className, schema, query) {
|
deleteObjectsByQuery(className, schema, query) {
|
||||||
debug('deleteObjectsByQuery', className, query);
|
debug('deleteObjectsByQuery', className, query);
|
||||||
let values = [className];
|
const values = [className];
|
||||||
let index = 2;
|
const index = 2;
|
||||||
let where = buildWhereClause({ schema, index, query })
|
const where = buildWhereClause({ schema, index, query })
|
||||||
values.push(...where.values);
|
values.push(...where.values);
|
||||||
if (Object.keys(query).length === 0) {
|
if (Object.keys(query).length === 0) {
|
||||||
where.pattern = 'TRUE';
|
where.pattern = 'TRUE';
|
||||||
}
|
}
|
||||||
let qs = `WITH deleted AS (DELETE FROM $1:name WHERE ${where.pattern} RETURNING *) SELECT count(*) FROM deleted`;
|
const qs = `WITH deleted AS (DELETE FROM $1:name WHERE ${where.pattern} RETURNING *) SELECT count(*) FROM deleted`;
|
||||||
debug(qs, values);
|
debug(qs, values);
|
||||||
return this._client.one(qs, values , a => +a.count)
|
return this._client.one(qs, values , a => +a.count)
|
||||||
.then(count => {
|
.then(count => {
|
||||||
@@ -813,8 +813,8 @@ export class PostgresStorageAdapter {
|
|||||||
// Apply the update to all objects that match the given Parse Query.
|
// Apply the update to all objects that match the given Parse Query.
|
||||||
updateObjectsByQuery(className, schema, query, update) {
|
updateObjectsByQuery(className, schema, query, update) {
|
||||||
debug('updateObjectsByQuery', className, query, update);
|
debug('updateObjectsByQuery', className, query, update);
|
||||||
let updatePatterns = [];
|
const updatePatterns = [];
|
||||||
let values = [className]
|
const values = [className]
|
||||||
let index = 2;
|
let index = 2;
|
||||||
schema = toPostgresSchema(schema);
|
schema = toPostgresSchema(schema);
|
||||||
|
|
||||||
@@ -822,19 +822,19 @@ export class PostgresStorageAdapter {
|
|||||||
update = handleDotFields(update);
|
update = handleDotFields(update);
|
||||||
// Resolve authData first,
|
// Resolve authData first,
|
||||||
// So we don't end up with multiple key updates
|
// So we don't end up with multiple key updates
|
||||||
for (let fieldName in update) {
|
for (const fieldName in update) {
|
||||||
let authDataMatch = fieldName.match(/^_auth_data_([a-zA-Z0-9_]+)$/);
|
const authDataMatch = fieldName.match(/^_auth_data_([a-zA-Z0-9_]+)$/);
|
||||||
if (authDataMatch) {
|
if (authDataMatch) {
|
||||||
var provider = authDataMatch[1];
|
var provider = authDataMatch[1];
|
||||||
let value = update[fieldName];
|
const value = update[fieldName];
|
||||||
delete update[fieldName];
|
delete update[fieldName];
|
||||||
update['authData'] = update['authData'] || {};
|
update['authData'] = update['authData'] || {};
|
||||||
update['authData'][provider] = value;
|
update['authData'][provider] = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let fieldName in update) {
|
for (const fieldName in update) {
|
||||||
let fieldValue = update[fieldName];
|
const fieldValue = update[fieldName];
|
||||||
if (fieldValue === null) {
|
if (fieldValue === null) {
|
||||||
updatePatterns.push(`$${index}:name = NULL`);
|
updatePatterns.push(`$${index}:name = NULL`);
|
||||||
values.push(fieldName);
|
values.push(fieldName);
|
||||||
@@ -842,15 +842,15 @@ export class PostgresStorageAdapter {
|
|||||||
} else if (fieldName == 'authData') {
|
} else if (fieldName == 'authData') {
|
||||||
// This recursively sets the json_object
|
// This recursively sets the json_object
|
||||||
// Only 1 level deep
|
// Only 1 level deep
|
||||||
let generate = (jsonb, key, value) => {
|
const generate = (jsonb, key, value) => {
|
||||||
return `json_object_set_key(COALESCE(${jsonb}, '{}'::jsonb), ${key}, ${value})::jsonb`;
|
return `json_object_set_key(COALESCE(${jsonb}, '{}'::jsonb), ${key}, ${value})::jsonb`;
|
||||||
}
|
}
|
||||||
let lastKey = `$${index}:name`;
|
const lastKey = `$${index}:name`;
|
||||||
let fieldNameIndex = index;
|
const fieldNameIndex = index;
|
||||||
index+=1;
|
index+=1;
|
||||||
values.push(fieldName);
|
values.push(fieldName);
|
||||||
let update = Object.keys(fieldValue).reduce((lastKey, key) => {
|
const update = Object.keys(fieldValue).reduce((lastKey, key) => {
|
||||||
let str = generate(lastKey, `$${index}::text`, `$${index+1}::jsonb`)
|
const str = generate(lastKey, `$${index}::text`, `$${index+1}::jsonb`)
|
||||||
index+=2;
|
index+=2;
|
||||||
let value = fieldValue[key];
|
let value = fieldValue[key];
|
||||||
if (value) {
|
if (value) {
|
||||||
@@ -941,12 +941,12 @@ export class PostgresStorageAdapter {
|
|||||||
} else if (Array.isArray(fieldValue)
|
} else if (Array.isArray(fieldValue)
|
||||||
&& schema.fields[fieldName]
|
&& schema.fields[fieldName]
|
||||||
&& schema.fields[fieldName].type === 'Array') {
|
&& schema.fields[fieldName].type === 'Array') {
|
||||||
let expectedType = parseTypeToPostgresType(schema.fields[fieldName]);
|
const expectedType = parseTypeToPostgresType(schema.fields[fieldName]);
|
||||||
if (expectedType === 'text[]') {
|
if (expectedType === 'text[]') {
|
||||||
updatePatterns.push(`$${index}:name = $${index + 1}::text[]`);
|
updatePatterns.push(`$${index}:name = $${index + 1}::text[]`);
|
||||||
} else {
|
} else {
|
||||||
let type = 'text';
|
let type = 'text';
|
||||||
for (let elt of fieldValue) {
|
for (const elt of fieldValue) {
|
||||||
if (typeof elt == 'object') {
|
if (typeof elt == 'object') {
|
||||||
type = 'json';
|
type = 'json';
|
||||||
break;
|
break;
|
||||||
@@ -962,10 +962,10 @@ export class PostgresStorageAdapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let where = buildWhereClause({ schema, index, query })
|
const where = buildWhereClause({ schema, index, query })
|
||||||
values.push(...where.values);
|
values.push(...where.values);
|
||||||
|
|
||||||
let qs = `UPDATE $1:name SET ${updatePatterns.join(',')} WHERE ${where.pattern} RETURNING *`;
|
const qs = `UPDATE $1:name SET ${updatePatterns.join(',')} WHERE ${where.pattern} RETURNING *`;
|
||||||
debug('update: ', qs, values);
|
debug('update: ', qs, values);
|
||||||
return this._client.any(qs, values); // TODO: This is unsafe, verification is needed, or a different query method;
|
return this._client.any(qs, values); // TODO: This is unsafe, verification is needed, or a different query method;
|
||||||
}
|
}
|
||||||
@@ -973,7 +973,7 @@ export class PostgresStorageAdapter {
|
|||||||
// Hopefully, we can get rid of this. It's only used for config and hooks.
|
// Hopefully, we can get rid of this. It's only used for config and hooks.
|
||||||
upsertOneObject(className, schema, query, update) {
|
upsertOneObject(className, schema, query, update) {
|
||||||
debug('upsertOneObject', {className, query, update});
|
debug('upsertOneObject', {className, query, update});
|
||||||
let createValue = Object.assign({}, query, update);
|
const createValue = Object.assign({}, query, update);
|
||||||
return this.createObject(className, schema, createValue).catch((err) => {
|
return this.createObject(className, schema, createValue).catch((err) => {
|
||||||
// ignore duplicate value errors as it's upsert
|
// ignore duplicate value errors as it's upsert
|
||||||
if (err.code === Parse.Error.DUPLICATE_VALUE) {
|
if (err.code === Parse.Error.DUPLICATE_VALUE) {
|
||||||
@@ -988,7 +988,7 @@ export class PostgresStorageAdapter {
|
|||||||
const hasLimit = limit !== undefined;
|
const hasLimit = limit !== undefined;
|
||||||
const hasSkip = skip !== undefined;
|
const hasSkip = skip !== undefined;
|
||||||
let values = [className];
|
let values = [className];
|
||||||
let where = buildWhereClause({ schema, query, index: 2 })
|
const where = buildWhereClause({ schema, query, index: 2 })
|
||||||
values.push(...where.values);
|
values.push(...where.values);
|
||||||
|
|
||||||
const wherePattern = where.pattern.length > 0 ? `WHERE ${where.pattern}` : '';
|
const wherePattern = where.pattern.length > 0 ? `WHERE ${where.pattern}` : '';
|
||||||
@@ -1003,7 +1003,7 @@ export class PostgresStorageAdapter {
|
|||||||
|
|
||||||
let sortPattern = '';
|
let sortPattern = '';
|
||||||
if (sort) {
|
if (sort) {
|
||||||
let sorting = Object.keys(sort).map((key) => {
|
const sorting = Object.keys(sort).map((key) => {
|
||||||
// Using $idx pattern gives: non-integer constant in ORDER BY
|
// Using $idx pattern gives: non-integer constant in ORDER BY
|
||||||
if (sort[key] === 1) {
|
if (sort[key] === 1) {
|
||||||
return `"${key}" ASC`;
|
return `"${key}" ASC`;
|
||||||
@@ -1085,7 +1085,7 @@ export class PostgresStorageAdapter {
|
|||||||
object._password_changed_at = { __type: 'Date', iso: object._password_changed_at.toISOString() };
|
object._password_changed_at = { __type: 'Date', iso: object._password_changed_at.toISOString() };
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let fieldName in object) {
|
for (const fieldName in object) {
|
||||||
if (object[fieldName] === null) {
|
if (object[fieldName] === null) {
|
||||||
delete object[fieldName];
|
delete object[fieldName];
|
||||||
}
|
}
|
||||||
@@ -1125,8 +1125,8 @@ export class PostgresStorageAdapter {
|
|||||||
// Executes a count.
|
// Executes a count.
|
||||||
count(className, schema, query) {
|
count(className, schema, query) {
|
||||||
debug('count', className, query);
|
debug('count', className, query);
|
||||||
let values = [className];
|
const values = [className];
|
||||||
let where = buildWhereClause({ schema, query, index: 2 });
|
const where = buildWhereClause({ schema, query, index: 2 });
|
||||||
values.push(...where.values);
|
values.push(...where.values);
|
||||||
|
|
||||||
const wherePattern = where.pattern.length > 0 ? `WHERE ${where.pattern}` : '';
|
const wherePattern = where.pattern.length > 0 ? `WHERE ${where.pattern}` : '';
|
||||||
@@ -1140,7 +1140,7 @@ export class PostgresStorageAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
performInitialization({ VolatileClassesSchemas }) {
|
performInitialization({ VolatileClassesSchemas }) {
|
||||||
let now = new Date().getTime();
|
const now = new Date().getTime();
|
||||||
debug('performInitialization');
|
debug('performInitialization');
|
||||||
let promises = VolatileClassesSchemas.map((schema) => {
|
let promises = VolatileClassesSchemas.map((schema) => {
|
||||||
return this.createTable(schema.className, schema).catch((err) =>{
|
return this.createTable(schema.className, schema).catch((err) =>{
|
||||||
|
|||||||
14
src/Auth.js
14
src/Auth.js
@@ -44,7 +44,7 @@ function nobody(config) {
|
|||||||
var getAuthForSessionToken = function({ config, sessionToken, installationId } = {}) {
|
var getAuthForSessionToken = function({ config, sessionToken, installationId } = {}) {
|
||||||
return config.cacheController.user.get(sessionToken).then((userJSON) => {
|
return config.cacheController.user.get(sessionToken).then((userJSON) => {
|
||||||
if (userJSON) {
|
if (userJSON) {
|
||||||
let cachedUser = Parse.Object.fromJSON(userJSON);
|
const cachedUser = Parse.Object.fromJSON(userJSON);
|
||||||
return Promise.resolve(new Auth({config, isMaster: false, installationId, user: cachedUser}));
|
return Promise.resolve(new Auth({config, isMaster: false, installationId, user: cachedUser}));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,7 +71,7 @@ var getAuthForSessionToken = function({ config, sessionToken, installationId } =
|
|||||||
obj['className'] = '_User';
|
obj['className'] = '_User';
|
||||||
obj['sessionToken'] = sessionToken;
|
obj['sessionToken'] = sessionToken;
|
||||||
config.cacheController.user.put(sessionToken, obj);
|
config.cacheController.user.put(sessionToken, obj);
|
||||||
let userObject = Parse.Object.fromJSON(obj);
|
const userObject = Parse.Object.fromJSON(obj);
|
||||||
return new Auth({config, isMaster: false, installationId, user: userObject});
|
return new Auth({config, isMaster: false, installationId, user: userObject});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -87,9 +87,9 @@ var getAuthForLegacySessionToken = function({config, sessionToken, installationI
|
|||||||
if (results.length !== 1) {
|
if (results.length !== 1) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid legacy session token');
|
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid legacy session token');
|
||||||
}
|
}
|
||||||
let obj = results[0];
|
const obj = results[0];
|
||||||
obj.className = '_User';
|
obj.className = '_User';
|
||||||
let userObject = Parse.Object.fromJSON(obj);
|
const userObject = Parse.Object.fromJSON(obj);
|
||||||
return new Auth({config, isMaster: false, installationId, user: userObject});
|
return new Auth({config, isMaster: false, installationId, user: userObject});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -162,7 +162,7 @@ Auth.prototype._loadRoles = function() {
|
|||||||
|
|
||||||
// Given a list of roleIds, find all the parent roles, returns a promise with all names
|
// Given a list of roleIds, find all the parent roles, returns a promise with all names
|
||||||
Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queriedRoles = {}) {
|
Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queriedRoles = {}) {
|
||||||
let ins = roleIDs.filter((roleID) => {
|
const ins = roleIDs.filter((roleID) => {
|
||||||
return queriedRoles[roleID] !== true;
|
return queriedRoles[roleID] !== true;
|
||||||
}).map((roleID) => {
|
}).map((roleID) => {
|
||||||
// mark as queried
|
// mark as queried
|
||||||
@@ -185,7 +185,7 @@ Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queri
|
|||||||
} else {
|
} else {
|
||||||
restWhere = { 'roles': { '$in': ins }}
|
restWhere = { 'roles': { '$in': ins }}
|
||||||
}
|
}
|
||||||
let query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {});
|
const query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {});
|
||||||
return query.execute().then((response) => {
|
return query.execute().then((response) => {
|
||||||
var results = response.results;
|
var results = response.results;
|
||||||
// Nothing found
|
// Nothing found
|
||||||
@@ -193,7 +193,7 @@ Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queri
|
|||||||
return Promise.resolve(names);
|
return Promise.resolve(names);
|
||||||
}
|
}
|
||||||
// Map the results with all Ids and names
|
// Map the results with all Ids and names
|
||||||
let resultMap = results.reduce((memo, role) => {
|
const resultMap = results.reduce((memo, role) => {
|
||||||
memo.names.push(role.name);
|
memo.names.push(role.name);
|
||||||
memo.ids.push(role.objectId);
|
memo.ids.push(role.objectId);
|
||||||
return memo;
|
return memo;
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ function compatible(compatibleSDK) {
|
|||||||
if (!clientSDK) {
|
if (!clientSDK) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
let clientVersion = clientSDK.version;
|
const clientVersion = clientSDK.version;
|
||||||
let compatiblityVersion = compatibleSDK[clientSDK.sdk];
|
const compatiblityVersion = compatibleSDK[clientSDK.sdk];
|
||||||
return semver.satisfies(clientVersion, compatiblityVersion);
|
return semver.satisfies(clientVersion, compatiblityVersion);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -22,8 +22,8 @@ function supportsForwardDelete(clientSDK) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function fromString(version) {
|
function fromString(version) {
|
||||||
let versionRE = /([-a-zA-Z]+)([0-9\.]+)/;
|
const versionRE = /([-a-zA-Z]+)([0-9\.]+)/;
|
||||||
let match = version.toLowerCase().match(versionRE);
|
const match = version.toLowerCase().match(versionRE);
|
||||||
if (match && match.length === 3) {
|
if (match && match.length === 3) {
|
||||||
return {
|
return {
|
||||||
sdk: match[1],
|
sdk: match[1],
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ function removeTrailingSlash(str) {
|
|||||||
|
|
||||||
export class Config {
|
export class Config {
|
||||||
constructor(applicationId: string, mount: string) {
|
constructor(applicationId: string, mount: string) {
|
||||||
let cacheInfo = AppCache.get(applicationId);
|
const cacheInfo = AppCache.get(applicationId);
|
||||||
if (!cacheInfo) {
|
if (!cacheInfo) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,14 +42,14 @@ export class AdaptableController {
|
|||||||
throw new Error(this.constructor.name+" requires an adapter");
|
throw new Error(this.constructor.name+" requires an adapter");
|
||||||
}
|
}
|
||||||
|
|
||||||
let Type = this.expectedAdapterType();
|
const Type = this.expectedAdapterType();
|
||||||
// Allow skipping for testing
|
// Allow skipping for testing
|
||||||
if (!Type) {
|
if (!Type) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Makes sure the prototype matches
|
// Makes sure the prototype matches
|
||||||
let mismatches = Object.getOwnPropertyNames(Type.prototype).reduce((obj, key) => {
|
const mismatches = Object.getOwnPropertyNames(Type.prototype).reduce((obj, key) => {
|
||||||
const adapterType = typeof adapter[key];
|
const adapterType = typeof adapter[key];
|
||||||
const expectedType = typeof Type.prototype[key];
|
const expectedType = typeof Type.prototype[key];
|
||||||
if (adapterType !== expectedType) {
|
if (adapterType !== expectedType) {
|
||||||
|
|||||||
@@ -20,17 +20,17 @@ export class SubCache {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get(key) {
|
get(key) {
|
||||||
let cacheKey = joinKeys(this.prefix, key);
|
const cacheKey = joinKeys(this.prefix, key);
|
||||||
return this.cache.get(cacheKey);
|
return this.cache.get(cacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
put(key, value, ttl) {
|
put(key, value, ttl) {
|
||||||
let cacheKey = joinKeys(this.prefix, key);
|
const cacheKey = joinKeys(this.prefix, key);
|
||||||
return this.cache.put(cacheKey, value, ttl);
|
return this.cache.put(cacheKey, value, ttl);
|
||||||
}
|
}
|
||||||
|
|
||||||
del(key) {
|
del(key) {
|
||||||
let cacheKey = joinKeys(this.prefix, key);
|
const cacheKey = joinKeys(this.prefix, key);
|
||||||
return this.cache.del(cacheKey);
|
return this.cache.del(cacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,17 +50,17 @@ export class CacheController extends AdaptableController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
get(key) {
|
get(key) {
|
||||||
let cacheKey = joinKeys(this.appId, key);
|
const cacheKey = joinKeys(this.appId, key);
|
||||||
return this.adapter.get(cacheKey).then(null, () => Promise.resolve(null));
|
return this.adapter.get(cacheKey).then(null, () => Promise.resolve(null));
|
||||||
}
|
}
|
||||||
|
|
||||||
put(key, value, ttl) {
|
put(key, value, ttl) {
|
||||||
let cacheKey = joinKeys(this.appId, key);
|
const cacheKey = joinKeys(this.appId, key);
|
||||||
return this.adapter.put(cacheKey, value, ttl);
|
return this.adapter.put(cacheKey, value, ttl);
|
||||||
}
|
}
|
||||||
|
|
||||||
del(key) {
|
del(key) {
|
||||||
let cacheKey = joinKeys(this.appId, key);
|
const cacheKey = joinKeys(this.appId, key);
|
||||||
return this.adapter.del(cacheKey);
|
return this.adapter.del(cacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ import logger from '../logger';
|
|||||||
import * as SchemaController from './SchemaController';
|
import * as SchemaController from './SchemaController';
|
||||||
|
|
||||||
function addWriteACL(query, acl) {
|
function addWriteACL(query, acl) {
|
||||||
let newQuery = _.cloneDeep(query);
|
const newQuery = _.cloneDeep(query);
|
||||||
//Can't be any existing '_wperm' query, we don't allow client queries on that, no need to $and
|
//Can't be any existing '_wperm' query, we don't allow client queries on that, no need to $and
|
||||||
newQuery._wperm = { "$in" : [null, ...acl]};
|
newQuery._wperm = { "$in" : [null, ...acl]};
|
||||||
return newQuery;
|
return newQuery;
|
||||||
}
|
}
|
||||||
|
|
||||||
function addReadACL(query, acl) {
|
function addReadACL(query, acl) {
|
||||||
let newQuery = _.cloneDeep(query);
|
const newQuery = _.cloneDeep(query);
|
||||||
//Can't be any existing '_rperm' query, we don't allow client queries on that, no need to $and
|
//Can't be any existing '_rperm' query, we don't allow client queries on that, no need to $and
|
||||||
newQuery._rperm = { "$in" : [null, "*", ...acl]};
|
newQuery._rperm = { "$in" : [null, "*", ...acl]};
|
||||||
return newQuery;
|
return newQuery;
|
||||||
@@ -31,7 +31,7 @@ const transformObjectACL = ({ ACL, ...result }) => {
|
|||||||
result._wperm = [];
|
result._wperm = [];
|
||||||
result._rperm = [];
|
result._rperm = [];
|
||||||
|
|
||||||
for (let entry in ACL) {
|
for (const entry in ACL) {
|
||||||
if (ACL[entry].read) {
|
if (ACL[entry].read) {
|
||||||
result._rperm.push(entry);
|
result._rperm.push(entry);
|
||||||
}
|
}
|
||||||
@@ -139,7 +139,7 @@ DatabaseController.prototype.redirectClassNameForKey = function(className, key)
|
|||||||
// batch request, that could confuse other users of the schema.
|
// batch request, that could confuse other users of the schema.
|
||||||
DatabaseController.prototype.validateObject = function(className, object, query, { acl }) {
|
DatabaseController.prototype.validateObject = function(className, object, query, { acl }) {
|
||||||
let schema;
|
let schema;
|
||||||
let isMaster = acl === undefined;
|
const isMaster = acl === undefined;
|
||||||
var aclGroup = acl || [];
|
var aclGroup = acl || [];
|
||||||
return this.loadSchema().then(s => {
|
return this.loadSchema().then(s => {
|
||||||
schema = s;
|
schema = s;
|
||||||
@@ -241,7 +241,7 @@ DatabaseController.prototype.update = function(className, query, update, {
|
|||||||
throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid field name for update: ${fieldName}`);
|
throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid field name for update: ${fieldName}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
for (let updateOperation in update) {
|
for (const updateOperation in update) {
|
||||||
if (Object.keys(updateOperation).some(innerKey => innerKey.includes('$') || innerKey.includes('.'))) {
|
if (Object.keys(updateOperation).some(innerKey => innerKey.includes('$') || innerKey.includes('.'))) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_NESTED_KEY, "Nested keys should not contain the '$' or '.' characters");
|
throw new Parse.Error(Parse.Error.INVALID_NESTED_KEY, "Nested keys should not contain the '$' or '.' characters");
|
||||||
}
|
}
|
||||||
@@ -270,12 +270,12 @@ DatabaseController.prototype.update = function(className, query, update, {
|
|||||||
};
|
};
|
||||||
|
|
||||||
function sanitizeDatabaseResult(originalObject, result) {
|
function sanitizeDatabaseResult(originalObject, result) {
|
||||||
let response = {};
|
const response = {};
|
||||||
if (!result) {
|
if (!result) {
|
||||||
return Promise.resolve(response);
|
return Promise.resolve(response);
|
||||||
}
|
}
|
||||||
Object.keys(originalObject).forEach(key => {
|
Object.keys(originalObject).forEach(key => {
|
||||||
let keyUpdate = originalObject[key];
|
const keyUpdate = originalObject[key];
|
||||||
// determine if that was an op
|
// determine if that was an op
|
||||||
if (keyUpdate && typeof keyUpdate === 'object' && keyUpdate.__op
|
if (keyUpdate && typeof keyUpdate === 'object' && keyUpdate.__op
|
||||||
&& ['Add', 'AddUnique', 'Remove', 'Increment'].indexOf(keyUpdate.__op) > -1) {
|
&& ['Add', 'AddUnique', 'Remove', 'Increment'].indexOf(keyUpdate.__op) > -1) {
|
||||||
@@ -300,7 +300,7 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (op.__op == 'AddRelation') {
|
if (op.__op == 'AddRelation') {
|
||||||
for (let object of op.objects) {
|
for (const object of op.objects) {
|
||||||
pending.push(this.addRelation(key, className,
|
pending.push(this.addRelation(key, className,
|
||||||
objectId,
|
objectId,
|
||||||
object.objectId));
|
object.objectId));
|
||||||
@@ -309,7 +309,7 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (op.__op == 'RemoveRelation') {
|
if (op.__op == 'RemoveRelation') {
|
||||||
for (let object of op.objects) {
|
for (const object of op.objects) {
|
||||||
pending.push(this.removeRelation(key, className,
|
pending.push(this.removeRelation(key, className,
|
||||||
objectId,
|
objectId,
|
||||||
object.objectId));
|
object.objectId));
|
||||||
@@ -324,10 +324,10 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
for (let key in update) {
|
for (const key in update) {
|
||||||
process(update[key], key);
|
process(update[key], key);
|
||||||
}
|
}
|
||||||
for (let key of deleteMe) {
|
for (const key of deleteMe) {
|
||||||
delete update[key];
|
delete update[key];
|
||||||
}
|
}
|
||||||
return Promise.all(pending);
|
return Promise.all(pending);
|
||||||
@@ -337,7 +337,7 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI
|
|||||||
// Returns a promise that resolves successfully iff the add was successful.
|
// Returns a promise that resolves successfully iff the add was successful.
|
||||||
const relationSchema = { fields: { relatedId: { type: 'String' }, owningId: { type: 'String' } } };
|
const relationSchema = { fields: { relatedId: { type: 'String' }, owningId: { type: 'String' } } };
|
||||||
DatabaseController.prototype.addRelation = function(key, fromClassName, fromId, toId) {
|
DatabaseController.prototype.addRelation = function(key, fromClassName, fromId, toId) {
|
||||||
let doc = {
|
const doc = {
|
||||||
relatedId: toId,
|
relatedId: toId,
|
||||||
owningId : fromId
|
owningId : fromId
|
||||||
};
|
};
|
||||||
@@ -410,7 +410,7 @@ DatabaseController.prototype.destroy = function(className, query, { acl } = {})
|
|||||||
};
|
};
|
||||||
|
|
||||||
const flattenUpdateOperatorsForCreate = object => {
|
const flattenUpdateOperatorsForCreate = object => {
|
||||||
for (let key in object) {
|
for (const key in object) {
|
||||||
if (object[key] && object[key].__op) {
|
if (object[key] && object[key].__op) {
|
||||||
switch (object[key].__op) {
|
switch (object[key].__op) {
|
||||||
case 'Increment':
|
case 'Increment':
|
||||||
@@ -469,7 +469,7 @@ const transformAuthData = (className, object, schema) => {
|
|||||||
// Returns a promise that resolves successfully iff the object saved.
|
// Returns a promise that resolves successfully iff the object saved.
|
||||||
DatabaseController.prototype.create = function(className, object, { acl } = {}) {
|
DatabaseController.prototype.create = function(className, object, { acl } = {}) {
|
||||||
// Make a copy of the object, so we don't mutate the incoming data.
|
// Make a copy of the object, so we don't mutate the incoming data.
|
||||||
let originalObject = object;
|
const originalObject = object;
|
||||||
object = transformObjectACL(object);
|
object = transformObjectACL(object);
|
||||||
|
|
||||||
object.createdAt = { iso: object.createdAt, __type: 'Date' };
|
object.createdAt = { iso: object.createdAt, __type: 'Date' };
|
||||||
@@ -496,13 +496,13 @@ DatabaseController.prototype.create = function(className, object, { acl } = {})
|
|||||||
};
|
};
|
||||||
|
|
||||||
DatabaseController.prototype.canAddField = function(schema, className, object, aclGroup) {
|
DatabaseController.prototype.canAddField = function(schema, className, object, aclGroup) {
|
||||||
let classSchema = schema.data[className];
|
const classSchema = schema.data[className];
|
||||||
if (!classSchema) {
|
if (!classSchema) {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
let fields = Object.keys(object);
|
const fields = Object.keys(object);
|
||||||
let schemaFields = Object.keys(classSchema);
|
const schemaFields = Object.keys(classSchema);
|
||||||
let newKeys = fields.filter((field) => {
|
const newKeys = fields.filter((field) => {
|
||||||
return schemaFields.indexOf(field) < 0;
|
return schemaFields.indexOf(field) < 0;
|
||||||
})
|
})
|
||||||
if (newKeys.length > 0) {
|
if (newKeys.length > 0) {
|
||||||
@@ -543,7 +543,7 @@ DatabaseController.prototype.reduceInRelation = function(className, query, schem
|
|||||||
// Search for an in-relation or equal-to-relation
|
// Search for an in-relation or equal-to-relation
|
||||||
// Make it sequential for now, not sure of paralleization side effects
|
// Make it sequential for now, not sure of paralleization side effects
|
||||||
if (query['$or']) {
|
if (query['$or']) {
|
||||||
let ors = query['$or'];
|
const ors = query['$or'];
|
||||||
return Promise.all(ors.map((aQuery, index) => {
|
return Promise.all(ors.map((aQuery, index) => {
|
||||||
return this.reduceInRelation(className, aQuery, schema).then((aQuery) => {
|
return this.reduceInRelation(className, aQuery, schema).then((aQuery) => {
|
||||||
query['$or'][index] = aQuery;
|
query['$or'][index] = aQuery;
|
||||||
@@ -553,14 +553,14 @@ DatabaseController.prototype.reduceInRelation = function(className, query, schem
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let promises = Object.keys(query).map((key) => {
|
const promises = Object.keys(query).map((key) => {
|
||||||
if (query[key] && (query[key]['$in'] || query[key]['$ne'] || query[key]['$nin'] || query[key].__type == 'Pointer')) {
|
if (query[key] && (query[key]['$in'] || query[key]['$ne'] || query[key]['$nin'] || query[key].__type == 'Pointer')) {
|
||||||
let t = schema.getExpectedType(className, key);
|
const t = schema.getExpectedType(className, key);
|
||||||
if (!t || t.type !== 'Relation') {
|
if (!t || t.type !== 'Relation') {
|
||||||
return Promise.resolve(query);
|
return Promise.resolve(query);
|
||||||
}
|
}
|
||||||
// Build the list of queries
|
// Build the list of queries
|
||||||
let queries = Object.keys(query[key]).map((constraintKey) => {
|
const queries = Object.keys(query[key]).map((constraintKey) => {
|
||||||
let relatedIds;
|
let relatedIds;
|
||||||
let isNegation = false;
|
let isNegation = false;
|
||||||
if (constraintKey === 'objectId') {
|
if (constraintKey === 'objectId') {
|
||||||
@@ -586,7 +586,7 @@ DatabaseController.prototype.reduceInRelation = function(className, query, schem
|
|||||||
delete query[key];
|
delete query[key];
|
||||||
// execute each query independnently to build the list of
|
// execute each query independnently to build the list of
|
||||||
// $in / $nin
|
// $in / $nin
|
||||||
let promises = queries.map((q) => {
|
const promises = queries.map((q) => {
|
||||||
if (!q) {
|
if (!q) {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
@@ -637,12 +637,12 @@ DatabaseController.prototype.reduceRelationKeys = function(className, query) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
DatabaseController.prototype.addInObjectIdsIds = function(ids = null, query) {
|
DatabaseController.prototype.addInObjectIdsIds = function(ids = null, query) {
|
||||||
let idsFromString = typeof query.objectId === 'string' ? [query.objectId] : null;
|
const idsFromString = typeof query.objectId === 'string' ? [query.objectId] : null;
|
||||||
let idsFromEq = query.objectId && query.objectId['$eq'] ? [query.objectId['$eq']] : null;
|
const idsFromEq = query.objectId && query.objectId['$eq'] ? [query.objectId['$eq']] : null;
|
||||||
let idsFromIn = query.objectId && query.objectId['$in'] ? query.objectId['$in'] : null;
|
const idsFromIn = query.objectId && query.objectId['$in'] ? query.objectId['$in'] : null;
|
||||||
|
|
||||||
let allIds = [idsFromString, idsFromEq, idsFromIn, ids].filter(list => list !== null);
|
const allIds = [idsFromString, idsFromEq, idsFromIn, ids].filter(list => list !== null);
|
||||||
let totalLength = allIds.reduce((memo, list) => memo + list.length, 0);
|
const totalLength = allIds.reduce((memo, list) => memo + list.length, 0);
|
||||||
|
|
||||||
let idsIntersection = [];
|
let idsIntersection = [];
|
||||||
if (totalLength > 125) {
|
if (totalLength > 125) {
|
||||||
@@ -665,7 +665,7 @@ DatabaseController.prototype.addInObjectIdsIds = function(ids = null, query) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
DatabaseController.prototype.addNotInObjectIdsIds = function(ids = [], query) {
|
DatabaseController.prototype.addNotInObjectIdsIds = function(ids = [], query) {
|
||||||
let idsFromNin = query.objectId && query.objectId['$nin'] ? query.objectId['$nin'] : [];
|
const idsFromNin = query.objectId && query.objectId['$nin'] ? query.objectId['$nin'] : [];
|
||||||
let allIds = [...idsFromNin,...ids].filter(list => list !== null);
|
let allIds = [...idsFromNin,...ids].filter(list => list !== null);
|
||||||
|
|
||||||
// make a set and spread to remove duplicates
|
// make a set and spread to remove duplicates
|
||||||
@@ -707,8 +707,8 @@ DatabaseController.prototype.find = function(className, query, {
|
|||||||
keys,
|
keys,
|
||||||
op
|
op
|
||||||
} = {}) {
|
} = {}) {
|
||||||
let isMaster = acl === undefined;
|
const isMaster = acl === undefined;
|
||||||
let aclGroup = acl || [];
|
const aclGroup = acl || [];
|
||||||
op = op || (typeof query.objectId == 'string' && Object.keys(query).length === 1 ? 'get' : 'find');
|
op = op || (typeof query.objectId == 'string' && Object.keys(query).length === 1 ? 'get' : 'find');
|
||||||
let classExists = true;
|
let classExists = true;
|
||||||
return this.loadSchema()
|
return this.loadSchema()
|
||||||
@@ -846,9 +846,9 @@ DatabaseController.prototype.addPointerPermissions = function(schema, className,
|
|||||||
if (schema.testBaseCLP(className, aclGroup, operation)) {
|
if (schema.testBaseCLP(className, aclGroup, operation)) {
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
let perms = schema.perms[className];
|
const perms = schema.perms[className];
|
||||||
let field = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields';
|
const field = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields';
|
||||||
let userACL = aclGroup.filter((acl) => {
|
const userACL = aclGroup.filter((acl) => {
|
||||||
return acl.indexOf('role:') != 0 && acl != '*';
|
return acl.indexOf('role:') != 0 && acl != '*';
|
||||||
});
|
});
|
||||||
// the ACL should have exactly 1 user
|
// the ACL should have exactly 1 user
|
||||||
@@ -858,16 +858,16 @@ DatabaseController.prototype.addPointerPermissions = function(schema, className,
|
|||||||
if (userACL.length != 1) {
|
if (userACL.length != 1) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let userId = userACL[0];
|
const userId = userACL[0];
|
||||||
let userPointer = {
|
const userPointer = {
|
||||||
"__type": "Pointer",
|
"__type": "Pointer",
|
||||||
"className": "_User",
|
"className": "_User",
|
||||||
"objectId": userId
|
"objectId": userId
|
||||||
};
|
};
|
||||||
|
|
||||||
let permFields = perms[field];
|
const permFields = perms[field];
|
||||||
let ors = permFields.map((key) => {
|
const ors = permFields.map((key) => {
|
||||||
let q = {
|
const q = {
|
||||||
[key]: userPointer
|
[key]: userPointer
|
||||||
};
|
};
|
||||||
return {'$and': [q, query]};
|
return {'$and': [q, query]};
|
||||||
@@ -886,17 +886,17 @@ DatabaseController.prototype.addPointerPermissions = function(schema, className,
|
|||||||
DatabaseController.prototype.performInitialization = function() {
|
DatabaseController.prototype.performInitialization = function() {
|
||||||
const requiredUserFields = { fields: { ...SchemaController.defaultColumns._Default, ...SchemaController.defaultColumns._User } };
|
const requiredUserFields = { fields: { ...SchemaController.defaultColumns._Default, ...SchemaController.defaultColumns._User } };
|
||||||
|
|
||||||
let userClassPromise = this.loadSchema()
|
const userClassPromise = this.loadSchema()
|
||||||
.then(schema => schema.enforceClassExists('_User'))
|
.then(schema => schema.enforceClassExists('_User'))
|
||||||
|
|
||||||
let usernameUniqueness = userClassPromise
|
const usernameUniqueness = userClassPromise
|
||||||
.then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['username']))
|
.then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['username']))
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
logger.warn('Unable to ensure uniqueness for usernames: ', error);
|
logger.warn('Unable to ensure uniqueness for usernames: ', error);
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
});
|
});
|
||||||
|
|
||||||
let emailUniqueness = userClassPromise
|
const emailUniqueness = userClassPromise
|
||||||
.then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['email']))
|
.then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['email']))
|
||||||
.catch(error => {
|
.catch(error => {
|
||||||
logger.warn('Unable to ensure uniqueness for user email addresses: ', error);
|
logger.warn('Unable to ensure uniqueness for user email addresses: ', error);
|
||||||
@@ -904,7 +904,7 @@ DatabaseController.prototype.performInitialization = function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Create tables for volatile classes
|
// Create tables for volatile classes
|
||||||
let adapterInit = this.adapter.performInitialization({ VolatileClassesSchemas: SchemaController.VolatileClassesSchemas });
|
const adapterInit = this.adapter.performInitialization({ VolatileClassesSchemas: SchemaController.VolatileClassesSchemas });
|
||||||
return Promise.all([usernameUniqueness, emailUniqueness, adapterInit]);
|
return Promise.all([usernameUniqueness, emailUniqueness, adapterInit]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ export class FilesController extends AdaptableController {
|
|||||||
|
|
||||||
createFile(config, filename, data, contentType) {
|
createFile(config, filename, data, contentType) {
|
||||||
|
|
||||||
let extname = path.extname(filename);
|
const extname = path.extname(filename);
|
||||||
|
|
||||||
const hasExtension = extname.length > 0;
|
const hasExtension = extname.length > 0;
|
||||||
|
|
||||||
@@ -53,13 +53,13 @@ export class FilesController extends AdaptableController {
|
|||||||
if (typeof object !== 'object') {
|
if (typeof object !== 'object') {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (let key in object) {
|
for (const key in object) {
|
||||||
let fileObject = object[key];
|
const fileObject = object[key];
|
||||||
if (fileObject && fileObject['__type'] === 'File') {
|
if (fileObject && fileObject['__type'] === 'File') {
|
||||||
if (fileObject['url']) {
|
if (fileObject['url']) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let filename = fileObject['name'];
|
const filename = fileObject['name'];
|
||||||
// all filenames starting with "tfss-" should be from files.parsetfss.com
|
// all filenames starting with "tfss-" should be from files.parsetfss.com
|
||||||
// all filenames starting with a "-" seperated UUID should be from files.parse.com
|
// all filenames starting with a "-" seperated UUID should be from files.parse.com
|
||||||
// all other filenames have been migrated or created from Parse Server
|
// all other filenames have been migrated or created from Parse Server
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ export class HooksController {
|
|||||||
|
|
||||||
function wrapToHTTPRequest(hook, key) {
|
function wrapToHTTPRequest(hook, key) {
|
||||||
return (req, res) => {
|
return (req, res) => {
|
||||||
let jsonBody = {};
|
const jsonBody = {};
|
||||||
for (var i in req) {
|
for (var i in req) {
|
||||||
jsonBody[i] = req[i];
|
jsonBody[i] = req[i];
|
||||||
}
|
}
|
||||||
@@ -169,7 +169,7 @@ function wrapToHTTPRequest(hook, key) {
|
|||||||
jsonBody.original = req.original.toJSON();
|
jsonBody.original = req.original.toJSON();
|
||||||
jsonBody.original.className = req.original.className;
|
jsonBody.original.className = req.original.className;
|
||||||
}
|
}
|
||||||
let jsonRequest: any = {
|
const jsonRequest: any = {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export class LiveQueryController {
|
|||||||
if (!this.hasLiveQuery(className)) {
|
if (!this.hasLiveQuery(className)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let req = this._makePublisherRequest(currentObject, originalObject);
|
const req = this._makePublisherRequest(currentObject, originalObject);
|
||||||
this.liveQueryPublisher.onCloudCodeAfterSave(req);
|
this.liveQueryPublisher.onCloudCodeAfterSave(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ export class LiveQueryController {
|
|||||||
if (!this.hasLiveQuery(className)) {
|
if (!this.hasLiveQuery(className)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let req = this._makePublisherRequest(currentObject, originalObject);
|
const req = this._makePublisherRequest(currentObject, originalObject);
|
||||||
this.liveQueryPublisher.onCloudCodeAfterDelete(req);
|
this.liveQueryPublisher.onCloudCodeAfterDelete(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ export class LiveQueryController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_makePublisherRequest(currentObject: any, originalObject: any): any {
|
_makePublisherRequest(currentObject: any, originalObject: any): any {
|
||||||
let req = {
|
const req = {
|
||||||
object: currentObject
|
object: currentObject
|
||||||
};
|
};
|
||||||
if (currentObject) {
|
if (currentObject) {
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ export class LoggerController extends AdaptableController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (e.body) {
|
if (e.body) {
|
||||||
for (let key of Object.keys(e.body)) {
|
for (const key of Object.keys(e.body)) {
|
||||||
if (key === 'password') {
|
if (key === 'password') {
|
||||||
e.body[key] = '********';
|
e.body[key] = '********';
|
||||||
break;
|
break;
|
||||||
@@ -111,12 +111,12 @@ export class LoggerController extends AdaptableController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static parseOptions(options = {}) {
|
static parseOptions(options = {}) {
|
||||||
let from = LoggerController.validDateTime(options.from) ||
|
const from = LoggerController.validDateTime(options.from) ||
|
||||||
new Date(Date.now() - 7 * MILLISECONDS_IN_A_DAY);
|
new Date(Date.now() - 7 * MILLISECONDS_IN_A_DAY);
|
||||||
let until = LoggerController.validDateTime(options.until) || new Date();
|
const until = LoggerController.validDateTime(options.until) || new Date();
|
||||||
let size = Number(options.size) || 10;
|
const size = Number(options.size) || 10;
|
||||||
let order = options.order || LogOrder.DESCENDING;
|
const order = options.order || LogOrder.DESCENDING;
|
||||||
let level = options.level || LogLevel.INFO;
|
const level = options.level || LogLevel.INFO;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
from,
|
from,
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ export class PushController extends AdaptableController {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
if (body.data && body.data.badge) {
|
if (body.data && body.data.badge) {
|
||||||
let badge = body.data.badge;
|
const badge = body.data.badge;
|
||||||
let restUpdate = {};
|
let restUpdate = {};
|
||||||
if (typeof badge == 'string' && badge.toLowerCase() === 'increment') {
|
if (typeof badge == 'string' && badge.toLowerCase() === 'increment') {
|
||||||
restUpdate = { badge: { __op: 'Increment', amount: 1 } }
|
restUpdate = { badge: { __op: 'Increment', amount: 1 } }
|
||||||
@@ -66,20 +66,20 @@ export class PushController extends AdaptableController {
|
|||||||
} else {
|
} else {
|
||||||
throw "Invalid value for badge, expected number or 'Increment'";
|
throw "Invalid value for badge, expected number or 'Increment'";
|
||||||
}
|
}
|
||||||
let updateWhere = deepcopy(where);
|
const updateWhere = deepcopy(where);
|
||||||
|
|
||||||
badgeUpdate = () => {
|
badgeUpdate = () => {
|
||||||
updateWhere.deviceType = 'ios';
|
updateWhere.deviceType = 'ios';
|
||||||
// Build a real RestQuery so we can use it in RestWrite
|
// Build a real RestQuery so we can use it in RestWrite
|
||||||
let restQuery = new RestQuery(config, master(config), '_Installation', updateWhere);
|
const restQuery = new RestQuery(config, master(config), '_Installation', updateWhere);
|
||||||
return restQuery.buildRestWhere().then(() => {
|
return restQuery.buildRestWhere().then(() => {
|
||||||
let write = new RestWrite(config, master(config), '_Installation', restQuery.restWhere, restUpdate);
|
const write = new RestWrite(config, master(config), '_Installation', restQuery.restWhere, restUpdate);
|
||||||
write.runOptions.many = true;
|
write.runOptions.many = true;
|
||||||
return write.execute();
|
return write.execute();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let pushStatus = pushStatusHandler(config);
|
const pushStatus = pushStatusHandler(config);
|
||||||
return Promise.resolve().then(() => {
|
return Promise.resolve().then(() => {
|
||||||
return pushStatus.setInitial(body, where);
|
return pushStatus.setInitial(body, where);
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
@@ -105,7 +105,7 @@ export class PushController extends AdaptableController {
|
|||||||
sendToAdapter(body, installations, pushStatus) {
|
sendToAdapter(body, installations, pushStatus) {
|
||||||
if (body.data && body.data.badge && typeof body.data.badge == 'string' && body.data.badge.toLowerCase() == "increment") {
|
if (body.data && body.data.badge && typeof body.data.badge == 'string' && body.data.badge.toLowerCase() == "increment") {
|
||||||
// Collect the badges to reduce the # of calls
|
// Collect the badges to reduce the # of calls
|
||||||
let badgeInstallationsMap = installations.reduce((map, installation) => {
|
const badgeInstallationsMap = installations.reduce((map, installation) => {
|
||||||
let badge = installation.badge;
|
let badge = installation.badge;
|
||||||
if (installation.deviceType != "ios") {
|
if (installation.deviceType != "ios") {
|
||||||
badge = UNSUPPORTED_BADGE_KEY;
|
badge = UNSUPPORTED_BADGE_KEY;
|
||||||
@@ -116,8 +116,8 @@ export class PushController extends AdaptableController {
|
|||||||
}, {});
|
}, {});
|
||||||
|
|
||||||
// Map the on the badges count and return the send result
|
// Map the on the badges count and return the send result
|
||||||
let promises = Object.keys(badgeInstallationsMap).map((badge) => {
|
const promises = Object.keys(badgeInstallationsMap).map((badge) => {
|
||||||
let payload = deepcopy(body);
|
const payload = deepcopy(body);
|
||||||
if (badge == UNSUPPORTED_BADGE_KEY) {
|
if (badge == UNSUPPORTED_BADGE_KEY) {
|
||||||
delete payload.data.badge;
|
delete payload.data.badge;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export default class SchemaCache {
|
|||||||
if (!allKeys) {
|
if (!allKeys) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let promises = Object.keys(allKeys).map((key) => {
|
const promises = Object.keys(allKeys).map((key) => {
|
||||||
return this.cache.del(key);
|
return this.cache.del(key);
|
||||||
});
|
});
|
||||||
return Promise.all(promises);
|
return Promise.all(promises);
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ const requireAuthenticationRegex = /^requiresAuthentication$/
|
|||||||
const permissionKeyRegex = Object.freeze([userIdRegex, roleRegex, publicRegex, requireAuthenticationRegex]);
|
const permissionKeyRegex = Object.freeze([userIdRegex, roleRegex, publicRegex, requireAuthenticationRegex]);
|
||||||
|
|
||||||
function verifyPermissionKey(key) {
|
function verifyPermissionKey(key) {
|
||||||
let result = permissionKeyRegex.reduce((isGood, regEx) => {
|
const result = permissionKeyRegex.reduce((isGood, regEx) => {
|
||||||
isGood = isGood || key.match(regEx) != null;
|
isGood = isGood || key.match(regEx) != null;
|
||||||
return isGood;
|
return isGood;
|
||||||
}, false);
|
}, false);
|
||||||
@@ -162,7 +162,7 @@ function validateCLP(perms, fields) {
|
|||||||
|
|
||||||
Object.keys(perms[operation]).forEach((key) => {
|
Object.keys(perms[operation]).forEach((key) => {
|
||||||
verifyPermissionKey(key);
|
verifyPermissionKey(key);
|
||||||
let perm = perms[operation][key];
|
const perm = perms[operation][key];
|
||||||
if (perm !== true) {
|
if (perm !== true) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_JSON, `'${perm}' is not a valid value for class level permissions ${operation}:${key}:${perm}`);
|
throw new Parse.Error(Parse.Error.INVALID_JSON, `'${perm}' is not a valid value for class level permissions ${operation}:${key}:${perm}`);
|
||||||
}
|
}
|
||||||
@@ -346,7 +346,7 @@ export default class SchemaController {
|
|||||||
|
|
||||||
// Inject the in-memory classes
|
// Inject the in-memory classes
|
||||||
volatileClasses.forEach(className => {
|
volatileClasses.forEach(className => {
|
||||||
let schema = injectDefaultSchema({ className });
|
const schema = injectDefaultSchema({ className });
|
||||||
this.data[className] = schema.fields;
|
this.data[className] = schema.fields;
|
||||||
this.perms[className] = schema.classLevelPermissions;
|
this.perms[className] = schema.classLevelPermissions;
|
||||||
});
|
});
|
||||||
@@ -439,9 +439,9 @@ export default class SchemaController {
|
|||||||
updateClass(className, submittedFields, classLevelPermissions, database) {
|
updateClass(className, submittedFields, classLevelPermissions, database) {
|
||||||
return this.getOneSchema(className)
|
return this.getOneSchema(className)
|
||||||
.then(schema => {
|
.then(schema => {
|
||||||
let existingFields = schema.fields;
|
const existingFields = schema.fields;
|
||||||
Object.keys(submittedFields).forEach(name => {
|
Object.keys(submittedFields).forEach(name => {
|
||||||
let field = submittedFields[name];
|
const field = submittedFields[name];
|
||||||
if (existingFields[name] && field.__op !== 'Delete') {
|
if (existingFields[name] && field.__op !== 'Delete') {
|
||||||
throw new Parse.Error(255, `Field ${name} exists, cannot update.`);
|
throw new Parse.Error(255, `Field ${name} exists, cannot update.`);
|
||||||
}
|
}
|
||||||
@@ -452,16 +452,16 @@ export default class SchemaController {
|
|||||||
|
|
||||||
delete existingFields._rperm;
|
delete existingFields._rperm;
|
||||||
delete existingFields._wperm;
|
delete existingFields._wperm;
|
||||||
let newSchema = buildMergedSchemaObject(existingFields, submittedFields);
|
const newSchema = buildMergedSchemaObject(existingFields, submittedFields);
|
||||||
let validationError = this.validateSchemaData(className, newSchema, classLevelPermissions, Object.keys(existingFields));
|
const validationError = this.validateSchemaData(className, newSchema, classLevelPermissions, Object.keys(existingFields));
|
||||||
if (validationError) {
|
if (validationError) {
|
||||||
throw new Parse.Error(validationError.code, validationError.error);
|
throw new Parse.Error(validationError.code, validationError.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Finally we have checked to make sure the request is valid and we can start deleting fields.
|
// Finally we have checked to make sure the request is valid and we can start deleting fields.
|
||||||
// Do all deletions first, then a single save to _SCHEMA collection to handle all additions.
|
// Do all deletions first, then a single save to _SCHEMA collection to handle all additions.
|
||||||
let deletePromises = [];
|
const deletePromises = [];
|
||||||
let insertedFields = [];
|
const insertedFields = [];
|
||||||
Object.keys(submittedFields).forEach(fieldName => {
|
Object.keys(submittedFields).forEach(fieldName => {
|
||||||
if (submittedFields[fieldName].__op === 'Delete') {
|
if (submittedFields[fieldName].__op === 'Delete') {
|
||||||
const promise = this.deleteField(fieldName, className, database);
|
const promise = this.deleteField(fieldName, className, database);
|
||||||
@@ -474,7 +474,7 @@ export default class SchemaController {
|
|||||||
return Promise.all(deletePromises) // Delete Everything
|
return Promise.all(deletePromises) // Delete Everything
|
||||||
.then(() => this.reloadData({ clearCache: true })) // Reload our Schema, so we have all the new values
|
.then(() => this.reloadData({ clearCache: true })) // Reload our Schema, so we have all the new values
|
||||||
.then(() => {
|
.then(() => {
|
||||||
let promises = insertedFields.map(fieldName => {
|
const promises = insertedFields.map(fieldName => {
|
||||||
const type = submittedFields[fieldName];
|
const type = submittedFields[fieldName];
|
||||||
return this.enforceFieldExists(className, fieldName, type);
|
return this.enforceFieldExists(className, fieldName, type);
|
||||||
});
|
});
|
||||||
@@ -542,7 +542,7 @@ export default class SchemaController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
validateSchemaData(className, fields, classLevelPermissions, existingFieldNames) {
|
validateSchemaData(className, fields, classLevelPermissions, existingFieldNames) {
|
||||||
for (let fieldName in fields) {
|
for (const fieldName in fields) {
|
||||||
if (existingFieldNames.indexOf(fieldName) < 0) {
|
if (existingFieldNames.indexOf(fieldName) < 0) {
|
||||||
if (!fieldNameIsValid(fieldName)) {
|
if (!fieldNameIsValid(fieldName)) {
|
||||||
return {
|
return {
|
||||||
@@ -561,11 +561,11 @@ export default class SchemaController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (let fieldName in defaultColumns[className]) {
|
for (const fieldName in defaultColumns[className]) {
|
||||||
fields[fieldName] = defaultColumns[className][fieldName];
|
fields[fieldName] = defaultColumns[className][fieldName];
|
||||||
}
|
}
|
||||||
|
|
||||||
let geoPoints = Object.keys(fields).filter(key => fields[key] && fields[key].type === 'GeoPoint');
|
const geoPoints = Object.keys(fields).filter(key => fields[key] && fields[key].type === 'GeoPoint');
|
||||||
if (geoPoints.length > 1) {
|
if (geoPoints.length > 1) {
|
||||||
return {
|
return {
|
||||||
code: Parse.Error.INCORRECT_TYPE,
|
code: Parse.Error.INCORRECT_TYPE,
|
||||||
@@ -605,7 +605,7 @@ export default class SchemaController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return this.reloadData().then(() => {
|
return this.reloadData().then(() => {
|
||||||
let expectedType = this.getExpectedType(className, fieldName);
|
const expectedType = this.getExpectedType(className, fieldName);
|
||||||
if (typeof type === 'string') {
|
if (typeof type === 'string') {
|
||||||
type = { type };
|
type = { type };
|
||||||
}
|
}
|
||||||
@@ -690,11 +690,11 @@ export default class SchemaController {
|
|||||||
validateObject(className, object, query) {
|
validateObject(className, object, query) {
|
||||||
let geocount = 0;
|
let geocount = 0;
|
||||||
let promise = this.enforceClassExists(className);
|
let promise = this.enforceClassExists(className);
|
||||||
for (let fieldName in object) {
|
for (const fieldName in object) {
|
||||||
if (object[fieldName] === undefined) {
|
if (object[fieldName] === undefined) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let expected = getType(object[fieldName]);
|
const expected = getType(object[fieldName]);
|
||||||
if (expected === 'GeoPoint') {
|
if (expected === 'GeoPoint') {
|
||||||
geocount++;
|
geocount++;
|
||||||
}
|
}
|
||||||
@@ -722,12 +722,12 @@ export default class SchemaController {
|
|||||||
|
|
||||||
// Validates that all the properties are set for the object
|
// Validates that all the properties are set for the object
|
||||||
validateRequiredColumns(className, object, query) {
|
validateRequiredColumns(className, object, query) {
|
||||||
let columns = requiredColumns[className];
|
const columns = requiredColumns[className];
|
||||||
if (!columns || columns.length == 0) {
|
if (!columns || columns.length == 0) {
|
||||||
return Promise.resolve(this);
|
return Promise.resolve(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
let missingColumns = columns.filter(function(column){
|
const missingColumns = columns.filter(function(column){
|
||||||
if (query && query.objectId) {
|
if (query && query.objectId) {
|
||||||
if (object[column] && typeof object[column] === "object") {
|
if (object[column] && typeof object[column] === "object") {
|
||||||
// Trying to delete a required column
|
// Trying to delete a required column
|
||||||
@@ -752,8 +752,8 @@ export default class SchemaController {
|
|||||||
if (!this.perms[className] || !this.perms[className][operation]) {
|
if (!this.perms[className] || !this.perms[className][operation]) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
let classPerms = this.perms[className];
|
const classPerms = this.perms[className];
|
||||||
let perms = classPerms[operation];
|
const perms = classPerms[operation];
|
||||||
// Handle the public scenario quickly
|
// Handle the public scenario quickly
|
||||||
if (perms['*']) {
|
if (perms['*']) {
|
||||||
return true;
|
return true;
|
||||||
@@ -774,8 +774,8 @@ export default class SchemaController {
|
|||||||
if (!this.perms[className] || !this.perms[className][operation]) {
|
if (!this.perms[className] || !this.perms[className][operation]) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
let classPerms = this.perms[className];
|
const classPerms = this.perms[className];
|
||||||
let perms = classPerms[operation];
|
const perms = classPerms[operation];
|
||||||
|
|
||||||
// If only for authenticated users
|
// If only for authenticated users
|
||||||
// make sure we have an aclGroup
|
// make sure we have an aclGroup
|
||||||
@@ -797,7 +797,7 @@ export default class SchemaController {
|
|||||||
|
|
||||||
// No matching CLP, let's check the Pointer permissions
|
// No matching CLP, let's check the Pointer permissions
|
||||||
// And handle those later
|
// And handle those later
|
||||||
let permissionField = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields';
|
const permissionField = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields';
|
||||||
|
|
||||||
// Reject create when write lockdown
|
// Reject create when write lockdown
|
||||||
if (permissionField == 'writeUserFields' && operation == 'create') {
|
if (permissionField == 'writeUserFields' && operation == 'create') {
|
||||||
@@ -831,7 +831,7 @@ export default class SchemaController {
|
|||||||
|
|
||||||
// Returns a promise for a new Schema.
|
// Returns a promise for a new Schema.
|
||||||
const load = (dbAdapter, schemaCache, options) => {
|
const load = (dbAdapter, schemaCache, options) => {
|
||||||
let schema = new SchemaController(dbAdapter, schemaCache);
|
const schema = new SchemaController(dbAdapter, schemaCache);
|
||||||
return schema.reloadData(options).then(() => schema);
|
return schema.reloadData(options).then(() => schema);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -841,20 +841,20 @@ const load = (dbAdapter, schemaCache, options) => {
|
|||||||
// to mongoSchemaFromFieldsAndClassName. No validation is done here, it
|
// to mongoSchemaFromFieldsAndClassName. No validation is done here, it
|
||||||
// is done in mongoSchemaFromFieldsAndClassName.
|
// is done in mongoSchemaFromFieldsAndClassName.
|
||||||
function buildMergedSchemaObject(existingFields, putRequest) {
|
function buildMergedSchemaObject(existingFields, putRequest) {
|
||||||
let newSchema = {};
|
const newSchema = {};
|
||||||
let sysSchemaField = Object.keys(defaultColumns).indexOf(existingFields._id) === -1 ? [] : Object.keys(defaultColumns[existingFields._id]);
|
const sysSchemaField = Object.keys(defaultColumns).indexOf(existingFields._id) === -1 ? [] : Object.keys(defaultColumns[existingFields._id]);
|
||||||
for (let oldField in existingFields) {
|
for (const oldField in existingFields) {
|
||||||
if (oldField !== '_id' && oldField !== 'ACL' && oldField !== 'updatedAt' && oldField !== 'createdAt' && oldField !== 'objectId') {
|
if (oldField !== '_id' && oldField !== 'ACL' && oldField !== 'updatedAt' && oldField !== 'createdAt' && oldField !== 'objectId') {
|
||||||
if (sysSchemaField.length > 0 && sysSchemaField.indexOf(oldField) !== -1) {
|
if (sysSchemaField.length > 0 && sysSchemaField.indexOf(oldField) !== -1) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let fieldIsDeleted = putRequest[oldField] && putRequest[oldField].__op === 'Delete'
|
const fieldIsDeleted = putRequest[oldField] && putRequest[oldField].__op === 'Delete'
|
||||||
if (!fieldIsDeleted) {
|
if (!fieldIsDeleted) {
|
||||||
newSchema[oldField] = existingFields[oldField];
|
newSchema[oldField] = existingFields[oldField];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (let newField in putRequest) {
|
for (const newField in putRequest) {
|
||||||
if (newField !== 'objectId' && putRequest[newField].__op !== 'Delete') {
|
if (newField !== 'objectId' && putRequest[newField].__op !== 'Delete') {
|
||||||
if (sysSchemaField.length > 0 && sysSchemaField.indexOf(newField) !== -1) {
|
if (sysSchemaField.length > 0 && sysSchemaField.indexOf(newField) !== -1) {
|
||||||
continue;
|
continue;
|
||||||
@@ -879,7 +879,7 @@ function thenValidateRequiredColumns(schemaPromise, className, object, query) {
|
|||||||
// The output should be a valid schema value.
|
// The output should be a valid schema value.
|
||||||
// TODO: ensure that this is compatible with the format used in Open DB
|
// TODO: ensure that this is compatible with the format used in Open DB
|
||||||
function getType(obj) {
|
function getType(obj) {
|
||||||
let type = typeof obj;
|
const type = typeof obj;
|
||||||
switch(type) {
|
switch(type) {
|
||||||
case 'boolean':
|
case 'boolean':
|
||||||
return 'Boolean';
|
return 'Boolean';
|
||||||
|
|||||||
@@ -48,8 +48,8 @@ export class UserController extends AdaptableController {
|
|||||||
throw undefined;
|
throw undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
let query = {username: username, _email_verify_token: token};
|
const query = {username: username, _email_verify_token: token};
|
||||||
let updateFields = { emailVerified: true, _email_verify_token: {__op: 'Delete'}};
|
const updateFields = { emailVerified: true, _email_verify_token: {__op: 'Delete'}};
|
||||||
|
|
||||||
// if the email verify token needs to be validated then
|
// if the email verify token needs to be validated then
|
||||||
// add additional query params and additional fields that need to be updated
|
// add additional query params and additional fields that need to be updated
|
||||||
@@ -119,8 +119,8 @@ export class UserController extends AdaptableController {
|
|||||||
// We may need to fetch the user in case of update email
|
// We may need to fetch the user in case of update email
|
||||||
this.getUserIfNeeded(user).then((user) => {
|
this.getUserIfNeeded(user).then((user) => {
|
||||||
const username = encodeURIComponent(user.username);
|
const username = encodeURIComponent(user.username);
|
||||||
let link = `${this.config.verifyEmailURL}?token=${token}&username=${username}`;
|
const link = `${this.config.verifyEmailURL}?token=${token}&username=${username}`;
|
||||||
let options = {
|
const options = {
|
||||||
appName: this.config.appName,
|
appName: this.config.appName,
|
||||||
link: link,
|
link: link,
|
||||||
user: inflate('_User', user),
|
user: inflate('_User', user),
|
||||||
@@ -153,9 +153,9 @@ export class UserController extends AdaptableController {
|
|||||||
.then(user => {
|
.then(user => {
|
||||||
const token = encodeURIComponent(user._perishable_token);
|
const token = encodeURIComponent(user._perishable_token);
|
||||||
const username = encodeURIComponent(user.username);
|
const username = encodeURIComponent(user.username);
|
||||||
let link = `${this.config.requestResetPasswordURL}?token=${token}&username=${username}`
|
const link = `${this.config.requestResetPasswordURL}?token=${token}&username=${username}`
|
||||||
|
|
||||||
let options = {
|
const options = {
|
||||||
appName: this.config.appName,
|
appName: this.config.appName,
|
||||||
link: link,
|
link: link,
|
||||||
user: inflate('_User', user),
|
user: inflate('_User', user),
|
||||||
@@ -188,22 +188,22 @@ export class UserController extends AdaptableController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
defaultVerificationEmail({link, user, appName, }) {
|
defaultVerificationEmail({link, user, appName, }) {
|
||||||
let text = "Hi,\n\n" +
|
const text = "Hi,\n\n" +
|
||||||
"You are being asked to confirm the e-mail address " + user.get("email") + " with " + appName + "\n\n" +
|
"You are being asked to confirm the e-mail address " + user.get("email") + " with " + appName + "\n\n" +
|
||||||
"" +
|
"" +
|
||||||
"Click here to confirm it:\n" + link;
|
"Click here to confirm it:\n" + link;
|
||||||
let to = user.get("email");
|
const to = user.get("email");
|
||||||
let subject = 'Please verify your e-mail for ' + appName;
|
const subject = 'Please verify your e-mail for ' + appName;
|
||||||
return { text, to, subject };
|
return { text, to, subject };
|
||||||
}
|
}
|
||||||
|
|
||||||
defaultResetPasswordEmail({link, user, appName, }) {
|
defaultResetPasswordEmail({link, user, appName, }) {
|
||||||
let text = "Hi,\n\n" +
|
const text = "Hi,\n\n" +
|
||||||
"You requested to reset your password for " + appName + ".\n\n" +
|
"You requested to reset your password for " + appName + ".\n\n" +
|
||||||
"" +
|
"" +
|
||||||
"Click here to reset it:\n" + link;
|
"Click here to reset it:\n" + link;
|
||||||
let to = user.get("email") || user.get('username');
|
const to = user.get("email") || user.get('username');
|
||||||
let subject = 'Password Reset for ' + appName;
|
const subject = 'Password Reset for ' + appName;
|
||||||
return { text, to, subject };
|
return { text, to, subject };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import logger from '../logger';
|
|||||||
import type { FlattenedObjectData } from './Subscription';
|
import type { FlattenedObjectData } from './Subscription';
|
||||||
export type Message = { [attr: string]: any };
|
export type Message = { [attr: string]: any };
|
||||||
|
|
||||||
let dafaultFields = ['className', 'objectId', 'updatedAt', 'createdAt', 'ACL'];
|
const dafaultFields = ['className', 'objectId', 'updatedAt', 'createdAt', 'ACL'];
|
||||||
|
|
||||||
class Client {
|
class Client {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -63,7 +63,7 @@ class Client {
|
|||||||
|
|
||||||
_pushEvent(type: string): Function {
|
_pushEvent(type: string): Function {
|
||||||
return function(subscriptionId: number, parseObjectJSON: any): void {
|
return function(subscriptionId: number, parseObjectJSON: any): void {
|
||||||
let response: Message = {
|
const response: Message = {
|
||||||
'op' : type,
|
'op' : type,
|
||||||
'clientId' : this.id
|
'clientId' : this.id
|
||||||
};
|
};
|
||||||
@@ -85,11 +85,11 @@ class Client {
|
|||||||
if (!fields) {
|
if (!fields) {
|
||||||
return parseObjectJSON;
|
return parseObjectJSON;
|
||||||
}
|
}
|
||||||
let limitedParseObject = {};
|
const limitedParseObject = {};
|
||||||
for (let field of dafaultFields) {
|
for (const field of dafaultFields) {
|
||||||
limitedParseObject[field] = parseObjectJSON[field];
|
limitedParseObject[field] = parseObjectJSON[field];
|
||||||
}
|
}
|
||||||
for (let field of fields) {
|
for (const field of fields) {
|
||||||
if (field in parseObjectJSON) {
|
if (field in parseObjectJSON) {
|
||||||
limitedParseObject[field] = parseObjectJSON[field];
|
limitedParseObject[field] = parseObjectJSON[field];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ class ParseCloudCodePublisher {
|
|||||||
_onCloudCodeMessage(type: string, request: any): void {
|
_onCloudCodeMessage(type: string, request: any): void {
|
||||||
logger.verbose('Raw request from cloud code current : %j | original : %j', request.object, request.original);
|
logger.verbose('Raw request from cloud code current : %j | original : %j', request.object, request.original);
|
||||||
// We need the full JSON which includes className
|
// We need the full JSON which includes className
|
||||||
let message = {
|
const message = {
|
||||||
currentParseObject: request.object._toFullJSON()
|
currentParseObject: request.object._toFullJSON()
|
||||||
}
|
}
|
||||||
if (request.original) {
|
if (request.original) {
|
||||||
|
|||||||
@@ -28,9 +28,9 @@ class ParseLiveQueryServer {
|
|||||||
config = config || {};
|
config = config || {};
|
||||||
|
|
||||||
// Store keys, convert obj to map
|
// Store keys, convert obj to map
|
||||||
let keyPairs = config.keyPairs || {};
|
const keyPairs = config.keyPairs || {};
|
||||||
this.keyPairs = new Map();
|
this.keyPairs = new Map();
|
||||||
for (let key of Object.keys(keyPairs)) {
|
for (const key of Object.keys(keyPairs)) {
|
||||||
this.keyPairs.set(key, keyPairs[key]);
|
this.keyPairs.set(key, keyPairs[key]);
|
||||||
}
|
}
|
||||||
logger.verbose('Support key pairs', this.keyPairs);
|
logger.verbose('Support key pairs', this.keyPairs);
|
||||||
@@ -39,11 +39,11 @@ class ParseLiveQueryServer {
|
|||||||
Parse.Object.disableSingleInstance();
|
Parse.Object.disableSingleInstance();
|
||||||
Parse.User.enableUnsafeCurrentUser();
|
Parse.User.enableUnsafeCurrentUser();
|
||||||
|
|
||||||
let serverURL = config.serverURL || Parse.serverURL;
|
const serverURL = config.serverURL || Parse.serverURL;
|
||||||
Parse.serverURL = serverURL;
|
Parse.serverURL = serverURL;
|
||||||
let appId = config.appId || Parse.applicationId;
|
const appId = config.appId || Parse.applicationId;
|
||||||
let javascriptKey = Parse.javaScriptKey;
|
const javascriptKey = Parse.javaScriptKey;
|
||||||
let masterKey = config.masterKey || Parse.masterKey;
|
const masterKey = config.masterKey || Parse.masterKey;
|
||||||
Parse.initialize(appId, javascriptKey, masterKey);
|
Parse.initialize(appId, javascriptKey, masterKey);
|
||||||
|
|
||||||
// Initialize websocket server
|
// Initialize websocket server
|
||||||
@@ -86,13 +86,13 @@ class ParseLiveQueryServer {
|
|||||||
// Message.originalParseObject is the original ParseObject JSON.
|
// Message.originalParseObject is the original ParseObject JSON.
|
||||||
_inflateParseObject(message: any): void {
|
_inflateParseObject(message: any): void {
|
||||||
// Inflate merged object
|
// Inflate merged object
|
||||||
let currentParseObject = message.currentParseObject;
|
const currentParseObject = message.currentParseObject;
|
||||||
let className = currentParseObject.className;
|
let className = currentParseObject.className;
|
||||||
let parseObject = new Parse.Object(className);
|
let parseObject = new Parse.Object(className);
|
||||||
parseObject._finishFetch(currentParseObject);
|
parseObject._finishFetch(currentParseObject);
|
||||||
message.currentParseObject = parseObject;
|
message.currentParseObject = parseObject;
|
||||||
// Inflate original object
|
// Inflate original object
|
||||||
let originalParseObject = message.originalParseObject;
|
const originalParseObject = message.originalParseObject;
|
||||||
if (originalParseObject) {
|
if (originalParseObject) {
|
||||||
className = originalParseObject.className;
|
className = originalParseObject.className;
|
||||||
parseObject = new Parse.Object(className);
|
parseObject = new Parse.Object(className);
|
||||||
@@ -106,28 +106,28 @@ class ParseLiveQueryServer {
|
|||||||
_onAfterDelete(message: any): void {
|
_onAfterDelete(message: any): void {
|
||||||
logger.verbose(Parse.applicationId + 'afterDelete is triggered');
|
logger.verbose(Parse.applicationId + 'afterDelete is triggered');
|
||||||
|
|
||||||
let deletedParseObject = message.currentParseObject.toJSON();
|
const deletedParseObject = message.currentParseObject.toJSON();
|
||||||
let className = deletedParseObject.className;
|
const className = deletedParseObject.className;
|
||||||
logger.verbose('ClassName: %j | ObjectId: %s', className, deletedParseObject.id);
|
logger.verbose('ClassName: %j | ObjectId: %s', className, deletedParseObject.id);
|
||||||
logger.verbose('Current client number : %d', this.clients.size);
|
logger.verbose('Current client number : %d', this.clients.size);
|
||||||
|
|
||||||
let classSubscriptions = this.subscriptions.get(className);
|
const classSubscriptions = this.subscriptions.get(className);
|
||||||
if (typeof classSubscriptions === 'undefined') {
|
if (typeof classSubscriptions === 'undefined') {
|
||||||
logger.debug('Can not find subscriptions under this class ' + className);
|
logger.debug('Can not find subscriptions under this class ' + className);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (let subscription of classSubscriptions.values()) {
|
for (const subscription of classSubscriptions.values()) {
|
||||||
let isSubscriptionMatched = this._matchesSubscription(deletedParseObject, subscription);
|
const isSubscriptionMatched = this._matchesSubscription(deletedParseObject, subscription);
|
||||||
if (!isSubscriptionMatched) {
|
if (!isSubscriptionMatched) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for (let [clientId, requestIds] of _.entries(subscription.clientRequestIds)) {
|
for (const [clientId, requestIds] of _.entries(subscription.clientRequestIds)) {
|
||||||
let client = this.clients.get(clientId);
|
const client = this.clients.get(clientId);
|
||||||
if (typeof client === 'undefined') {
|
if (typeof client === 'undefined') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for (let requestId of requestIds) {
|
for (const requestId of requestIds) {
|
||||||
let acl = message.currentParseObject.getACL();
|
const acl = message.currentParseObject.getACL();
|
||||||
// Check ACL
|
// Check ACL
|
||||||
this._matchesACL(acl, client, requestId).then((isMatched) => {
|
this._matchesACL(acl, client, requestId).then((isMatched) => {
|
||||||
if (!isMatched) {
|
if (!isMatched) {
|
||||||
@@ -151,25 +151,25 @@ class ParseLiveQueryServer {
|
|||||||
if (message.originalParseObject) {
|
if (message.originalParseObject) {
|
||||||
originalParseObject = message.originalParseObject.toJSON();
|
originalParseObject = message.originalParseObject.toJSON();
|
||||||
}
|
}
|
||||||
let currentParseObject = message.currentParseObject.toJSON();
|
const currentParseObject = message.currentParseObject.toJSON();
|
||||||
let className = currentParseObject.className;
|
const className = currentParseObject.className;
|
||||||
logger.verbose('ClassName: %s | ObjectId: %s', className, currentParseObject.id);
|
logger.verbose('ClassName: %s | ObjectId: %s', className, currentParseObject.id);
|
||||||
logger.verbose('Current client number : %d', this.clients.size);
|
logger.verbose('Current client number : %d', this.clients.size);
|
||||||
|
|
||||||
let classSubscriptions = this.subscriptions.get(className);
|
const classSubscriptions = this.subscriptions.get(className);
|
||||||
if (typeof classSubscriptions === 'undefined') {
|
if (typeof classSubscriptions === 'undefined') {
|
||||||
logger.debug('Can not find subscriptions under this class ' + className);
|
logger.debug('Can not find subscriptions under this class ' + className);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (let subscription of classSubscriptions.values()) {
|
for (const subscription of classSubscriptions.values()) {
|
||||||
let isOriginalSubscriptionMatched = this._matchesSubscription(originalParseObject, subscription);
|
const isOriginalSubscriptionMatched = this._matchesSubscription(originalParseObject, subscription);
|
||||||
let isCurrentSubscriptionMatched = this._matchesSubscription(currentParseObject, subscription);
|
const isCurrentSubscriptionMatched = this._matchesSubscription(currentParseObject, subscription);
|
||||||
for (let [clientId, requestIds] of _.entries(subscription.clientRequestIds)) {
|
for (const [clientId, requestIds] of _.entries(subscription.clientRequestIds)) {
|
||||||
let client = this.clients.get(clientId);
|
const client = this.clients.get(clientId);
|
||||||
if (typeof client === 'undefined') {
|
if (typeof client === 'undefined') {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for (let requestId of requestIds) {
|
for (const requestId of requestIds) {
|
||||||
// Set orignal ParseObject ACL checking promise, if the object does not match
|
// Set orignal ParseObject ACL checking promise, if the object does not match
|
||||||
// subscription, we do not need to check ACL
|
// subscription, we do not need to check ACL
|
||||||
let originalACLCheckingPromise;
|
let originalACLCheckingPromise;
|
||||||
@@ -188,7 +188,7 @@ class ParseLiveQueryServer {
|
|||||||
if (!isCurrentSubscriptionMatched) {
|
if (!isCurrentSubscriptionMatched) {
|
||||||
currentACLCheckingPromise = Parse.Promise.as(false);
|
currentACLCheckingPromise = Parse.Promise.as(false);
|
||||||
} else {
|
} else {
|
||||||
let currentACL = message.currentParseObject.getACL();
|
const currentACL = message.currentParseObject.getACL();
|
||||||
currentACLCheckingPromise = this._matchesACL(currentACL, client, requestId);
|
currentACLCheckingPromise = this._matchesACL(currentACL, client, requestId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,7 +221,7 @@ class ParseLiveQueryServer {
|
|||||||
} else {
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
let functionName = 'push' + type;
|
const functionName = 'push' + type;
|
||||||
client[functionName](requestId, currentParseObject);
|
client[functionName](requestId, currentParseObject);
|
||||||
}, (error) => {
|
}, (error) => {
|
||||||
logger.error('Matching ACL error : ', error);
|
logger.error('Matching ACL error : ', error);
|
||||||
@@ -271,23 +271,23 @@ class ParseLiveQueryServer {
|
|||||||
|
|
||||||
parseWebsocket.on('disconnect', () => {
|
parseWebsocket.on('disconnect', () => {
|
||||||
logger.info('Client disconnect: %d', parseWebsocket.clientId);
|
logger.info('Client disconnect: %d', parseWebsocket.clientId);
|
||||||
let clientId = parseWebsocket.clientId;
|
const clientId = parseWebsocket.clientId;
|
||||||
if (!this.clients.has(clientId)) {
|
if (!this.clients.has(clientId)) {
|
||||||
logger.error('Can not find client %d on disconnect', clientId);
|
logger.error('Can not find client %d on disconnect', clientId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete client
|
// Delete client
|
||||||
let client = this.clients.get(clientId);
|
const client = this.clients.get(clientId);
|
||||||
this.clients.delete(clientId);
|
this.clients.delete(clientId);
|
||||||
|
|
||||||
// Delete client from subscriptions
|
// Delete client from subscriptions
|
||||||
for (let [requestId, subscriptionInfo] of _.entries(client.subscriptionInfos)) {
|
for (const [requestId, subscriptionInfo] of _.entries(client.subscriptionInfos)) {
|
||||||
let subscription = subscriptionInfo.subscription;
|
const subscription = subscriptionInfo.subscription;
|
||||||
subscription.deleteClientSubscription(clientId, requestId);
|
subscription.deleteClientSubscription(clientId, requestId);
|
||||||
|
|
||||||
// If there is no client which is subscribing this subscription, remove it from subscriptions
|
// If there is no client which is subscribing this subscription, remove it from subscriptions
|
||||||
let classSubscriptions = this.subscriptions.get(subscription.className);
|
const classSubscriptions = this.subscriptions.get(subscription.className);
|
||||||
if (!subscription.hasSubscribingClient()) {
|
if (!subscription.hasSubscribingClient()) {
|
||||||
classSubscriptions.delete(subscription.hash);
|
classSubscriptions.delete(subscription.hash);
|
||||||
}
|
}
|
||||||
@@ -316,12 +316,12 @@ class ParseLiveQueryServer {
|
|||||||
return Parse.Promise.as(true);
|
return Parse.Promise.as(true);
|
||||||
}
|
}
|
||||||
// Check subscription sessionToken matches ACL first
|
// Check subscription sessionToken matches ACL first
|
||||||
let subscriptionInfo = client.getSubscriptionInfo(requestId);
|
const subscriptionInfo = client.getSubscriptionInfo(requestId);
|
||||||
if (typeof subscriptionInfo === 'undefined') {
|
if (typeof subscriptionInfo === 'undefined') {
|
||||||
return Parse.Promise.as(false);
|
return Parse.Promise.as(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
let subscriptionSessionToken = subscriptionInfo.sessionToken;
|
const subscriptionSessionToken = subscriptionInfo.sessionToken;
|
||||||
return this.sessionTokenCache.getUserId(subscriptionSessionToken).then((userId) => {
|
return this.sessionTokenCache.getUserId(subscriptionSessionToken).then((userId) => {
|
||||||
return acl.getReadAccess(userId);
|
return acl.getReadAccess(userId);
|
||||||
}).then((isSubscriptionSessionTokenMatched) => {
|
}).then((isSubscriptionSessionTokenMatched) => {
|
||||||
@@ -368,7 +368,7 @@ class ParseLiveQueryServer {
|
|||||||
then((roles) => {
|
then((roles) => {
|
||||||
|
|
||||||
// Finally, see if any of the user's roles allow them read access
|
// Finally, see if any of the user's roles allow them read access
|
||||||
for (let role of roles) {
|
for (const role of roles) {
|
||||||
if (acl.getRoleReadAccess(role)) {
|
if (acl.getRoleReadAccess(role)) {
|
||||||
return resolve(true);
|
return resolve(true);
|
||||||
}
|
}
|
||||||
@@ -387,7 +387,7 @@ class ParseLiveQueryServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check client sessionToken matches ACL
|
// Check client sessionToken matches ACL
|
||||||
let clientSessionToken = client.sessionToken;
|
const clientSessionToken = client.sessionToken;
|
||||||
return this.sessionTokenCache.getUserId(clientSessionToken).then((userId) => {
|
return this.sessionTokenCache.getUserId(clientSessionToken).then((userId) => {
|
||||||
return acl.getReadAccess(userId);
|
return acl.getReadAccess(userId);
|
||||||
});
|
});
|
||||||
@@ -404,7 +404,7 @@ class ParseLiveQueryServer {
|
|||||||
logger.error('Key in request is not valid');
|
logger.error('Key in request is not valid');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let client = new Client(this.clientId, parseWebsocket);
|
const client = new Client(this.clientId, parseWebsocket);
|
||||||
parseWebsocket.clientId = this.clientId;
|
parseWebsocket.clientId = this.clientId;
|
||||||
this.clientId += 1;
|
this.clientId += 1;
|
||||||
this.clients.set(parseWebsocket.clientId, client);
|
this.clients.set(parseWebsocket.clientId, client);
|
||||||
@@ -417,7 +417,7 @@ class ParseLiveQueryServer {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
let isValid = false;
|
let isValid = false;
|
||||||
for (let [key, secret] of validKeyPairs) {
|
for (const [key, secret] of validKeyPairs) {
|
||||||
if (!request[key] || request[key] !== secret) {
|
if (!request[key] || request[key] !== secret) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -434,16 +434,16 @@ class ParseLiveQueryServer {
|
|||||||
logger.error('Can not find this client, make sure you connect to server before subscribing');
|
logger.error('Can not find this client, make sure you connect to server before subscribing');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let client = this.clients.get(parseWebsocket.clientId);
|
const client = this.clients.get(parseWebsocket.clientId);
|
||||||
|
|
||||||
// Get subscription from subscriptions, create one if necessary
|
// Get subscription from subscriptions, create one if necessary
|
||||||
let subscriptionHash = queryHash(request.query);
|
const subscriptionHash = queryHash(request.query);
|
||||||
// Add className to subscriptions if necessary
|
// Add className to subscriptions if necessary
|
||||||
let className = request.query.className;
|
const className = request.query.className;
|
||||||
if (!this.subscriptions.has(className)) {
|
if (!this.subscriptions.has(className)) {
|
||||||
this.subscriptions.set(className, new Map());
|
this.subscriptions.set(className, new Map());
|
||||||
}
|
}
|
||||||
let classSubscriptions = this.subscriptions.get(className);
|
const classSubscriptions = this.subscriptions.get(className);
|
||||||
let subscription;
|
let subscription;
|
||||||
if (classSubscriptions.has(subscriptionHash)) {
|
if (classSubscriptions.has(subscriptionHash)) {
|
||||||
subscription = classSubscriptions.get(subscriptionHash);
|
subscription = classSubscriptions.get(subscriptionHash);
|
||||||
@@ -453,7 +453,7 @@ class ParseLiveQueryServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add subscriptionInfo to client
|
// Add subscriptionInfo to client
|
||||||
let subscriptionInfo = {
|
const subscriptionInfo = {
|
||||||
subscription: subscription
|
subscription: subscription
|
||||||
};
|
};
|
||||||
// Add selected fields and sessionToken for this subscription if necessary
|
// Add selected fields and sessionToken for this subscription if necessary
|
||||||
@@ -486,8 +486,8 @@ class ParseLiveQueryServer {
|
|||||||
logger.error('Can not find this client, make sure you connect to server before unsubscribing');
|
logger.error('Can not find this client, make sure you connect to server before unsubscribing');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let requestId = request.requestId;
|
const requestId = request.requestId;
|
||||||
let client = this.clients.get(parseWebsocket.clientId);
|
const client = this.clients.get(parseWebsocket.clientId);
|
||||||
if (typeof client === 'undefined') {
|
if (typeof client === 'undefined') {
|
||||||
Client.pushError(parseWebsocket, 2, 'Cannot find client with clientId ' + parseWebsocket.clientId +
|
Client.pushError(parseWebsocket, 2, 'Cannot find client with clientId ' + parseWebsocket.clientId +
|
||||||
'. Make sure you connect to live query server before unsubscribing.');
|
'. Make sure you connect to live query server before unsubscribing.');
|
||||||
@@ -495,7 +495,7 @@ class ParseLiveQueryServer {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let subscriptionInfo = client.getSubscriptionInfo(requestId);
|
const subscriptionInfo = client.getSubscriptionInfo(requestId);
|
||||||
if (typeof subscriptionInfo === 'undefined') {
|
if (typeof subscriptionInfo === 'undefined') {
|
||||||
Client.pushError(parseWebsocket, 2, 'Cannot find subscription with clientId ' + parseWebsocket.clientId +
|
Client.pushError(parseWebsocket, 2, 'Cannot find subscription with clientId ' + parseWebsocket.clientId +
|
||||||
' subscriptionId ' + requestId + '. Make sure you subscribe to live query server before unsubscribing.');
|
' subscriptionId ' + requestId + '. Make sure you subscribe to live query server before unsubscribing.');
|
||||||
@@ -506,11 +506,11 @@ class ParseLiveQueryServer {
|
|||||||
// Remove subscription from client
|
// Remove subscription from client
|
||||||
client.deleteSubscriptionInfo(requestId);
|
client.deleteSubscriptionInfo(requestId);
|
||||||
// Remove client from subscription
|
// Remove client from subscription
|
||||||
let subscription = subscriptionInfo.subscription;
|
const subscription = subscriptionInfo.subscription;
|
||||||
let className = subscription.className;
|
const className = subscription.className;
|
||||||
subscription.deleteClientSubscription(parseWebsocket.clientId, requestId);
|
subscription.deleteClientSubscription(parseWebsocket.clientId, requestId);
|
||||||
// If there is no client which is subscribing this subscription, remove it from subscriptions
|
// If there is no client which is subscribing this subscription, remove it from subscriptions
|
||||||
let classSubscriptions = this.subscriptions.get(className);
|
const classSubscriptions = this.subscriptions.get(className);
|
||||||
if (!subscription.hasSubscribingClient()) {
|
if (!subscription.hasSubscribingClient()) {
|
||||||
classSubscriptions.delete(subscription.hash);
|
classSubscriptions.delete(subscription.hash);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import {
|
|||||||
RedisPubSub
|
RedisPubSub
|
||||||
} from '../Adapters/PubSub/RedisPubSub';
|
} from '../Adapters/PubSub/RedisPubSub';
|
||||||
|
|
||||||
let ParsePubSub = {};
|
const ParsePubSub = {};
|
||||||
|
|
||||||
function useRedis(config: any): boolean {
|
function useRedis(config: any): boolean {
|
||||||
let redisURL = config.redisURL;
|
const redisURL = config.redisURL;
|
||||||
return typeof redisURL !== 'undefined' && redisURL !== '';
|
return typeof redisURL !== 'undefined' && redisURL !== '';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ ParsePubSub.createPublisher = function(config: any): any {
|
|||||||
if (useRedis(config)) {
|
if (useRedis(config)) {
|
||||||
return RedisPubSub.createPublisher(config);
|
return RedisPubSub.createPublisher(config);
|
||||||
} else {
|
} else {
|
||||||
let adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config)
|
const adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config)
|
||||||
if (typeof adapter.createPublisher !== 'function') {
|
if (typeof adapter.createPublisher !== 'function') {
|
||||||
throw 'pubSubAdapter should have createPublisher()';
|
throw 'pubSubAdapter should have createPublisher()';
|
||||||
}
|
}
|
||||||
@@ -30,7 +30,7 @@ ParsePubSub.createSubscriber = function(config: any): void {
|
|||||||
if (useRedis(config)) {
|
if (useRedis(config)) {
|
||||||
return RedisPubSub.createSubscriber(config);
|
return RedisPubSub.createSubscriber(config);
|
||||||
} else {
|
} else {
|
||||||
let adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config)
|
const adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config)
|
||||||
if (typeof adapter.createSubscriber !== 'function') {
|
if (typeof adapter.createSubscriber !== 'function') {
|
||||||
throw 'pubSubAdapter should have createSubscriber()';
|
throw 'pubSubAdapter should have createSubscriber()';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,20 @@
|
|||||||
import logger from '../logger';
|
import logger from '../logger';
|
||||||
|
|
||||||
let typeMap = new Map([['disconnect', 'close']]);
|
const typeMap = new Map([['disconnect', 'close']]);
|
||||||
|
|
||||||
export class ParseWebSocketServer {
|
export class ParseWebSocketServer {
|
||||||
server: Object;
|
server: Object;
|
||||||
|
|
||||||
constructor(server: any, onConnect: Function, websocketTimeout: number = 10 * 1000) {
|
constructor(server: any, onConnect: Function, websocketTimeout: number = 10 * 1000) {
|
||||||
let WebSocketServer = require('ws').Server;
|
const WebSocketServer = require('ws').Server;
|
||||||
let wss = new WebSocketServer({ server: server });
|
const wss = new WebSocketServer({ server: server });
|
||||||
wss.on('listening', () => {
|
wss.on('listening', () => {
|
||||||
logger.info('Parse LiveQuery Server starts running');
|
logger.info('Parse LiveQuery Server starts running');
|
||||||
});
|
});
|
||||||
wss.on('connection', (ws) => {
|
wss.on('connection', (ws) => {
|
||||||
onConnect(new ParseWebSocket(ws));
|
onConnect(new ParseWebSocket(ws));
|
||||||
// Send ping to client periodically
|
// Send ping to client periodically
|
||||||
let pingIntervalId = setInterval(() => {
|
const pingIntervalId = setInterval(() => {
|
||||||
if (ws.readyState == ws.OPEN) {
|
if (ws.readyState == ws.OPEN) {
|
||||||
ws.ping();
|
ws.ping();
|
||||||
} else {
|
} else {
|
||||||
@@ -34,7 +34,7 @@ export class ParseWebSocket {
|
|||||||
}
|
}
|
||||||
|
|
||||||
on(type: string, callback): void {
|
on(type: string, callback): void {
|
||||||
let wsType = typeMap.has(type) ? typeMap.get(type) : type;
|
const wsType = typeMap.has(type) ? typeMap.get(type) : type;
|
||||||
this.ws.on(wsType, callback);
|
this.ws.on(wsType, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -217,8 +217,8 @@ function matchesKeyConstraints(object, key, constraints) {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case '$exists': {
|
case '$exists': {
|
||||||
let propertyExists = typeof object[key] !== 'undefined';
|
const propertyExists = typeof object[key] !== 'undefined';
|
||||||
let existenceIsRequired = constraints['$exists'];
|
const existenceIsRequired = constraints['$exists'];
|
||||||
if (typeof constraints['$exists'] !== 'boolean') {
|
if (typeof constraints['$exists'] !== 'boolean') {
|
||||||
// The SDK will never submit a non-boolean for $exists, but if someone
|
// The SDK will never submit a non-boolean for $exists, but if someone
|
||||||
// tries to submit a non-boolean for $exits outside the SDKs, just ignore it.
|
// tries to submit a non-boolean for $exits outside the SDKs, just ignore it.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
let general = {
|
const general = {
|
||||||
'title': 'General request schema',
|
'title': 'General request schema',
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -9,7 +9,7 @@ let general = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
let connect = {
|
const connect = {
|
||||||
'title': 'Connect operation schema',
|
'title': 'Connect operation schema',
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -40,7 +40,7 @@ let connect = {
|
|||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
};
|
};
|
||||||
|
|
||||||
let subscribe = {
|
const subscribe = {
|
||||||
'title': 'Subscribe operation schema',
|
'title': 'Subscribe operation schema',
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -78,7 +78,7 @@ let subscribe = {
|
|||||||
'additionalProperties': false
|
'additionalProperties': false
|
||||||
};
|
};
|
||||||
|
|
||||||
let update = {
|
const update = {
|
||||||
'title': 'Update operation schema',
|
'title': 'Update operation schema',
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -116,7 +116,7 @@ let update = {
|
|||||||
'additionalProperties': false
|
'additionalProperties': false
|
||||||
};
|
};
|
||||||
|
|
||||||
let unsubscribe = {
|
const unsubscribe = {
|
||||||
'title': 'Unsubscribe operation schema',
|
'title': 'Unsubscribe operation schema',
|
||||||
'type': 'object',
|
'type': 'object',
|
||||||
'properties': {
|
'properties': {
|
||||||
@@ -129,7 +129,7 @@ let unsubscribe = {
|
|||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
}
|
}
|
||||||
|
|
||||||
let RequestSchema = {
|
const RequestSchema = {
|
||||||
'general': general,
|
'general': general,
|
||||||
'connect': connect,
|
'connect': connect,
|
||||||
'subscribe': subscribe,
|
'subscribe': subscribe,
|
||||||
|
|||||||
@@ -16,14 +16,14 @@ class SessionTokenCache {
|
|||||||
if (!sessionToken) {
|
if (!sessionToken) {
|
||||||
return Parse.Promise.error('Empty sessionToken');
|
return Parse.Promise.error('Empty sessionToken');
|
||||||
}
|
}
|
||||||
let userId = this.cache.get(sessionToken);
|
const userId = this.cache.get(sessionToken);
|
||||||
if (userId) {
|
if (userId) {
|
||||||
logger.verbose('Fetch userId %s of sessionToken %s from Cache', userId, sessionToken);
|
logger.verbose('Fetch userId %s of sessionToken %s from Cache', userId, sessionToken);
|
||||||
return Parse.Promise.as(userId);
|
return Parse.Promise.as(userId);
|
||||||
}
|
}
|
||||||
return Parse.User.become(sessionToken).then((user) => {
|
return Parse.User.become(sessionToken).then((user) => {
|
||||||
logger.verbose('Fetch userId %s of sessionToken %s from Parse', user.id, sessionToken);
|
logger.verbose('Fetch userId %s of sessionToken %s from Parse', user.id, sessionToken);
|
||||||
let userId = user.id;
|
const userId = user.id;
|
||||||
this.cache.set(sessionToken, userId);
|
this.cache.set(sessionToken, userId);
|
||||||
return Parse.Promise.as(userId);
|
return Parse.Promise.as(userId);
|
||||||
}, (error) => {
|
}, (error) => {
|
||||||
|
|||||||
@@ -21,18 +21,18 @@ class Subscription {
|
|||||||
if (!this.clientRequestIds.has(clientId)) {
|
if (!this.clientRequestIds.has(clientId)) {
|
||||||
this.clientRequestIds.set(clientId, []);
|
this.clientRequestIds.set(clientId, []);
|
||||||
}
|
}
|
||||||
let requestIds = this.clientRequestIds.get(clientId);
|
const requestIds = this.clientRequestIds.get(clientId);
|
||||||
requestIds.push(requestId);
|
requestIds.push(requestId);
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteClientSubscription(clientId: number, requestId: number): void {
|
deleteClientSubscription(clientId: number, requestId: number): void {
|
||||||
let requestIds = this.clientRequestIds.get(clientId);
|
const requestIds = this.clientRequestIds.get(clientId);
|
||||||
if (typeof requestIds === 'undefined') {
|
if (typeof requestIds === 'undefined') {
|
||||||
logger.error('Can not find client %d to delete', clientId);
|
logger.error('Can not find client %d to delete', clientId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let index = requestIds.indexOf(requestId);
|
const index = requestIds.indexOf(requestId);
|
||||||
if (index < 0) {
|
if (index < 0) {
|
||||||
logger.error('Can not find client %d subscription %d to delete', clientId, requestId);
|
logger.error('Can not find client %d subscription %d to delete', clientId, requestId);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -307,7 +307,7 @@ class ParseServer {
|
|||||||
api.use(middlewares.allowMethodOverride);
|
api.use(middlewares.allowMethodOverride);
|
||||||
api.use(middlewares.handleParseHeaders);
|
api.use(middlewares.handleParseHeaders);
|
||||||
|
|
||||||
let appRouter = ParseServer.promiseRouter({ appId });
|
const appRouter = ParseServer.promiseRouter({ appId });
|
||||||
api.use(appRouter.expressRouter());
|
api.use(appRouter.expressRouter());
|
||||||
|
|
||||||
api.use(middlewares.handleParseErrors);
|
api.use(middlewares.handleParseErrors);
|
||||||
@@ -332,7 +332,7 @@ class ParseServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static promiseRouter({appId}) {
|
static promiseRouter({appId}) {
|
||||||
let routers = [
|
const routers = [
|
||||||
new ClassesRouter(),
|
new ClassesRouter(),
|
||||||
new UsersRouter(),
|
new UsersRouter(),
|
||||||
new SessionsRouter(),
|
new SessionsRouter(),
|
||||||
@@ -351,11 +351,11 @@ class ParseServer {
|
|||||||
new CloudCodeRouter()
|
new CloudCodeRouter()
|
||||||
];
|
];
|
||||||
|
|
||||||
let routes = routers.reduce((memo, router) => {
|
const routes = routers.reduce((memo, router) => {
|
||||||
return memo.concat(router.routes);
|
return memo.concat(router.routes);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
let appRouter = new PromiseRouter(routes, appId);
|
const appRouter = new PromiseRouter(routes, appId);
|
||||||
|
|
||||||
batch.mountOnto(appRouter);
|
batch.mountOnto(appRouter);
|
||||||
return appRouter;
|
return appRouter;
|
||||||
|
|||||||
@@ -33,10 +33,10 @@ function getAuth(options = {}, config) {
|
|||||||
function ParseServerRESTController(applicationId, router) {
|
function ParseServerRESTController(applicationId, router) {
|
||||||
function handleRequest(method, path, data = {}, options = {}) {
|
function handleRequest(method, path, data = {}, options = {}) {
|
||||||
// Store the arguments, for later use if internal fails
|
// Store the arguments, for later use if internal fails
|
||||||
let args = arguments;
|
const args = arguments;
|
||||||
|
|
||||||
let config = new Config(applicationId);
|
const config = new Config(applicationId);
|
||||||
let serverURL = URL.parse(config.serverURL);
|
const serverURL = URL.parse(config.serverURL);
|
||||||
if (path.indexOf(serverURL.path) === 0) {
|
if (path.indexOf(serverURL.path) === 0) {
|
||||||
path = path.slice(serverURL.path.length, path.length);
|
path = path.slice(serverURL.path.length, path.length);
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,7 @@ function ParseServerRESTController(applicationId, router) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (path === '/batch') {
|
if (path === '/batch') {
|
||||||
let promises = data.requests.map((request) => {
|
const promises = data.requests.map((request) => {
|
||||||
return handleRequest(request.method, request.path, request.body, options).then((response) => {
|
return handleRequest(request.method, request.path, request.body, options).then((response) => {
|
||||||
return Parse.Promise.as({success: response});
|
return Parse.Promise.as({success: response});
|
||||||
}, (error) => {
|
}, (error) => {
|
||||||
@@ -63,7 +63,7 @@ function ParseServerRESTController(applicationId, router) {
|
|||||||
|
|
||||||
return new Parse.Promise((resolve, reject) => {
|
return new Parse.Promise((resolve, reject) => {
|
||||||
getAuth(options, config).then((auth) => {
|
getAuth(options, config).then((auth) => {
|
||||||
let request = {
|
const request = {
|
||||||
body: data,
|
body: data,
|
||||||
config,
|
config,
|
||||||
auth,
|
auth,
|
||||||
|
|||||||
@@ -93,10 +93,10 @@ export default class PromiseRouter {
|
|||||||
if (route.method != method) {
|
if (route.method != method) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let layer = route.layer || new Layer(route.path, null, route.handler);
|
const layer = route.layer || new Layer(route.path, null, route.handler);
|
||||||
let match = layer.match(path);
|
const match = layer.match(path);
|
||||||
if (match) {
|
if (match) {
|
||||||
let params = layer.params;
|
const params = layer.params;
|
||||||
Object.keys(params).forEach((key) => {
|
Object.keys(params).forEach((key) => {
|
||||||
params[key] = validateParameter(key, params[key]);
|
params[key] = validateParameter(key, params[key]);
|
||||||
});
|
});
|
||||||
@@ -108,8 +108,8 @@ export default class PromiseRouter {
|
|||||||
// Mount the routes on this router onto an express app (or express router)
|
// Mount the routes on this router onto an express app (or express router)
|
||||||
mountOnto(expressApp) {
|
mountOnto(expressApp) {
|
||||||
this.routes.forEach((route) => {
|
this.routes.forEach((route) => {
|
||||||
let method = route.method.toLowerCase();
|
const method = route.method.toLowerCase();
|
||||||
let handler = makeExpressHandler(this.appId, route.handler);
|
const handler = makeExpressHandler(this.appId, route.handler);
|
||||||
expressApp[method].call(expressApp, route.path, handler);
|
expressApp[method].call(expressApp, route.path, handler);
|
||||||
});
|
});
|
||||||
return expressApp;
|
return expressApp;
|
||||||
@@ -140,9 +140,9 @@ export default class PromiseRouter {
|
|||||||
function makeExpressHandler(appId, promiseHandler) {
|
function makeExpressHandler(appId, promiseHandler) {
|
||||||
return function(req, res, next) {
|
return function(req, res, next) {
|
||||||
try {
|
try {
|
||||||
let url = maskSensitiveUrl(req);
|
const url = maskSensitiveUrl(req);
|
||||||
let body = Object.assign({}, req.body);
|
const body = Object.assign({}, req.body);
|
||||||
let stringifiedBody = JSON.stringify(body, null, 2);
|
const stringifiedBody = JSON.stringify(body, null, 2);
|
||||||
log.verbose(`REQUEST for [${req.method}] ${url}: ${stringifiedBody}`, {
|
log.verbose(`REQUEST for [${req.method}] ${url}: ${stringifiedBody}`, {
|
||||||
method: req.method,
|
method: req.method,
|
||||||
url: url,
|
url: url,
|
||||||
@@ -155,7 +155,7 @@ function makeExpressHandler(appId, promiseHandler) {
|
|||||||
throw 'control should not get here';
|
throw 'control should not get here';
|
||||||
}
|
}
|
||||||
|
|
||||||
let stringifiedResponse = JSON.stringify(result, null, 2);
|
const stringifiedResponse = JSON.stringify(result, null, 2);
|
||||||
log.verbose(
|
log.verbose(
|
||||||
`RESPONSE from [${req.method}] ${url}: ${stringifiedResponse}`,
|
`RESPONSE from [${req.method}] ${url}: ${stringifiedResponse}`,
|
||||||
{result: result}
|
{result: result}
|
||||||
@@ -198,7 +198,7 @@ function makeExpressHandler(appId, promiseHandler) {
|
|||||||
|
|
||||||
function maskSensitiveUrl(req) {
|
function maskSensitiveUrl(req) {
|
||||||
let maskUrl = req.originalUrl.toString();
|
let maskUrl = req.originalUrl.toString();
|
||||||
let shouldMaskUrl = req.method === 'GET' && req.originalUrl.includes('/login')
|
const shouldMaskUrl = req.method === 'GET' && req.originalUrl.includes('/login')
|
||||||
&& !req.originalUrl.includes('classes');
|
&& !req.originalUrl.includes('classes');
|
||||||
if (shouldMaskUrl) {
|
if (shouldMaskUrl) {
|
||||||
maskUrl = log.maskSensitiveUrl(maskUrl);
|
maskUrl = log.maskSensitiveUrl(maskUrl);
|
||||||
|
|||||||
@@ -252,7 +252,7 @@ RestQuery.prototype.replaceInQuery = function() {
|
|||||||
'improper usage of $inQuery');
|
'improper usage of $inQuery');
|
||||||
}
|
}
|
||||||
|
|
||||||
let additionalOptions = {
|
const additionalOptions = {
|
||||||
redirectClassNameForKey: inQueryValue.redirectClassNameForKey
|
redirectClassNameForKey: inQueryValue.redirectClassNameForKey
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -300,7 +300,7 @@ RestQuery.prototype.replaceNotInQuery = function() {
|
|||||||
'improper usage of $notInQuery');
|
'improper usage of $notInQuery');
|
||||||
}
|
}
|
||||||
|
|
||||||
let additionalOptions = {
|
const additionalOptions = {
|
||||||
redirectClassNameForKey: notInQueryValue.redirectClassNameForKey
|
redirectClassNameForKey: notInQueryValue.redirectClassNameForKey
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -350,7 +350,7 @@ RestQuery.prototype.replaceSelect = function() {
|
|||||||
'improper usage of $select');
|
'improper usage of $select');
|
||||||
}
|
}
|
||||||
|
|
||||||
let additionalOptions = {
|
const additionalOptions = {
|
||||||
redirectClassNameForKey: selectValue.query.redirectClassNameForKey
|
redirectClassNameForKey: selectValue.query.redirectClassNameForKey
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -398,7 +398,7 @@ RestQuery.prototype.replaceDontSelect = function() {
|
|||||||
throw new Parse.Error(Parse.Error.INVALID_QUERY,
|
throw new Parse.Error(Parse.Error.INVALID_QUERY,
|
||||||
'improper usage of $dontSelect');
|
'improper usage of $dontSelect');
|
||||||
}
|
}
|
||||||
let additionalOptions = {
|
const additionalOptions = {
|
||||||
redirectClassNameForKey: dontSelectValue.query.redirectClassNameForKey
|
redirectClassNameForKey: dontSelectValue.query.redirectClassNameForKey
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -445,7 +445,7 @@ RestQuery.prototype.runFind = function(options = {}) {
|
|||||||
this.response = {results: []};
|
this.response = {results: []};
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
let findOptions = Object.assign({}, this.findOptions);
|
const findOptions = Object.assign({}, this.findOptions);
|
||||||
if (this.keys) {
|
if (this.keys) {
|
||||||
findOptions.keys = this.keys.map((key) => {
|
findOptions.keys = this.keys.map((key) => {
|
||||||
return key.split('.')[0];
|
return key.split('.')[0];
|
||||||
@@ -535,23 +535,23 @@ function includePath(config, auth, response, path, restOptions = {}) {
|
|||||||
if (pointers.length == 0) {
|
if (pointers.length == 0) {
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
let pointersHash = {};
|
const pointersHash = {};
|
||||||
for (var pointer of pointers) {
|
for (var pointer of pointers) {
|
||||||
if (!pointer) {
|
if (!pointer) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let className = pointer.className;
|
const className = pointer.className;
|
||||||
// only include the good pointers
|
// only include the good pointers
|
||||||
if (className) {
|
if (className) {
|
||||||
pointersHash[className] = pointersHash[className] || new Set();
|
pointersHash[className] = pointersHash[className] || new Set();
|
||||||
pointersHash[className].add(pointer.objectId);
|
pointersHash[className].add(pointer.objectId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let includeRestOptions = {};
|
const includeRestOptions = {};
|
||||||
if (restOptions.keys) {
|
if (restOptions.keys) {
|
||||||
let keys = new Set(restOptions.keys.split(','));
|
const keys = new Set(restOptions.keys.split(','));
|
||||||
let keySet = Array.from(keys).reduce((set, key) => {
|
const keySet = Array.from(keys).reduce((set, key) => {
|
||||||
let keyPath = key.split('.');
|
const keyPath = key.split('.');
|
||||||
let i=0;
|
let i=0;
|
||||||
for (i; i<path.length; i++) {
|
for (i; i<path.length; i++) {
|
||||||
if (path[i] != keyPath[i]) {
|
if (path[i] != keyPath[i]) {
|
||||||
@@ -568,8 +568,8 @@ function includePath(config, auth, response, path, restOptions = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let queryPromises = Object.keys(pointersHash).map((className) => {
|
const queryPromises = Object.keys(pointersHash).map((className) => {
|
||||||
let where = {'objectId': {'$in': Array.from(pointersHash[className])}};
|
const where = {'objectId': {'$in': Array.from(pointersHash[className])}};
|
||||||
var query = new RestQuery(config, auth, className, where, includeRestOptions);
|
var query = new RestQuery(config, auth, className, where, includeRestOptions);
|
||||||
return query.execute({op: 'get'}).then((results) => {
|
return query.execute({op: 'get'}).then((results) => {
|
||||||
results.className = className;
|
results.className = className;
|
||||||
@@ -682,7 +682,7 @@ function findObjectWithKey(root, key) {
|
|||||||
}
|
}
|
||||||
if (root instanceof Array) {
|
if (root instanceof Array) {
|
||||||
for (var item of root) {
|
for (var item of root) {
|
||||||
let answer = findObjectWithKey(item, key);
|
const answer = findObjectWithKey(item, key);
|
||||||
if (answer) {
|
if (answer) {
|
||||||
return answer;
|
return answer;
|
||||||
}
|
}
|
||||||
@@ -692,7 +692,7 @@ function findObjectWithKey(root, key) {
|
|||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
for (var subkey in root) {
|
for (var subkey in root) {
|
||||||
let answer = findObjectWithKey(root[subkey], key);
|
const answer = findObjectWithKey(root[subkey], key);
|
||||||
if (answer) {
|
if (answer) {
|
||||||
return answer;
|
return answer;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -153,7 +153,7 @@ RestWrite.prototype.runBeforeTrigger = function() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let originalObject = null;
|
let originalObject = null;
|
||||||
let updatedObject = triggers.inflate(extraData, this.originalData);
|
const updatedObject = triggers.inflate(extraData, this.originalData);
|
||||||
if (this.query && this.query.objectId) {
|
if (this.query && this.query.objectId) {
|
||||||
// This is an update for existing object.
|
// This is an update for existing object.
|
||||||
originalObject = triggers.inflate(extraData, this.originalData);
|
originalObject = triggers.inflate(extraData, this.originalData);
|
||||||
@@ -221,7 +221,7 @@ RestWrite.prototype.validateAuthData = function() {
|
|||||||
var authData = this.data.authData;
|
var authData = this.data.authData;
|
||||||
var providers = Object.keys(authData);
|
var providers = Object.keys(authData);
|
||||||
if (providers.length > 0) {
|
if (providers.length > 0) {
|
||||||
let canHandleAuthData = providers.reduce((canHandle, provider) => {
|
const canHandleAuthData = providers.reduce((canHandle, provider) => {
|
||||||
var providerAuthData = authData[provider];
|
var providerAuthData = authData[provider];
|
||||||
var hasToken = (providerAuthData && providerAuthData.id);
|
var hasToken = (providerAuthData && providerAuthData.id);
|
||||||
return canHandle && (hasToken || providerAuthData == null);
|
return canHandle && (hasToken || providerAuthData == null);
|
||||||
@@ -235,11 +235,11 @@ RestWrite.prototype.validateAuthData = function() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
RestWrite.prototype.handleAuthDataValidation = function(authData) {
|
RestWrite.prototype.handleAuthDataValidation = function(authData) {
|
||||||
let validations = Object.keys(authData).map((provider) => {
|
const validations = Object.keys(authData).map((provider) => {
|
||||||
if (authData[provider] === null) {
|
if (authData[provider] === null) {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
let validateAuthData = this.config.authDataManager.getValidatorForProvider(provider);
|
const validateAuthData = this.config.authDataManager.getValidatorForProvider(provider);
|
||||||
if (!validateAuthData) {
|
if (!validateAuthData) {
|
||||||
throw new Parse.Error(Parse.Error.UNSUPPORTED_SERVICE,
|
throw new Parse.Error(Parse.Error.UNSUPPORTED_SERVICE,
|
||||||
'This authentication method is unsupported.');
|
'This authentication method is unsupported.');
|
||||||
@@ -250,13 +250,13 @@ RestWrite.prototype.handleAuthDataValidation = function(authData) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
RestWrite.prototype.findUsersWithAuthData = function(authData) {
|
RestWrite.prototype.findUsersWithAuthData = function(authData) {
|
||||||
let providers = Object.keys(authData);
|
const providers = Object.keys(authData);
|
||||||
let query = providers.reduce((memo, provider) => {
|
const query = providers.reduce((memo, provider) => {
|
||||||
if (!authData[provider]) {
|
if (!authData[provider]) {
|
||||||
return memo;
|
return memo;
|
||||||
}
|
}
|
||||||
let queryKey = `authData.${provider}.id`;
|
const queryKey = `authData.${provider}.id`;
|
||||||
let query = {};
|
const query = {};
|
||||||
query[queryKey] = authData[provider].id;
|
query[queryKey] = authData[provider].id;
|
||||||
memo.push(query);
|
memo.push(query);
|
||||||
return memo;
|
return memo;
|
||||||
@@ -293,16 +293,16 @@ RestWrite.prototype.handleAuthData = function(authData) {
|
|||||||
if (!this.query) {
|
if (!this.query) {
|
||||||
// Login with auth data
|
// Login with auth data
|
||||||
delete results[0].password;
|
delete results[0].password;
|
||||||
let userResult = results[0];
|
const userResult = results[0];
|
||||||
|
|
||||||
// need to set the objectId first otherwise location has trailing undefined
|
// need to set the objectId first otherwise location has trailing undefined
|
||||||
this.data.objectId = userResult.objectId;
|
this.data.objectId = userResult.objectId;
|
||||||
|
|
||||||
// Determine if authData was updated
|
// Determine if authData was updated
|
||||||
let mutatedAuthData = {};
|
const mutatedAuthData = {};
|
||||||
Object.keys(authData).forEach((provider) => {
|
Object.keys(authData).forEach((provider) => {
|
||||||
let providerData = authData[provider];
|
const providerData = authData[provider];
|
||||||
let userAuthData = userResult.authData[provider];
|
const userAuthData = userResult.authData[provider];
|
||||||
if (!_.isEqual(providerData, userAuthData)) {
|
if (!_.isEqual(providerData, userAuthData)) {
|
||||||
mutatedAuthData[provider] = providerData;
|
mutatedAuthData[provider] = providerData;
|
||||||
}
|
}
|
||||||
@@ -489,7 +489,7 @@ RestWrite.prototype._validatePasswordHistory = function() {
|
|||||||
oldPasswords.push(user.password);
|
oldPasswords.push(user.password);
|
||||||
const newPassword = this.data.password;
|
const newPassword = this.data.password;
|
||||||
// compare the new password hash with all old password hashes
|
// compare the new password hash with all old password hashes
|
||||||
let promises = oldPasswords.map(function (hash) {
|
const promises = oldPasswords.map(function (hash) {
|
||||||
return passwordCrypto.compare(newPassword, hash).then((result) => {
|
return passwordCrypto.compare(newPassword, hash).then((result) => {
|
||||||
if (result) // reject if there is a match
|
if (result) // reject if there is a match
|
||||||
return Promise.reject("REPEAT_PASSWORD");
|
return Promise.reject("REPEAT_PASSWORD");
|
||||||
@@ -687,7 +687,7 @@ RestWrite.prototype.handleInstallation = function() {
|
|||||||
var deviceTokenMatches = [];
|
var deviceTokenMatches = [];
|
||||||
|
|
||||||
// Instead of issuing 3 reads, let's do it with one OR.
|
// Instead of issuing 3 reads, let's do it with one OR.
|
||||||
let orQueries = [];
|
const orQueries = [];
|
||||||
if (this.query && this.query.objectId) {
|
if (this.query && this.query.objectId) {
|
||||||
orQueries.push({
|
orQueries.push({
|
||||||
objectId: this.query.objectId
|
objectId: this.query.objectId
|
||||||
@@ -802,7 +802,7 @@ RestWrite.prototype.handleInstallation = function() {
|
|||||||
// Exactly one device token match and it doesn't have an installation
|
// Exactly one device token match and it doesn't have an installation
|
||||||
// ID. This is the one case where we want to merge with the existing
|
// ID. This is the one case where we want to merge with the existing
|
||||||
// object.
|
// object.
|
||||||
let delQuery = {objectId: idMatch.objectId};
|
const delQuery = {objectId: idMatch.objectId};
|
||||||
return this.config.database.destroy('_Installation', delQuery)
|
return this.config.database.destroy('_Installation', delQuery)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
return deviceTokenMatches[0]['objectId'];
|
return deviceTokenMatches[0]['objectId'];
|
||||||
@@ -813,7 +813,7 @@ RestWrite.prototype.handleInstallation = function() {
|
|||||||
// We're setting the device token on an existing installation, so
|
// We're setting the device token on an existing installation, so
|
||||||
// we should try cleaning out old installations that match this
|
// we should try cleaning out old installations that match this
|
||||||
// device token.
|
// device token.
|
||||||
let delQuery = {
|
const delQuery = {
|
||||||
'deviceToken': this.data.deviceToken,
|
'deviceToken': this.data.deviceToken,
|
||||||
};
|
};
|
||||||
// We have a unique install Id, use that to preserve
|
// We have a unique install Id, use that to preserve
|
||||||
@@ -1004,8 +1004,8 @@ RestWrite.prototype.runAfterTrigger = function() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Avoid doing any setup for triggers if there is no 'afterSave' trigger for this class.
|
// Avoid doing any setup for triggers if there is no 'afterSave' trigger for this class.
|
||||||
let hasAfterSaveHook = triggers.triggerExists(this.className, triggers.Types.afterSave, this.config.applicationId);
|
const hasAfterSaveHook = triggers.triggerExists(this.className, triggers.Types.afterSave, this.config.applicationId);
|
||||||
let hasLiveQuery = this.config.liveQueryController.hasLiveQuery(this.className);
|
const hasLiveQuery = this.config.liveQueryController.hasLiveQuery(this.className);
|
||||||
if (!hasAfterSaveHook && !hasLiveQuery) {
|
if (!hasAfterSaveHook && !hasLiveQuery) {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
@@ -1023,7 +1023,7 @@ RestWrite.prototype.runAfterTrigger = function() {
|
|||||||
|
|
||||||
// Build the inflated object, different from beforeSave, originalData is not empty
|
// Build the inflated object, different from beforeSave, originalData is not empty
|
||||||
// since developers can change data in the beforeSave.
|
// since developers can change data in the beforeSave.
|
||||||
let updatedObject = triggers.inflate(extraData, this.originalData);
|
const updatedObject = triggers.inflate(extraData, this.originalData);
|
||||||
updatedObject.set(this.sanitizedData());
|
updatedObject.set(this.sanitizedData());
|
||||||
updatedObject._handleSaveResponse(this.response.response, this.response.status || 200);
|
updatedObject._handleSaveResponse(this.response.response, this.response.status || 200);
|
||||||
|
|
||||||
@@ -1049,7 +1049,7 @@ RestWrite.prototype.objectId = function() {
|
|||||||
|
|
||||||
// Returns a copy of the data and delete bad keys (_auth_data, _hashed_password...)
|
// Returns a copy of the data and delete bad keys (_auth_data, _hashed_password...)
|
||||||
RestWrite.prototype.sanitizedData = function() {
|
RestWrite.prototype.sanitizedData = function() {
|
||||||
let data = Object.keys(this.data).reduce((data, key) => {
|
const data = Object.keys(this.data).reduce((data, key) => {
|
||||||
// Regexp comes from Parse.Object.prototype.validate
|
// Regexp comes from Parse.Object.prototype.validate
|
||||||
if (!(/^[A-Za-z][0-9A-Za-z_]*$/).test(key)) {
|
if (!(/^[A-Za-z][0-9A-Za-z_]*$/).test(key)) {
|
||||||
delete data[key];
|
delete data[key];
|
||||||
@@ -1061,7 +1061,7 @@ RestWrite.prototype.sanitizedData = function() {
|
|||||||
|
|
||||||
RestWrite.prototype.cleanUserAuthData = function() {
|
RestWrite.prototype.cleanUserAuthData = function() {
|
||||||
if (this.response && this.response.response && this.className === '_User') {
|
if (this.response && this.response.response && this.className === '_User') {
|
||||||
let user = this.response.response;
|
const user = this.response.response;
|
||||||
if (user.authData) {
|
if (user.authData) {
|
||||||
Object.keys(user.authData).forEach((provider) => {
|
Object.keys(user.authData).forEach((provider) => {
|
||||||
if (user.authData[provider] === null) {
|
if (user.authData[provider] === null) {
|
||||||
@@ -1079,10 +1079,10 @@ RestWrite.prototype._updateResponseWithData = function(response, data) {
|
|||||||
if (_.isEmpty(this.storage.fieldsChangedByTrigger)) {
|
if (_.isEmpty(this.storage.fieldsChangedByTrigger)) {
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
let clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK);
|
const clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK);
|
||||||
this.storage.fieldsChangedByTrigger.forEach(fieldName => {
|
this.storage.fieldsChangedByTrigger.forEach(fieldName => {
|
||||||
let dataValue = data[fieldName];
|
const dataValue = data[fieldName];
|
||||||
let responseValue = response[fieldName];
|
const responseValue = response[fieldName];
|
||||||
|
|
||||||
response[fieldName] = responseValue || dataValue;
|
response[fieldName] = responseValue || dataValue;
|
||||||
|
|
||||||
|
|||||||
@@ -9,12 +9,12 @@ const ALLOWED_GET_QUERY_KEYS = ['keys', 'include'];
|
|||||||
export class ClassesRouter extends PromiseRouter {
|
export class ClassesRouter extends PromiseRouter {
|
||||||
|
|
||||||
handleFind(req) {
|
handleFind(req) {
|
||||||
let body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query));
|
const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query));
|
||||||
let options = {};
|
const options = {};
|
||||||
let allowConstraints = ['skip', 'limit', 'order', 'count', 'keys',
|
const allowConstraints = ['skip', 'limit', 'order', 'count', 'keys',
|
||||||
'include', 'redirectClassNameForKey', 'where'];
|
'include', 'redirectClassNameForKey', 'where'];
|
||||||
|
|
||||||
for (let key of Object.keys(body)) {
|
for (const key of Object.keys(body)) {
|
||||||
if (allowConstraints.indexOf(key) === -1) {
|
if (allowConstraints.indexOf(key) === -1) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_QUERY, `Invalid parameter for query: ${key}`);
|
throw new Parse.Error(Parse.Error.INVALID_QUERY, `Invalid parameter for query: ${key}`);
|
||||||
}
|
}
|
||||||
@@ -49,7 +49,7 @@ export class ClassesRouter extends PromiseRouter {
|
|||||||
return rest.find(req.config, req.auth, req.params.className, body.where, options, req.info.clientSDK)
|
return rest.find(req.config, req.auth, req.params.className, body.where, options, req.info.clientSDK)
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (response && response.results) {
|
if (response && response.results) {
|
||||||
for (let result of response.results) {
|
for (const result of response.results) {
|
||||||
if (result.sessionToken) {
|
if (result.sessionToken) {
|
||||||
result.sessionToken = req.info.sessionToken || result.sessionToken;
|
result.sessionToken = req.info.sessionToken || result.sessionToken;
|
||||||
}
|
}
|
||||||
@@ -61,10 +61,10 @@ export class ClassesRouter extends PromiseRouter {
|
|||||||
|
|
||||||
// Returns a promise for a {response} object.
|
// Returns a promise for a {response} object.
|
||||||
handleGet(req) {
|
handleGet(req) {
|
||||||
let body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query));
|
const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query));
|
||||||
let options = {};
|
const options = {};
|
||||||
|
|
||||||
for (let key of Object.keys(body)) {
|
for (const key of Object.keys(body)) {
|
||||||
if (ALLOWED_GET_QUERY_KEYS.indexOf(key) === -1) {
|
if (ALLOWED_GET_QUERY_KEYS.indexOf(key) === -1) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'Improper encode of parameter');
|
throw new Parse.Error(Parse.Error.INVALID_QUERY, 'Improper encode of parameter');
|
||||||
}
|
}
|
||||||
@@ -114,8 +114,8 @@ export class ClassesRouter extends PromiseRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static JSONFromQuery(query) {
|
static JSONFromQuery(query) {
|
||||||
let json = {};
|
const json = {};
|
||||||
for (let [key, value] of _.entries(query)) {
|
for (const [key, value] of _.entries(query)) {
|
||||||
try {
|
try {
|
||||||
json[key] = JSON.parse(value);
|
json[key] = JSON.parse(value);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ export class CloudCodeRouter extends PromiseRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static getJobs(req) {
|
static getJobs(req) {
|
||||||
let config = req.config;
|
const config = req.config;
|
||||||
let jobs = triggers.getJobs(config.applicationId) || {};
|
const jobs = triggers.getJobs(config.applicationId) || {};
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
response: Object.keys(jobs).map((jobName) => {
|
response: Object.keys(jobs).map((jobName) => {
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ export class GlobalConfigRouter extends PromiseRouter {
|
|||||||
// If there is no config in the database - return empty config.
|
// If there is no config in the database - return empty config.
|
||||||
return { response: { params: {} } };
|
return { response: { params: {} } };
|
||||||
}
|
}
|
||||||
let globalConfig = results[0];
|
const globalConfig = results[0];
|
||||||
return { response: { params: globalConfig.params } };
|
return { response: { params: globalConfig.params } };
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
updateGlobalConfig(req) {
|
updateGlobalConfig(req) {
|
||||||
let params = req.body.params;
|
const params = req.body.params;
|
||||||
// Transform in dot notation to make sure it works
|
// Transform in dot notation to make sure it works
|
||||||
const update = Object.keys(params).reduce((acc, key) => {
|
const update = Object.keys(params).reduce((acc, key) => {
|
||||||
acc[`params.${key}`] = params[key];
|
acc[`params.${key}`] = params[key];
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import rest from '../rest';
|
|||||||
|
|
||||||
export class InstallationsRouter extends ClassesRouter {
|
export class InstallationsRouter extends ClassesRouter {
|
||||||
handleFind(req) {
|
handleFind(req) {
|
||||||
let body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query));
|
const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query));
|
||||||
var options = {};
|
var options = {};
|
||||||
|
|
||||||
if (body.skip) {
|
if (body.skip) {
|
||||||
|
|||||||
@@ -5,15 +5,15 @@ import path from 'path';
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import qs from 'querystring';
|
import qs from 'querystring';
|
||||||
|
|
||||||
let public_html = path.resolve(__dirname, "../../public_html");
|
const public_html = path.resolve(__dirname, "../../public_html");
|
||||||
let views = path.resolve(__dirname, '../../views');
|
const views = path.resolve(__dirname, '../../views');
|
||||||
|
|
||||||
export class PublicAPIRouter extends PromiseRouter {
|
export class PublicAPIRouter extends PromiseRouter {
|
||||||
|
|
||||||
verifyEmail(req) {
|
verifyEmail(req) {
|
||||||
let { token, username }= req.query;
|
const { token, username } = req.query;
|
||||||
let appId = req.params.appId;
|
const appId = req.params.appId;
|
||||||
let config = new Config(appId);
|
const config = new Config(appId);
|
||||||
|
|
||||||
if (!config.publicServerURL) {
|
if (!config.publicServerURL) {
|
||||||
return this.missingPublicServerURL();
|
return this.missingPublicServerURL();
|
||||||
@@ -23,9 +23,9 @@ export class PublicAPIRouter extends PromiseRouter {
|
|||||||
return this.invalidLink(req);
|
return this.invalidLink(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
let userController = config.userController;
|
const userController = config.userController;
|
||||||
return userController.verifyEmail(username, token).then(() => {
|
return userController.verifyEmail(username, token).then(() => {
|
||||||
let params = qs.stringify({username});
|
const params = qs.stringify({username});
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
status: 302,
|
status: 302,
|
||||||
location: `${config.verifyEmailSuccessURL}?${params}`
|
location: `${config.verifyEmailSuccessURL}?${params}`
|
||||||
@@ -37,7 +37,7 @@ export class PublicAPIRouter extends PromiseRouter {
|
|||||||
|
|
||||||
changePassword(req) {
|
changePassword(req) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let config = new Config(req.query.id);
|
const config = new Config(req.query.id);
|
||||||
if (!config.publicServerURL) {
|
if (!config.publicServerURL) {
|
||||||
return resolve({
|
return resolve({
|
||||||
status: 404,
|
status: 404,
|
||||||
@@ -59,20 +59,20 @@ export class PublicAPIRouter extends PromiseRouter {
|
|||||||
|
|
||||||
requestResetPassword(req) {
|
requestResetPassword(req) {
|
||||||
|
|
||||||
let config = req.config;
|
const config = req.config;
|
||||||
|
|
||||||
if (!config.publicServerURL) {
|
if (!config.publicServerURL) {
|
||||||
return this.missingPublicServerURL();
|
return this.missingPublicServerURL();
|
||||||
}
|
}
|
||||||
|
|
||||||
let { username, token } = req.query;
|
const { username, token } = req.query;
|
||||||
|
|
||||||
if (!username || !token) {
|
if (!username || !token) {
|
||||||
return this.invalidLink(req);
|
return this.invalidLink(req);
|
||||||
}
|
}
|
||||||
|
|
||||||
return config.userController.checkResetTokenValidity(username, token).then(() => {
|
return config.userController.checkResetTokenValidity(username, token).then(() => {
|
||||||
let params = qs.stringify({token, id: config.applicationId, username, app: config.appName, });
|
const params = qs.stringify({token, id: config.applicationId, username, app: config.appName, });
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
status: 302,
|
status: 302,
|
||||||
location: `${config.choosePasswordURL}?${params}`
|
location: `${config.choosePasswordURL}?${params}`
|
||||||
@@ -84,13 +84,13 @@ export class PublicAPIRouter extends PromiseRouter {
|
|||||||
|
|
||||||
resetPassword(req) {
|
resetPassword(req) {
|
||||||
|
|
||||||
let config = req.config;
|
const config = req.config;
|
||||||
|
|
||||||
if (!config.publicServerURL) {
|
if (!config.publicServerURL) {
|
||||||
return this.missingPublicServerURL();
|
return this.missingPublicServerURL();
|
||||||
}
|
}
|
||||||
|
|
||||||
let {
|
const {
|
||||||
username,
|
username,
|
||||||
token,
|
token,
|
||||||
new_password
|
new_password
|
||||||
@@ -101,13 +101,13 @@ export class PublicAPIRouter extends PromiseRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return config.userController.updatePassword(username, token, new_password).then(() => {
|
return config.userController.updatePassword(username, token, new_password).then(() => {
|
||||||
let params = qs.stringify({username: username});
|
const params = qs.stringify({username: username});
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
status: 302,
|
status: 302,
|
||||||
location: `${config.passwordResetSuccessURL}?${params}`
|
location: `${config.passwordResetSuccessURL}?${params}`
|
||||||
});
|
});
|
||||||
}, (err) => {
|
}, (err) => {
|
||||||
let params = qs.stringify({username: username, token: token, id: config.applicationId, error:err, app:config.appName})
|
const params = qs.stringify({username: username, token: token, id: config.applicationId, error:err, app:config.appName})
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
status: 302,
|
status: 302,
|
||||||
location: `${config.choosePasswordURL}?${params}`
|
location: `${config.choosePasswordURL}?${params}`
|
||||||
@@ -153,7 +153,7 @@ export class PublicAPIRouter extends PromiseRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
expressRouter() {
|
expressRouter() {
|
||||||
let router = express.Router();
|
const router = express.Router();
|
||||||
router.use("/apps", express.static(public_html));
|
router.use("/apps", express.static(public_html));
|
||||||
router.use("/", super.expressRouter());
|
router.use("/", super.expressRouter());
|
||||||
return router;
|
return router;
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ export class PushRouter extends PromiseRouter {
|
|||||||
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Push controller is not set');
|
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Push controller is not set');
|
||||||
}
|
}
|
||||||
|
|
||||||
let where = PushRouter.getQueryCondition(req);
|
const where = PushRouter.getQueryCondition(req);
|
||||||
let resolve;
|
let resolve;
|
||||||
let promise = new Promise((_resolve) => {
|
const promise = new Promise((_resolve) => {
|
||||||
resolve = _resolve;
|
resolve = _resolve;
|
||||||
});
|
});
|
||||||
pushController.sendPush(req.body, where, req.config, req.auth, (pushStatusId) => {
|
pushController.sendPush(req.body, where, req.config, req.auth, (pushStatusId) => {
|
||||||
@@ -38,9 +38,9 @@ export class PushRouter extends PromiseRouter {
|
|||||||
* @returns {Object} The query condition, the where field in a query api call
|
* @returns {Object} The query condition, the where field in a query api call
|
||||||
*/
|
*/
|
||||||
static getQueryCondition(req) {
|
static getQueryCondition(req) {
|
||||||
let body = req.body || {};
|
const body = req.body || {};
|
||||||
let hasWhere = typeof body.where !== 'undefined';
|
const hasWhere = typeof body.where !== 'undefined';
|
||||||
let hasChannels = typeof body.channels !== 'undefined';
|
const hasChannels = typeof body.channels !== 'undefined';
|
||||||
|
|
||||||
let where;
|
let where;
|
||||||
if (hasWhere && hasChannels) {
|
if (hasWhere && hasChannels) {
|
||||||
|
|||||||
@@ -55,8 +55,8 @@ function modifySchema(req) {
|
|||||||
return classNameMismatchResponse(req.body.className, req.params.className);
|
return classNameMismatchResponse(req.body.className, req.params.className);
|
||||||
}
|
}
|
||||||
|
|
||||||
let submittedFields = req.body.fields || {};
|
const submittedFields = req.body.fields || {};
|
||||||
let className = req.params.className;
|
const className = req.params.className;
|
||||||
|
|
||||||
return req.config.database.loadSchema({ clearCache: true})
|
return req.config.database.loadSchema({ clearCache: true})
|
||||||
.then(schema => schema.updateClass(className, submittedFields, req.body.classLevelPermissions, req.config.database))
|
.then(schema => schema.updateClass(className, submittedFields, req.body.classLevelPermissions, req.config.database))
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import rest from '../rest';
|
|||||||
import Auth from '../Auth';
|
import Auth from '../Auth';
|
||||||
import passwordCrypto from '../password';
|
import passwordCrypto from '../password';
|
||||||
import RestWrite from '../RestWrite';
|
import RestWrite from '../RestWrite';
|
||||||
let cryptoUtils = require('../cryptoUtils');
|
const cryptoUtils = require('../cryptoUtils');
|
||||||
|
|
||||||
export class UsersRouter extends ClassesRouter {
|
export class UsersRouter extends ClassesRouter {
|
||||||
handleFind(req) {
|
handleFind(req) {
|
||||||
@@ -23,7 +23,7 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleCreate(req) {
|
handleCreate(req) {
|
||||||
let data = deepcopy(req.body);
|
const data = deepcopy(req.body);
|
||||||
req.body = data;
|
req.body = data;
|
||||||
req.params.className = '_User';
|
req.params.className = '_User';
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
if (!req.info || !req.info.sessionToken) {
|
if (!req.info || !req.info.sessionToken) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token');
|
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token');
|
||||||
}
|
}
|
||||||
let sessionToken = req.info.sessionToken;
|
const sessionToken = req.info.sessionToken;
|
||||||
return rest.find(req.config, Auth.master(req.config), '_Session',
|
return rest.find(req.config, Auth.master(req.config), '_Session',
|
||||||
{ sessionToken },
|
{ sessionToken },
|
||||||
{ include: 'user' }, req.info.clientSDK)
|
{ include: 'user' }, req.info.clientSDK)
|
||||||
@@ -54,7 +54,7 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
!response.results[0].user) {
|
!response.results[0].user) {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token');
|
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token');
|
||||||
} else {
|
} else {
|
||||||
let user = response.results[0].user;
|
const user = response.results[0].user;
|
||||||
// Send token back on the login, because SDKs expect that.
|
// Send token back on the login, because SDKs expect that.
|
||||||
user.sessionToken = sessionToken;
|
user.sessionToken = sessionToken;
|
||||||
return { response: user };
|
return { response: user };
|
||||||
@@ -96,7 +96,7 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
})
|
})
|
||||||
.then((correct) => {
|
.then((correct) => {
|
||||||
isValidPassword = correct;
|
isValidPassword = correct;
|
||||||
let accountLockoutPolicy = new AccountLockout(user, req.config);
|
const accountLockoutPolicy = new AccountLockout(user, req.config);
|
||||||
return accountLockoutPolicy.handleLoginAttempt(isValidPassword);
|
return accountLockoutPolicy.handleLoginAttempt(isValidPassword);
|
||||||
})
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
@@ -126,7 +126,7 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let token = 'r:' + cryptoUtils.newToken();
|
const token = 'r:' + cryptoUtils.newToken();
|
||||||
user.sessionToken = token;
|
user.sessionToken = token;
|
||||||
delete user.password;
|
delete user.password;
|
||||||
|
|
||||||
@@ -145,8 +145,8 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
|
|
||||||
req.config.filesController.expandFilesInObject(req.config, user);
|
req.config.filesController.expandFilesInObject(req.config, user);
|
||||||
|
|
||||||
let expiresAt = req.config.generateSessionExpiresAt();
|
const expiresAt = req.config.generateSessionExpiresAt();
|
||||||
let sessionData = {
|
const sessionData = {
|
||||||
sessionToken: token,
|
sessionToken: token,
|
||||||
user: {
|
user: {
|
||||||
__type: 'Pointer',
|
__type: 'Pointer',
|
||||||
@@ -165,7 +165,7 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
sessionData.installationId = req.info.installationId
|
sessionData.installationId = req.info.installationId
|
||||||
}
|
}
|
||||||
|
|
||||||
let create = new RestWrite(req.config, Auth.master(req.config), '_Session', null, sessionData);
|
const create = new RestWrite(req.config, Auth.master(req.config), '_Session', null, sessionData);
|
||||||
return create.execute();
|
return create.execute();
|
||||||
}).then(() => {
|
}).then(() => {
|
||||||
return { response: user };
|
return { response: user };
|
||||||
@@ -173,7 +173,7 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleLogOut(req) {
|
handleLogOut(req) {
|
||||||
let success = {response: {}};
|
const success = {response: {}};
|
||||||
if (req.info && req.info.sessionToken) {
|
if (req.info && req.info.sessionToken) {
|
||||||
return rest.find(req.config, Auth.master(req.config), '_Session',
|
return rest.find(req.config, Auth.master(req.config), '_Session',
|
||||||
{ sessionToken: req.info.sessionToken }, undefined, req.info.clientSDK
|
{ sessionToken: req.info.sessionToken }, undefined, req.info.clientSDK
|
||||||
@@ -207,14 +207,14 @@ export class UsersRouter extends ClassesRouter {
|
|||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let { email } = req.body;
|
const { email } = req.body;
|
||||||
if (!email) {
|
if (!email) {
|
||||||
throw new Parse.Error(Parse.Error.EMAIL_MISSING, "you must provide an email");
|
throw new Parse.Error(Parse.Error.EMAIL_MISSING, "you must provide an email");
|
||||||
}
|
}
|
||||||
if (typeof email !== 'string') {
|
if (typeof email !== 'string') {
|
||||||
throw new Parse.Error(Parse.Error.INVALID_EMAIL_ADDRESS, 'you must provide a valid email string');
|
throw new Parse.Error(Parse.Error.INVALID_EMAIL_ADDRESS, 'you must provide a valid email string');
|
||||||
}
|
}
|
||||||
let userController = req.config.userController;
|
const userController = req.config.userController;
|
||||||
return userController.sendPasswordResetEmail(email).then(() => {
|
return userController.sendPasswordResetEmail(email).then(() => {
|
||||||
return Promise.resolve({
|
return Promise.resolve({
|
||||||
response: {}
|
response: {}
|
||||||
|
|||||||
@@ -42,11 +42,11 @@ function statusHandler(className, database) {
|
|||||||
|
|
||||||
export function jobStatusHandler(config) {
|
export function jobStatusHandler(config) {
|
||||||
let jobStatus;
|
let jobStatus;
|
||||||
let objectId = newObjectId();
|
const objectId = newObjectId();
|
||||||
let database = config.database;
|
const database = config.database;
|
||||||
let handler = statusHandler(JOB_STATUS_COLLECTION, database);
|
const handler = statusHandler(JOB_STATUS_COLLECTION, database);
|
||||||
let setRunning = function(jobName, params) {
|
const setRunning = function(jobName, params) {
|
||||||
let now = new Date();
|
const now = new Date();
|
||||||
jobStatus = {
|
jobStatus = {
|
||||||
objectId,
|
objectId,
|
||||||
jobName,
|
jobName,
|
||||||
@@ -61,24 +61,24 @@ export function jobStatusHandler(config) {
|
|||||||
return handler.create(jobStatus);
|
return handler.create(jobStatus);
|
||||||
}
|
}
|
||||||
|
|
||||||
let setMessage = function(message) {
|
const setMessage = function(message) {
|
||||||
if (!message || typeof message !== 'string') {
|
if (!message || typeof message !== 'string') {
|
||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
return handler.update({ objectId }, { message });
|
return handler.update({ objectId }, { message });
|
||||||
}
|
}
|
||||||
|
|
||||||
let setSucceeded = function(message) {
|
const setSucceeded = function(message) {
|
||||||
return setFinalStatus('succeeded', message);
|
return setFinalStatus('succeeded', message);
|
||||||
}
|
}
|
||||||
|
|
||||||
let setFailed = function(message) {
|
const setFailed = function(message) {
|
||||||
return setFinalStatus('failed', message);
|
return setFinalStatus('failed', message);
|
||||||
}
|
}
|
||||||
|
|
||||||
let setFinalStatus = function(status, message = undefined) {
|
const setFinalStatus = function(status, message = undefined) {
|
||||||
let finishedAt = new Date();
|
const finishedAt = new Date();
|
||||||
let update = { status, finishedAt };
|
const update = { status, finishedAt };
|
||||||
if (message && typeof message === 'string') {
|
if (message && typeof message === 'string') {
|
||||||
update.message = message;
|
update.message = message;
|
||||||
}
|
}
|
||||||
@@ -96,13 +96,13 @@ export function jobStatusHandler(config) {
|
|||||||
export function pushStatusHandler(config) {
|
export function pushStatusHandler(config) {
|
||||||
|
|
||||||
let pushStatus;
|
let pushStatus;
|
||||||
let objectId = newObjectId();
|
const objectId = newObjectId();
|
||||||
let database = config.database;
|
const database = config.database;
|
||||||
let handler = statusHandler(PUSH_STATUS_COLLECTION, database);
|
const handler = statusHandler(PUSH_STATUS_COLLECTION, database);
|
||||||
let setInitial = function(body = {}, where, options = {source: 'rest'}) {
|
const setInitial = function(body = {}, where, options = {source: 'rest'}) {
|
||||||
let now = new Date();
|
const now = new Date();
|
||||||
let data = body.data || {};
|
const data = body.data || {};
|
||||||
let payloadString = JSON.stringify(data);
|
const payloadString = JSON.stringify(data);
|
||||||
let pushHash;
|
let pushHash;
|
||||||
if (typeof data.alert === 'string') {
|
if (typeof data.alert === 'string') {
|
||||||
pushHash = md5Hash(data.alert);
|
pushHash = md5Hash(data.alert);
|
||||||
@@ -111,7 +111,7 @@ export function pushStatusHandler(config) {
|
|||||||
} else {
|
} else {
|
||||||
pushHash = 'd41d8cd98f00b204e9800998ecf8427e';
|
pushHash = 'd41d8cd98f00b204e9800998ecf8427e';
|
||||||
}
|
}
|
||||||
let object = {
|
const object = {
|
||||||
objectId,
|
objectId,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
pushTime: now.toISOString(),
|
pushTime: now.toISOString(),
|
||||||
@@ -135,14 +135,14 @@ export function pushStatusHandler(config) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let setRunning = function(installations) {
|
const setRunning = function(installations) {
|
||||||
logger.verbose('sending push to %d installations', installations.length);
|
logger.verbose('sending push to %d installations', installations.length);
|
||||||
return handler.update({status:"pending", objectId: objectId},
|
return handler.update({status:"pending", objectId: objectId},
|
||||||
{status: "running", updatedAt: new Date() });
|
{status: "running", updatedAt: new Date() });
|
||||||
}
|
}
|
||||||
|
|
||||||
let complete = function(results) {
|
const complete = function(results) {
|
||||||
let update = {
|
const update = {
|
||||||
status: 'succeeded',
|
status: 'succeeded',
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
numSent: 0,
|
numSent: 0,
|
||||||
@@ -155,7 +155,7 @@ export function pushStatusHandler(config) {
|
|||||||
if (!result || !result.device || !result.device.deviceType) {
|
if (!result || !result.device || !result.device.deviceType) {
|
||||||
return memo;
|
return memo;
|
||||||
}
|
}
|
||||||
let deviceType = result.device.deviceType;
|
const deviceType = result.device.deviceType;
|
||||||
if (result.transmitted)
|
if (result.transmitted)
|
||||||
{
|
{
|
||||||
memo.numSent++;
|
memo.numSent++;
|
||||||
@@ -175,8 +175,8 @@ export function pushStatusHandler(config) {
|
|||||||
return handler.update({status:"running", objectId }, update);
|
return handler.update({status:"running", objectId }, update);
|
||||||
}
|
}
|
||||||
|
|
||||||
let fail = function(err) {
|
const fail = function(err) {
|
||||||
let update = {
|
const update = {
|
||||||
errorMessage: JSON.stringify(err),
|
errorMessage: JSON.stringify(err),
|
||||||
status: 'failed',
|
status: 'failed',
|
||||||
updatedAt: new Date()
|
updatedAt: new Date()
|
||||||
|
|||||||
10
src/batch.js
10
src/batch.js
@@ -22,10 +22,10 @@ function makeBatchRoutingPathFunction(originalUrl, serverURL, publicServerURL) {
|
|||||||
serverURL = serverURL ? parseURL(serverURL) : undefined;
|
serverURL = serverURL ? parseURL(serverURL) : undefined;
|
||||||
publicServerURL = publicServerURL ? parseURL(publicServerURL): undefined;
|
publicServerURL = publicServerURL ? parseURL(publicServerURL): undefined;
|
||||||
|
|
||||||
let apiPrefixLength = originalUrl.length - batchPath.length;
|
const apiPrefixLength = originalUrl.length - batchPath.length;
|
||||||
let apiPrefix = originalUrl.slice(0, apiPrefixLength);
|
let apiPrefix = originalUrl.slice(0, apiPrefixLength);
|
||||||
|
|
||||||
let makeRoutablePath = function(requestPath) {
|
const makeRoutablePath = function(requestPath) {
|
||||||
// The routablePath is the path minus the api prefix
|
// The routablePath is the path minus the api prefix
|
||||||
if (requestPath.slice(0, apiPrefix.length) != apiPrefix) {
|
if (requestPath.slice(0, apiPrefix.length) != apiPrefix) {
|
||||||
throw new Parse.Error(
|
throw new Parse.Error(
|
||||||
@@ -37,14 +37,14 @@ function makeBatchRoutingPathFunction(originalUrl, serverURL, publicServerURL) {
|
|||||||
|
|
||||||
if (serverURL && publicServerURL
|
if (serverURL && publicServerURL
|
||||||
&& (serverURL.path != publicServerURL.path)) {
|
&& (serverURL.path != publicServerURL.path)) {
|
||||||
let localPath = serverURL.path;
|
const localPath = serverURL.path;
|
||||||
let publicPath = publicServerURL.path;
|
const publicPath = publicServerURL.path;
|
||||||
// Override the api prefix
|
// Override the api prefix
|
||||||
apiPrefix = localPath;
|
apiPrefix = localPath;
|
||||||
return function(requestPath) {
|
return function(requestPath) {
|
||||||
// Build the new path by removing the public path
|
// Build the new path by removing the public path
|
||||||
// and joining with the local path
|
// and joining with the local path
|
||||||
let newPath = path.posix.join('/', localPath, '/' , requestPath.slice(publicPath.length));
|
const newPath = path.posix.join('/', localPath, '/' , requestPath.slice(publicPath.length));
|
||||||
// Use the method for local routing
|
// Use the method for local routing
|
||||||
return makeRoutablePath(newPath);
|
return makeRoutablePath(newPath);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ function startServer(options, callback) {
|
|||||||
|
|
||||||
app.use(options.mountPath, api);
|
app.use(options.mountPath, api);
|
||||||
|
|
||||||
let server = app.listen(options.port, options.host, callback);
|
const server = app.listen(options.port, options.host, callback);
|
||||||
server.on('connection', initializeConnections);
|
server.on('connection', initializeConnections);
|
||||||
|
|
||||||
if (options.startLiveQueryServer || options.liveQueryServerOptions) {
|
if (options.startLiveQueryServer || options.liveQueryServerOptions) {
|
||||||
@@ -69,7 +69,7 @@ function startServer(options, callback) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let handleShutdown = function() {
|
const handleShutdown = function() {
|
||||||
console.log('Termination signal received. Shutting down.');
|
console.log('Termination signal received. Shutting down.');
|
||||||
destroyAliveConnections();
|
destroyAliveConnections();
|
||||||
server.close(function () {
|
server.close(function () {
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ function parseConfigFile(program) {
|
|||||||
if (program.args.length > 0) {
|
if (program.args.length > 0) {
|
||||||
let jsonPath = program.args[0];
|
let jsonPath = program.args[0];
|
||||||
jsonPath = path.resolve(jsonPath);
|
jsonPath = path.resolve(jsonPath);
|
||||||
let jsonConfig = require(jsonPath);
|
const jsonConfig = require(jsonPath);
|
||||||
if (jsonConfig.apps) {
|
if (jsonConfig.apps) {
|
||||||
if (jsonConfig.apps.length > 1) {
|
if (jsonConfig.apps.length > 1) {
|
||||||
throw 'Multiple apps are not supported';
|
throw 'Multiple apps are not supported';
|
||||||
@@ -78,11 +78,11 @@ function parseConfigFile(program) {
|
|||||||
options = jsonConfig;
|
options = jsonConfig;
|
||||||
}
|
}
|
||||||
Object.keys(options).forEach((key) => {
|
Object.keys(options).forEach((key) => {
|
||||||
let value = options[key];
|
const value = options[key];
|
||||||
if (!_definitions[key]) {
|
if (!_definitions[key]) {
|
||||||
throw `error: unknown option ${key}`;
|
throw `error: unknown option ${key}`;
|
||||||
}
|
}
|
||||||
let action = _definitions[key].action;
|
const action = _definitions[key].action;
|
||||||
if (action) {
|
if (action) {
|
||||||
options[key] = action(value);
|
options[key] = action(value);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import program from './commander';
|
import program from './commander';
|
||||||
|
|
||||||
function logStartupOptions(options) {
|
function logStartupOptions(options) {
|
||||||
for (let key in options) {
|
for (const key in options) {
|
||||||
let value = options[key];
|
let value = options[key];
|
||||||
if (key == "masterKey") {
|
if (key == "masterKey") {
|
||||||
value = "***REDACTED***";
|
value = "***REDACTED***";
|
||||||
@@ -31,7 +31,7 @@ export default function({
|
|||||||
}
|
}
|
||||||
program.parse(process.argv, process.env);
|
program.parse(process.argv, process.env);
|
||||||
|
|
||||||
let options = program.getOptions();
|
const options = program.getOptions();
|
||||||
start(program, options, function() {
|
start(program, options, function() {
|
||||||
logStartupOptions(options);
|
logStartupOptions(options);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export default class HTTPResponse {
|
|||||||
_data = body;
|
_data = body;
|
||||||
}
|
}
|
||||||
|
|
||||||
let getText = () => {
|
const getText = () => {
|
||||||
if (!_text && this.buffer) {
|
if (!_text && this.buffer) {
|
||||||
_text = this.buffer.toString('utf-8');
|
_text = this.buffer.toString('utf-8');
|
||||||
} else if (!_text && _data) {
|
} else if (!_text && _data) {
|
||||||
@@ -23,7 +23,7 @@ export default class HTTPResponse {
|
|||||||
return _text;
|
return _text;
|
||||||
}
|
}
|
||||||
|
|
||||||
let getData = () => {
|
const getData = () => {
|
||||||
if (!_data) {
|
if (!_data) {
|
||||||
try {
|
try {
|
||||||
_data = JSON.parse(getText());
|
_data = JSON.parse(getText());
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ module.exports = function(options) {
|
|||||||
}
|
}
|
||||||
return promise.reject(error);
|
return promise.reject(error);
|
||||||
}
|
}
|
||||||
let httpResponse = new HTTPResponse(response, body);
|
const httpResponse = new HTTPResponse(response, body);
|
||||||
|
|
||||||
// Consider <200 && >= 400 as errors
|
// Consider <200 && >= 400 as errors
|
||||||
if (httpResponse.status < 200 || httpResponse.status >= 400) {
|
if (httpResponse.status < 200 || httpResponse.status >= 400) {
|
||||||
|
|||||||
@@ -23,11 +23,11 @@ export function randomString(size: number): string {
|
|||||||
if (size === 0) {
|
if (size === 0) {
|
||||||
throw new Error('Zero-length randomString is useless.');
|
throw new Error('Zero-length randomString is useless.');
|
||||||
}
|
}
|
||||||
let chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
|
const chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
|
||||||
'abcdefghijklmnopqrstuvwxyz' +
|
'abcdefghijklmnopqrstuvwxyz' +
|
||||||
'0123456789');
|
'0123456789');
|
||||||
let objectId = '';
|
let objectId = '';
|
||||||
let bytes = randomBytes(size);
|
const bytes = randomBytes(size);
|
||||||
for (let i = 0; i < bytes.length; ++i) {
|
for (let i = 0; i < bytes.length; ++i) {
|
||||||
objectId += chars[bytes.readUInt8(i) % chars.length];
|
objectId += chars[bytes.readUInt8(i) % chars.length];
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user