Update parse SDK to 2.0.0 (#4925)

* WIP: Integrate JS SDK v2

- Removes backbone style callbacks
- Use Promise instead of Parse.Promise

* Fixes ParseObject and ParseRelation

* Updates Parse.Query with promises

* Alls tests should pass

* Ensure a fresh user is used for each test

* Use REST implementation to avoid side effects for username/email duplicates

* Uses js sdk v2
This commit is contained in:
Florent Vilmart
2018-08-05 13:58:07 -04:00
committed by GitHub
parent a61ef7ee2f
commit ff25ae254d
30 changed files with 3217 additions and 4783 deletions

46
package-lock.json generated
View File

@@ -212,6 +212,28 @@
"apn": "^3.0.0-alpha1",
"npmlog": "^4.0.2",
"parse": "^1.9.2"
},
"dependencies": {
"parse": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/parse/-/parse-1.11.1.tgz",
"integrity": "sha1-VY5TnULZ+4khDggiCdbzsD1frtU=",
"requires": {
"babel-runtime": "^6.11.6",
"ws": "^3.3.1",
"xmlhttprequest": "^1.7.0"
}
},
"ws": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-3.3.3.tgz",
"integrity": "sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA==",
"requires": {
"async-limiter": "~1.0.0",
"safe-buffer": "~5.1.0",
"ultron": "~1.1.0"
}
}
}
},
"@parse/s3-files-adapter": {
@@ -9859,25 +9881,13 @@
"integrity": "sha1-zWLmCvjX/qinBexP+ZCHHEaHHyc="
},
"parse": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/parse/-/parse-1.11.1.tgz",
"integrity": "sha1-VY5TnULZ+4khDggiCdbzsD1frtU=",
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/parse/-/parse-2.0.0.tgz",
"integrity": "sha512-YOpOkMXaJZfpzoSS+Jn3XxvdwS3lHlWk4GNi4Hawt2PoyZHT1/gSG4odKadfkvF05TyBtuY7AMzKruvtK/RfVw==",
"requires": {
"babel-runtime": "^6.11.6",
"ws": "^3.3.1",
"xmlhttprequest": "^1.7.0"
},
"dependencies": {
"ws": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-3.3.3.tgz",
"integrity": "sha512-nnWLa/NwZSt4KQJu51MYlCcSQ5g7INpOrOMt4XV8j4dqTXdmlUmSHQ8/oLC069ckre0fRsgfvsKwbTdtKLCDkA==",
"requires": {
"async-limiter": "~1.0.0",
"safe-buffer": "~5.1.0",
"ultron": "~1.1.0"
}
}
"babel-runtime": "6.26.0",
"ws": "6.0.0",
"xmlhttprequest": "1.8.0"
}
},
"parse-glob": {

View File

@@ -33,7 +33,7 @@
"lru-cache": "4.1.2",
"mime": "2.3.1",
"mongodb": "3.1.1",
"parse": "1.11.1",
"parse": "2.0.0",
"pg-promise": "8.4.5",
"redis": "2.8.0",
"request": "2.85.0",

View File

@@ -20,9 +20,7 @@
"describe_only": true,
"on_db": true,
"defaultConfiguration": true,
"expectSuccess": true,
"range": true,
"expectError": true,
"jequal": true,
"create": true,
"arrayContains": true

View File

@@ -120,7 +120,7 @@ describe('AuthenticationProviders', function() {
}
expect(res.get("installationId")).toEqual('yolo');
done();
}).fail(() => {
}).catch(() => {
fail('should not fail fetching the session');
done();
})
@@ -163,67 +163,43 @@ describe('AuthenticationProviders', function() {
}).catch(done.fail);
});
it("unlink and link with custom provider", (done) => {
it("unlink and link with custom provider", async () => {
const provider = getMockMyOauthProvider();
Parse.User._registerAuthenticationProvider(provider);
Parse.User._logInWith("myoauth", {
success: function(model) {
ok(model instanceof Parse.User, "Model should be a Parse.User");
strictEqual(Parse.User.current(), model);
ok(model.extended(), "Should have used the subclass.");
strictEqual(provider.authData.id, provider.synchronizedUserId);
strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);
strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);
ok(model._isLinked("myoauth"), "User should be linked to myoauth");
const model = await Parse.User._logInWith("myoauth");
ok(model instanceof Parse.User, "Model should be a Parse.User");
strictEqual(Parse.User.current(), model);
ok(model.extended(), "Should have used the subclass.");
strictEqual(provider.authData.id, provider.synchronizedUserId);
strictEqual(provider.authData.access_token, provider.synchronizedAuthToken);
strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration);
ok(model._isLinked("myoauth"), "User should be linked to myoauth");
model._unlinkFrom("myoauth", {
success: function(model) {
await model._unlinkFrom("myoauth");
ok(!model._isLinked("myoauth"),
"User should not be linked to myoauth");
ok(!provider.synchronizedUserId, "User id should be cleared");
ok(!provider.synchronizedAuthToken, "Auth token should be cleared");
ok(!provider.synchronizedExpiration,
"Expiration should be cleared");
// make sure the auth data is properly deleted
const config = Config.get(Parse.applicationId);
const res = await config.database.adapter.find('_User', {
fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation),
}, { objectId: model.id }, {})
expect(res.length).toBe(1);
expect(res[0]._auth_data_myoauth).toBeUndefined();
expect(res[0]._auth_data_myoauth).not.toBeNull();
ok(!model._isLinked("myoauth"),
"User should not be linked to myoauth");
ok(!provider.synchronizedUserId, "User id should be cleared");
ok(!provider.synchronizedAuthToken, "Auth token should be cleared");
ok(!provider.synchronizedExpiration,
"Expiration should be cleared");
// make sure the auth data is properly deleted
const config = Config.get(Parse.applicationId);
config.database.adapter.find('_User', {
fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation),
}, { objectId: model.id }, {})
.then(res => {
expect(res.length).toBe(1);
expect(res[0]._auth_data_myoauth).toBeUndefined();
expect(res[0]._auth_data_myoauth).not.toBeNull();
await model._linkWith("myoauth");
model._linkWith("myoauth", {
success: function(model) {
ok(provider.synchronizedUserId, "User id should have a value");
ok(provider.synchronizedAuthToken,
"Auth token should have a value");
ok(provider.synchronizedExpiration,
"Expiration should have a value");
ok(model._isLinked("myoauth"),
"User should be linked to myoauth");
done();
},
error: function() {
ok(false, "linking again should succeed");
done();
}
});
});
},
error: function() {
ok(false, "unlinking should succeed");
done();
}
});
},
error: function() {
ok(false, "linking should have worked");
done();
}
});
ok(provider.synchronizedUserId, "User id should have a value");
ok(provider.synchronizedAuthToken,
"Auth token should have a value");
ok(provider.synchronizedExpiration,
"Expiration should have a value");
ok(model._isLinked("myoauth"),
"User should be linked to myoauth");
});
function validateValidator(validator) {

View File

@@ -7,17 +7,17 @@ describe('Cloud Code', () => {
it('can load absolute cloud code file', done => {
reconfigureServer({ cloud: __dirname + '/cloud/cloudCodeRelativeFile.js' })
.then(() => {
Parse.Cloud.run('cloudCodeInFile', {}, result => {
Parse.Cloud.run('cloudCodeInFile', {}).then(result => {
expect(result).toEqual('It is possible to define cloud code in a file.');
done();
});
})
});
});
it('can load relative cloud code file', done => {
reconfigureServer({ cloud: './spec/cloud/cloudCodeAbsoluteFile.js' })
.then(() => {
Parse.Cloud.run('cloudCodeInFile', {}, result => {
Parse.Cloud.run('cloudCodeInFile', {}).then(result => {
expect(result).toEqual('It is possible to define cloud code in a file.');
done();
});
@@ -29,7 +29,7 @@ describe('Cloud Code', () => {
res.success('Hello world!');
});
Parse.Cloud.run('hello', {}, result => {
Parse.Cloud.run('hello', {}).then(result => {
expect(result).toEqual('Hello world!');
done();
});
@@ -183,15 +183,14 @@ describe('Cloud Code', () => {
const obj = req.object;
if(!obj.existed())
{
const promise = new Parse.Promise();
setTimeout(function(){
obj.set('proof', obj.id);
obj.save().then(function(){
promise.resolve();
});
}, 1000);
return promise;
return new Promise((resolve) => {
setTimeout(function(){
obj.set('proof', obj.id);
obj.save().then(function(){
resolve();
});
}, 1000);
});
}
});
@@ -218,15 +217,14 @@ describe('Cloud Code', () => {
const obj = req.object;
if(!obj.existed())
{
const promise = new Parse.Promise();
setTimeout(function(){
obj.set('proof', obj.id);
obj.save().then(function(){
promise.resolve();
});
}, 1000);
return promise;
return new Promise((resolve) => {
setTimeout(function(){
obj.set('proof', obj.id);
obj.save().then(function(){
resolve();
});
}, 1000);
});
}
});
@@ -247,12 +245,11 @@ describe('Cloud Code', () => {
it('test afterSave rejecting promise', function(done) {
Parse.Cloud.afterSave('AfterSaveTest2', function() {
const promise = new Parse.Promise();
setTimeout(function(){
promise.reject("THIS SHOULD BE IGNORED");
}, 1000);
return promise;
return new Promise((resolve, reject) => {
setTimeout(function(){
reject("THIS SHOULD BE IGNORED");
}, 1000);
});
});
const obj = new Parse.Object('AfterSaveTest2');
@@ -266,18 +263,15 @@ describe('Cloud Code', () => {
it('test afterDelete returning promise, object is deleted when destroy resolves', function(done) {
Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) {
const promise = new Parse.Promise();
setTimeout(function(){
const obj = new Parse.Object('AfterDeleteTestProof');
obj.set('proof', req.object.id);
obj.save().then(function(){
promise.resolve();
});
}, 1000);
return promise;
return new Promise((resolve) => {
setTimeout(function(){
const obj = new Parse.Object('AfterDeleteTestProof');
obj.set('proof', req.object.id);
obj.save().then(function(){
resolve();
});
}, 1000);
});
});
const errorHandler = function(error) {
@@ -302,18 +296,15 @@ describe('Cloud Code', () => {
it('test afterDelete ignoring promise, object is not yet deleted', function(done) {
Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) {
const promise = new Parse.Promise();
setTimeout(function(){
const obj = new Parse.Object('AfterDeleteTestProof');
obj.set('proof', req.object.id);
obj.save().then(function(){
promise.resolve();
});
}, 1000);
return promise;
return new Promise((resolve) => {
setTimeout(function(){
const obj = new Parse.Object('AfterDeleteTestProof');
obj.set('proof', req.object.id);
obj.save().then(function(){
resolve();
});
}, 1000);
});
});
const errorHandler = function(error) {
@@ -666,7 +657,7 @@ describe('Cloud Code', () => {
});
});
it('test save triggers get user', function(done) {
it('test save triggers get user', async (done) => {
Parse.Cloud.beforeSave('SaveTriggerUser', function(req, res) {
if (req.user && req.user.id) {
res.success();
@@ -685,16 +676,13 @@ describe('Cloud Code', () => {
user.set("password", "asdf");
user.set("email", "asdf@example.com");
user.set("username", "zxcv");
user.signUp(null, {
success: function() {
const obj = new Parse.Object('SaveTriggerUser');
obj.save().then(function() {
done();
}, function(error) {
fail(error);
done();
});
}
await user.signUp();
const obj = new Parse.Object('SaveTriggerUser');
obj.save().then(function() {
done();
}, function(error) {
fail(error);
done();
});
});
@@ -821,7 +809,7 @@ describe('Cloud Code', () => {
'X-Parse-Session-Token': session2,
}
}))
.then(() => Parse.Promise.all([cacheAdapter.get('test:user:' + session1), cacheAdapter.get('test:user:' + session2)]))
.then(() => Promise.all([cacheAdapter.get('test:user:' + session1), cacheAdapter.get('test:user:' + session2)]))
.then(cachedVals => {
expect(cachedVals[0].objectId).toEqual(user.id);
expect(cachedVals[1].objectId).toEqual(user.id);
@@ -1006,7 +994,7 @@ describe('Cloud Code', () => {
expect(objectAgain.get('remove')).toBeUndefined();
expect(object.get('remove')).toBeUndefined();
done();
}).fail((err) => {
}).catch((err) => {
jfail(err);
done();
});
@@ -1031,7 +1019,7 @@ describe('Cloud Code', () => {
// Originally it would throw as it would be a non-relation
expect(() => { objectAgain.relation('testsRelation') }).not.toThrow();
done();
}).fail((err) => {
}).catch((err) => {
jfail(err);
done();
})
@@ -1669,14 +1657,14 @@ describe('afterFind hooks', () => {
it('should also work with promise',(done) => {
Parse.Cloud.afterFind('MyObject', (req) => {
const promise = new Parse.Promise();
setTimeout(function(){
for(let i = 0 ; i < req.objects.length ; i++){
req.objects[i].set("secretField","###");
}
promise.resolve(req.objects);
}, 1000);
return promise;
return new Promise((resolve) => {
setTimeout(function(){
for(let i = 0 ; i < req.objects.length ; i++){
req.objects[i].set("secretField","###");
}
resolve(req.objects);
}, 1000);
});
});
const obj = new Parse.Object('MyObject');
obj.set('secretField', 'SSID');

View File

@@ -6,7 +6,7 @@ const FilesController = require('../lib/Controllers/FilesController').default;
const mockAdapter = {
createFile: () => {
return Parse.Promise.reject(new Error('it failed'));
return Promise.reject(new Error('it failed'));
},
deleteFile: () => { },
getFileData: () => { },
@@ -46,9 +46,10 @@ describe("FilesController", () => {
.then(() => new Parse.File("yolo.txt", [1, 2, 3], "text/plain").save())
.then(
() => done.fail('should not succeed'),
() => setImmediate(() => Parse.Promise.as('done'))
() => setImmediate(() => Promise.resolve('done'))
)
.then(() => logController.getLogs({ from: Date.now() - 500, size: 1000 }))
.then(() => new Promise(resolve => setTimeout(resolve, 200)))
.then(() => logController.getLogs({ from: Date.now() - 1000, size: 1000 }))
.then((logs) => {
// we get two logs here: 1. the source of the failure to save the file
// and 2 the message that will be sent back to the client.

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,12 @@ const SchemaController = require('../lib/Controllers/SchemaController');
const TestUtils = require('../lib/TestUtils');
const userSchema = SchemaController.convertSchemaToAdapterSchema({ className: '_User', fields: Object.assign({}, SchemaController.defaultColumns._Default, SchemaController.defaultColumns._User) });
const headers = {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'test',
'X-Parse-REST-API-Key': 'rest',
'X-Parse-Installation-Id': 'yolo'
}
describe_only_db('mongo')('miscellaneous', () => {
it('test rest_create_app', function(done) {
@@ -29,7 +35,7 @@ describe_only_db('mongo')('miscellaneous', () => {
expect(results.length).toEqual(1);
expect(results[0]['foo']).toEqual('bar');
done();
}).fail(error => {
}).catch(error => {
fail(JSON.stringify(error));
done();
})
@@ -44,113 +50,108 @@ describe('miscellaneous', function() {
expect(typeof obj.id).toBe('string');
expect(typeof obj.createdAt.toGMTString()).toBe('string');
done();
}, error => {
fail(JSON.stringify(error));
done();
});
}, done.fail);
});
it('get a TestObject', function(done) {
create({ 'bloop' : 'blarg' }, function(obj) {
create({ 'bloop' : 'blarg' }, async function(obj) {
const t2 = new TestObject({ objectId: obj.id });
t2.fetch({
success: function(obj2) {
expect(obj2.get('bloop')).toEqual('blarg');
expect(obj2.id).toBeTruthy();
expect(obj2.id).toEqual(obj.id);
done();
},
error: error => {
fail(JSON.stringify(error));
done();
}
});
const obj2 = await t2.fetch();
expect(obj2.get('bloop')).toEqual('blarg');
expect(obj2.id).toBeTruthy();
expect(obj2.id).toEqual(obj.id);
done();
});
});
it('create a valid parse user', function(done) {
createTestUser(function(data) {
createTestUser().then(function(data) {
expect(data.id).not.toBeUndefined();
expect(data.getSessionToken()).not.toBeUndefined();
expect(data.get('password')).toBeUndefined();
done();
}, error => {
fail(JSON.stringify(error));
done();
});
}, done.fail);
});
it('fail to create a duplicate username', done => {
let numCreated = 0;
let numFailed = 0;
const p1 = createTestUser();
p1.then(() => {
numCreated++;
expect(numCreated).toEqual(1);
})
.catch(error => {
numFailed++;
expect(numFailed).toEqual(1);
expect(error.code).toEqual(Parse.Error.USERNAME_TAKEN);
});
const p2 = createTestUser();
p2.then(() => {
numCreated++;
expect(numCreated).toEqual(1);
})
.catch(error => {
numFailed++;
expect(numFailed).toEqual(1);
expect(error.code).toEqual(Parse.Error.USERNAME_TAKEN);
});
Parse.Promise.when([p1, p2])
.then(() => {
fail('one of the users should not have been created');
done();
})
.catch(done);
});
it('ensure that email is uniquely indexed', done => {
it('fail to create a duplicate username', async () => {
let numFailed = 0;
let numCreated = 0;
const user1 = new Parse.User();
user1.setPassword('asdf');
user1.setUsername('u1');
user1.setEmail('dupe@dupe.dupe');
const p1 = user1.signUp();
p1.then(() => {
const p1 = rp.post(Parse.serverURL + '/users', {
json: {
password: 'asdf',
username: 'u1',
email: 'dupe@dupe.dupe'
},
headers
}).then(() => {
numCreated++;
expect(numCreated).toEqual(1);
}, error => {
}, ({ error }) => {
numFailed++;
expect(error.code).toEqual(Parse.Error.USERNAME_TAKEN);
});
const p2 = rp.post(Parse.serverURL + '/users', {
json: {
password: 'otherpassword',
username: 'u1',
email: 'email@other.email'
},
headers
}).then(() => {
numCreated++;
}, ({ error }) => {
numFailed++;
expect(error.code).toEqual(Parse.Error.USERNAME_TAKEN);
});
await Promise.all([p1, p2])
expect(numFailed).toEqual(1);
expect(numCreated).toBe(1);
});
it('ensure that email is uniquely indexed', async () => {
let numFailed = 0;
let numCreated = 0;
const p1 = rp.post(Parse.serverURL + '/users', {
json: {
password: 'asdf',
username: 'u1',
email: 'dupe@dupe.dupe'
},
headers
}).then(() => {
numCreated++;
expect(numCreated).toEqual(1);
}, ({ error }) => {
numFailed++;
expect(numFailed).toEqual(1);
expect(error.code).toEqual(Parse.Error.EMAIL_TAKEN);
});
const user2 = new Parse.User();
user2.setPassword('asdf');
user2.setUsername('u2');
user2.setEmail('dupe@dupe.dupe');
const p2 = user2.signUp();
p2.then(() => {
const p2 = rp.post(Parse.serverURL + '/users', {
json: {
password: 'asdf',
username: 'u2',
email: 'dupe@dupe.dupe'
},
headers
}).then(() => {
numCreated++;
expect(numCreated).toEqual(1);
}, error => {
}, ({ error }) => {
numFailed++;
expect(numFailed).toEqual(1);
expect(error.code).toEqual(Parse.Error.EMAIL_TAKEN);
});
Parse.Promise.when([p1, p2])
.then(() => {
fail('one of the users should not have been created');
done();
})
.catch(done);
await Promise.all([p1, p2])
expect(numFailed).toEqual(1);
expect(numCreated).toBe(1);
});
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', async done => {
try {
await Parse.User.logOut();
} catch(e) { /* ignore */ }
const config = Config.get('test');
// Remove existing data to clear out unique index
TestUtils.destroyAllDataPermanently()
@@ -237,20 +238,15 @@ describe('miscellaneous', function() {
});
it('succeed in logging in', function(done) {
createTestUser(function(u) {
createTestUser().then(async function(u) {
expect(typeof u.id).toEqual('string');
Parse.User.logIn('test', 'moon-y', {
success: function(user) {
expect(typeof user.id).toEqual('string');
expect(user.get('password')).toBeUndefined();
expect(user.getSessionToken()).not.toBeUndefined();
Parse.User.logOut().then(done);
}, error: error => {
fail(JSON.stringify(error));
done();
}
});
const user = await Parse.User.logIn('test', 'moon-y');
expect(typeof user.id).toEqual('string');
expect(user.get('password')).toBeUndefined();
expect(user.getSessionToken()).not.toBeUndefined();
await Parse.User.logOut();
done();
}, fail);
});
@@ -856,7 +852,7 @@ describe('miscellaneous', function() {
}
done();
});
}).fail(() => {
}).catch(() => {
fail('Should not fail');
done();
})

View File

@@ -204,98 +204,62 @@ describe('Parse.File testing', () => {
});
});
it("save file", done => {
it("save file", async () => {
const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url());
file.save(expectSuccess({
success: function(result) {
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
done();
}
}, done));
const result = await file.save();
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
});
it("save file in object", done => {
it("save file in object", async done => {
const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url());
file.save(expectSuccess({
success: function(result) {
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
const result = await file.save();
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
const object = new Parse.Object("TestObject");
object.save({
file: file
}, expectSuccess({
success: function(object) {
(new Parse.Query("TestObject")).get(object.id, expectSuccess({
success: function(objectAgain) {
ok(objectAgain.get("file") instanceof Parse.File);
done();
}
}));
}
}, done));
}
}, done));
const object = new Parse.Object("TestObject");
await object.save({ file: file });
const objectAgain = await (new Parse.Query("TestObject")).get(object.id);
ok(objectAgain.get("file") instanceof Parse.File);
done();
});
it("save file in object with escaped characters in filename", done => {
it("save file in object with escaped characters in filename", async () => {
const file = new Parse.File("hello . txt", data, "text/plain");
ok(!file.url());
file.save(expectSuccess({
success: function(result) {
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello . txt");
const result = await file.save();
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello . txt");
const object = new Parse.Object("TestObject");
object.save({
file: file
}, expectSuccess({
success: function(object) {
(new Parse.Query("TestObject")).get(object.id, expectSuccess({
success: function(objectAgain) {
ok(objectAgain.get("file") instanceof Parse.File);
done();
}
}));
}
}, done));
}
}, done));
const object = new Parse.Object("TestObject");
await object.save({ file });
const objectAgain = await (new Parse.Query("TestObject")).get(object.id);
ok(objectAgain.get("file") instanceof Parse.File);
});
it("autosave file in object", done => {
it("autosave file in object", async done => {
let file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url());
const object = new Parse.Object("TestObject");
object.save({
file: file
}, expectSuccess({
success: function(object) {
(new Parse.Query("TestObject")).get(object.id, expectSuccess({
success: function(objectAgain) {
file = objectAgain.get("file");
ok(file instanceof Parse.File);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
done();
}
}, done));
}
}, done));
await object.save({ file });
const objectAgain = await (new Parse.Query("TestObject")).get(object.id);
file = objectAgain.get("file");
ok(file instanceof Parse.File);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
done();
});
it("autosave file in object in object", done => {
it("autosave file in object in object", async done => {
let file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url());
@@ -305,44 +269,31 @@ describe('Parse.File testing', () => {
const parent = new Parse.Object("Parent");
parent.set("child", child);
parent.save(expectSuccess({
success: function(parent) {
const query = new Parse.Query("Parent");
query.include("child");
query.get(parent.id, expectSuccess({
success: function(parentAgain) {
const childAgain = parentAgain.get("child");
file = childAgain.get("file");
ok(file instanceof Parse.File);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
done();
}
}, done));
}
}, done));
await parent.save();
const query = new Parse.Query("Parent");
query.include("child");
const parentAgain = await query.get(parent.id);
const childAgain = parentAgain.get("child");
file = childAgain.get("file");
ok(file instanceof Parse.File);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
done();
});
it("saving an already saved file", done => {
it("saving an already saved file", async () => {
const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url());
file.save(expectSuccess({
success: function(result) {
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
const previousName = file.name();
const result = await file.save();
strictEqual(result, file);
ok(file.name());
ok(file.url());
notEqual(file.name(), "hello.txt");
const previousName = file.name();
file.save(expectSuccess({
success: function() {
equal(file.name(), previousName);
done();
}
}, done));
}
}, done));
await file.save();
equal(file.name(), previousName);
});
it("two saves at the same time", done => {
@@ -354,7 +305,7 @@ describe('Parse.File testing', () => {
const firstSave = file.save().then(function() { firstName = file.name(); });
const secondSave = file.save().then(function() { secondName = file.name(); });
Parse.Promise.when(firstSave, secondSave).then(function() {
Promise.all([firstSave, secondSave]).then(function() {
equal(firstName, secondName);
done();
}, function(error) {
@@ -363,18 +314,14 @@ describe('Parse.File testing', () => {
});
});
it("file toJSON testing", done => {
it("file toJSON testing", async () => {
const file = new Parse.File("hello.txt", data, "text/plain");
ok(!file.url());
const object = new Parse.Object("TestObject");
object.save({
await object.save({
file: file
}, expectSuccess({
success: function() {
ok(object.toJSON().file.url);
done();
}
}, done));
});
ok(object.toJSON().file.url);
});
it("content-type used with no extension", done => {

View File

@@ -6,26 +6,18 @@ const TestObject = Parse.Object.extend('TestObject');
describe('Parse.GeoPoint testing', () => {
it('geo point roundtrip', (done) => {
it('geo point roundtrip', async () => {
const point = new Parse.GeoPoint(44.0, -11.0);
const obj = new TestObject();
obj.set('location', point);
obj.set('name', 'Ferndale');
obj.save(null, {
success: function() {
const query = new Parse.Query(TestObject);
query.find({
success: function(results) {
equal(results.length, 1);
const pointAgain = results[0].get('location');
ok(pointAgain);
equal(pointAgain.latitude, 44.0);
equal(pointAgain.longitude, -11.0);
done();
}
});
}
});
await obj.save();
const results = await new Parse.Query(TestObject).find();
equal(results.length, 1);
const pointAgain = results[0].get('location');
ok(pointAgain);
equal(pointAgain.latitude, 44.0);
equal(pointAgain.longitude, -11.0);
});
it('update geopoint', (done) => {
@@ -47,25 +39,22 @@ describe('Parse.GeoPoint testing', () => {
});
});
it('has the correct __type field in the json response', done => {
it('has the correct __type field in the json response', async (done) => {
const point = new Parse.GeoPoint(44.0, -11.0);
const obj = new TestObject();
obj.set('location', point);
obj.set('name', 'Zhoul')
obj.save(null, {
success: (obj) => {
Parse.Cloud.httpRequest({
url: 'http://localhost:8378/1/classes/TestObject/' + obj.id,
headers: {
'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key': 'test'
}
}).then(response => {
equal(response.data.location.__type, 'GeoPoint');
done();
})
await obj.save();
Parse.Cloud.httpRequest({
url: 'http://localhost:8378/1/classes/TestObject/' + obj.id,
headers: {
'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key': 'test'
}
})
}).then(response => {
equal(response.data.location.__type, 'GeoPoint');
done();
});
});
it('creating geo point exception two fields', (done) => {
@@ -82,24 +71,21 @@ describe('Parse.GeoPoint testing', () => {
});
// TODO: This should also have support in postgres, or higher level database agnostic support.
it_exclude_dbs(['postgres'])('updating geo point exception two fields', (done) => {
it_exclude_dbs(['postgres'])('updating geo point exception two fields', async (done) => {
const point = new Parse.GeoPoint(20, 20);
const obj = new TestObject();
obj.set('locationOne', point);
obj.save(null, {
success: (obj) => {
obj.set('locationTwo', point);
obj.save().then(() => {
fail('expected error');
}, (err) => {
equal(err.code, Parse.Error.INCORRECT_TYPE);
done();
})
}
await obj.save();
obj.set('locationTwo', point);
obj.save().then(() => {
fail('expected error');
}, (err) => {
equal(err.code, Parse.Error.INCORRECT_TYPE);
done();
});
});
it('geo line', (done) => {
it('geo line', async (done) => {
const line = [];
for (let i = 0; i < 10; ++i) {
const obj = new TestObject();
@@ -109,22 +95,16 @@ describe('Parse.GeoPoint testing', () => {
obj.set('seq', i);
line.push(obj);
}
Parse.Object.saveAll(line, {
success: function() {
const query = new Parse.Query(TestObject);
const point = new Parse.GeoPoint(24, 19);
query.equalTo('construct', 'line');
query.withinMiles('location', point, 10000);
query.find({
success: function(results) {
equal(results.length, 10);
equal(results[0].get('seq'), 9);
equal(results[3].get('seq'), 6);
done();
}
});
}
});
await Parse.Object.saveAll(line);
const query = new Parse.Query(TestObject);
const point = new Parse.GeoPoint(24, 19);
query.equalTo('construct', 'line');
query.withinMiles('location', point, 10000);
const results = await query.find()
equal(results.length, 10);
equal(results[0].get('seq'), 9);
equal(results[3].get('seq'), 6);
done();
});
it('geo max distance large', (done) => {
@@ -150,7 +130,7 @@ describe('Parse.GeoPoint testing', () => {
});
});
it('geo max distance medium', (done) => {
it('geo max distance medium', async () => {
const objects = [];
[0, 1, 2].map(function(i) {
const obj = new TestObject();
@@ -159,22 +139,17 @@ describe('Parse.GeoPoint testing', () => {
obj.set('index', i);
objects.push(obj);
});
Parse.Object.saveAll(objects, function() {
const query = new Parse.Query(TestObject);
const point = new Parse.GeoPoint(1.0, -1.0);
query.withinRadians('location', point, 3.14 * 0.5);
query.find({
success: function(results) {
equal(results.length, 2);
equal(results[0].get('index'), 0);
equal(results[1].get('index'), 1);
done();
}
});
});
await Parse.Object.saveAll(objects)
const query = new Parse.Query(TestObject);
const point = new Parse.GeoPoint(1.0, -1.0);
query.withinRadians('location', point, 3.14 * 0.5);
const results = await query.find();
equal(results.length, 2);
equal(results[0].get('index'), 0);
equal(results[1].get('index'), 1);
});
it('geo max distance small', (done) => {
it('geo max distance small', async () => {
const objects = [];
[0, 1, 2].map(function(i) {
const obj = new TestObject();
@@ -183,21 +158,16 @@ describe('Parse.GeoPoint testing', () => {
obj.set('index', i);
objects.push(obj);
});
Parse.Object.saveAll(objects, function() {
const query = new Parse.Query(TestObject);
const point = new Parse.GeoPoint(1.0, -1.0);
query.withinRadians('location', point, 3.14 * 0.25);
query.find({
success: function(results) {
equal(results.length, 1);
equal(results[0].get('index'), 0);
done();
}
});
});
await Parse.Object.saveAll(objects);
const query = new Parse.Query(TestObject);
const point = new Parse.GeoPoint(1.0, -1.0);
query.withinRadians('location', point, 3.14 * 0.25);
const results = await query.find();
equal(results.length, 1);
equal(results[0].get('index'), 0);
});
const makeSomeGeoPoints = function(callback) {
const makeSomeGeoPoints = function() {
const sacramento = new TestObject();
sacramento.set('location', new Parse.GeoPoint(38.52, -121.50));
sacramento.set('name', 'Sacramento');
@@ -210,142 +180,97 @@ describe('Parse.GeoPoint testing', () => {
sf.set('location', new Parse.GeoPoint(37.75, -122.68));
sf.set('name', 'San Francisco');
Parse.Object.saveAll([sacramento, sf, honolulu], callback);
return Parse.Object.saveAll([sacramento, sf, honolulu]);
};
it('geo max distance in km everywhere', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
// Honolulu is 4300 km away from SFO on a sphere ;)
query.withinKilometers('location', sfo, 4800.0);
query.find({
success: function(results) {
equal(results.length, 3);
done();
}
});
});
it('geo max distance in km everywhere', async (done) => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
// Honolulu is 4300 km away from SFO on a sphere ;)
query.withinKilometers('location', sfo, 4800.0);
const results = await query.find();
equal(results.length, 3);
done();
});
it('geo max distance in km california', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 3700.0);
query.find({
success: function(results) {
equal(results.length, 2);
equal(results[0].get('name'), 'San Francisco');
equal(results[1].get('name'), 'Sacramento');
done();
}
});
});
it('geo max distance in km california', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 3700.0);
const results = await query.find();
equal(results.length, 2);
equal(results[0].get('name'), 'San Francisco');
equal(results[1].get('name'), 'Sacramento');
});
it('geo max distance in km bay area', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 100.0);
query.find({
success: function(results) {
equal(results.length, 1);
equal(results[0].get('name'), 'San Francisco');
done();
}
});
});
it('geo max distance in km bay area', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 100.0);
const results = await query.find();
equal(results.length, 1);
equal(results[0].get('name'), 'San Francisco');
});
it('geo max distance in km mid peninsula', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 10.0);
query.find({
success: function(results) {
equal(results.length, 0);
done();
}
});
});
it('geo max distance in km mid peninsula', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinKilometers('location', sfo, 10.0);
const results = await query.find();
equal(results.length, 0);
});
it('geo max distance in miles everywhere', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 2600.0);
query.find({
success: function(results) {
equal(results.length, 3);
done();
}
});
});
it('geo max distance in miles everywhere', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 2600.0);
const results = await query.find();
equal(results.length, 3);
});
it('geo max distance in miles california', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 2200.0);
query.find({
success: function(results) {
equal(results.length, 2);
equal(results[0].get('name'), 'San Francisco');
equal(results[1].get('name'), 'Sacramento');
done();
}
});
});
it('geo max distance in miles california', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 2200.0);
const results = await query.find();
equal(results.length, 2);
equal(results[0].get('name'), 'San Francisco');
equal(results[1].get('name'), 'Sacramento');
});
it('geo max distance in miles bay area', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
// 100km is 62 miles...
query.withinMiles('location', sfo, 62.0);
query.find({
success: function(results) {
equal(results.length, 1);
equal(results[0].get('name'), 'San Francisco');
done();
}
});
});
it('geo max distance in miles bay area', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 62.0);
const results = await query.find();
equal(results.length, 1);
equal(results[0].get('name'), 'San Francisco');
});
it('geo max distance in miles mid peninsula', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 10.0);
query.find({
success: function(results) {
equal(results.length, 0);
done();
}
});
});
it('geo max distance in miles mid peninsula', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.withinMiles('location', sfo, 10.0);
const results = await query.find();
equal(results.length, 0);
});
it('returns nearest location', (done) => {
makeSomeGeoPoints(function() {
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.near('location', sfo);
query.find({
success: function(results) {
equal(results[0].get('name'), 'San Francisco');
equal(results[1].get('name'), 'Sacramento');
done();
}
});
});
it('returns nearest location', async () => {
await makeSomeGeoPoints();
const sfo = new Parse.GeoPoint(37.6189722, -122.3748889);
const query = new Parse.Query(TestObject);
query.near('location', sfo);
const results = await query.find();
equal(results[0].get('name'), 'San Francisco');
equal(results[1].get('name'), 'Sacramento');
});
it('works with geobox queries', (done) => {
@@ -367,47 +292,33 @@ describe('Parse.GeoPoint testing', () => {
});
});
it('supports a sub-object with a geo point', done => {
it('supports a sub-object with a geo point', async () => {
const point = new Parse.GeoPoint(44.0, -11.0);
const obj = new TestObject();
obj.set('subobject', { location: point });
obj.save(null, {
success: function() {
const query = new Parse.Query(TestObject);
query.find({
success: function(results) {
equal(results.length, 1);
const pointAgain = results[0].get('subobject')['location'];
ok(pointAgain);
equal(pointAgain.latitude, 44.0);
equal(pointAgain.longitude, -11.0);
done();
}
});
}
});
await obj.save();
const query = new Parse.Query(TestObject);
const results = await query.find();
equal(results.length, 1);
const pointAgain = results[0].get('subobject')['location'];
ok(pointAgain);
equal(pointAgain.latitude, 44.0);
equal(pointAgain.longitude, -11.0);
});
it('supports array of geo points', done => {
it('supports array of geo points', async () => {
const point1 = new Parse.GeoPoint(44.0, -11.0);
const point2 = new Parse.GeoPoint(22.0, -55.0);
const obj = new TestObject();
obj.set('locations', [ point1, point2 ]);
obj.save(null, {
success: function() {
const query = new Parse.Query(TestObject);
query.find({
success: function(results) {
equal(results.length, 1);
const locations = results[0].get('locations');
expect(locations.length).toEqual(2);
expect(locations[0]).toEqual(point1);
expect(locations[1]).toEqual(point2);
done();
}
});
}
});
await obj.save();
const query = new Parse.Query(TestObject);
const results = await query.find();
equal(results.length, 1);
const locations = results[0].get('locations');
expect(locations.length).toEqual(2);
expect(locations[0]).toEqual(point1);
expect(locations[1]).toEqual(point2);
});
it('equalTo geopoint', (done) => {

View File

@@ -287,7 +287,7 @@ describe('Hooks', () => {
promises.push(Parse.Hooks.createFunction("AFunction" + i, "http://url.com/function" + i));
}
Parse.Promise.when(promises).then(function(){
Promise.all(promises).then(function(){
for (let i = 0; i < 5; i++) {
// Delete everything from memory, as the server just started
triggers.removeTrigger("beforeSave", "MyClass" + i, Parse.applicationId);
@@ -441,7 +441,7 @@ describe('Hooks', () => {
}).then(function(res) {
expect(res.get("hello")).toEqual("world");
done();
}).fail((err) => {
}).catch((err) => {
jfail(err);
fail("Should not fail creating a function");
done();
@@ -462,7 +462,7 @@ describe('Hooks', () => {
}).then(function(res) {
expect(res.get("hello")).toEqual("world");
done();
}).fail((err) => {
}).catch((err) => {
fail(`Should not fail: ${JSON.stringify(err)}`);
done();
});
@@ -485,19 +485,18 @@ describe('Hooks', () => {
const obj = new Parse.Object("SomeRandomObject");
return obj.save();
}).then(function() {
const promise = new Parse.Promise();
// Wait a bit here as it's an after save
setTimeout(() => {
expect(triggerCount).toBe(1);
new Parse.Query("AnotherObject")
.get(newObjectId)
.then((r) => promise.resolve(r));
}, 500);
return promise;
return new Promise((resolve) => {
setTimeout(() => {
expect(triggerCount).toBe(1);
new Parse.Query("AnotherObject")
.get(newObjectId)
.then((r) => resolve(r));
}, 500);
});
}).then(function(res){
expect(res.get("foo")).toEqual("bar");
done();
}).fail((err) => {
}).catch((err) => {
jfail(err);
fail("Should not fail creating a function");
done();

View File

@@ -61,12 +61,12 @@ describe('ParseLiveQueryServer', function() {
const mockSessionTokenCache = function(){
this.getUserId = function(sessionToken){
if (typeof sessionToken === 'undefined') {
return Parse.Promise.as(undefined);
return Promise.resolve(undefined);
}
if (sessionToken === null) {
return Parse.Promise.error();
return Promise.reject();
}
return Parse.Promise.as(testUserId);
return Promise.resolve(testUserId);
};
};
jasmine.mockLibrary('../lib/LiveQuery/SessionTokenCache', 'SessionTokenCache', mockSessionTokenCache);
@@ -575,7 +575,7 @@ describe('ParseLiveQueryServer', function() {
return true;
};
parseLiveQueryServer._matchesACL = function() {
return Parse.Promise.as(true);
return Promise.resolve(true);
};
parseLiveQueryServer._onAfterDelete(message);
@@ -610,7 +610,7 @@ describe('ParseLiveQueryServer', function() {
return false;
};
parseLiveQueryServer._matchesACL = function() {
return Parse.Promise.as(true)
return Promise.resolve(true)
};
// Trigger onAfterSave
parseLiveQueryServer._onAfterSave(message);
@@ -648,7 +648,7 @@ describe('ParseLiveQueryServer', function() {
return counter % 2 === 0;
};
parseLiveQueryServer._matchesACL = function() {
return Parse.Promise.as(true)
return Promise.resolve(true)
};
parseLiveQueryServer._onAfterSave(message);
@@ -681,7 +681,7 @@ describe('ParseLiveQueryServer', function() {
return true;
};
parseLiveQueryServer._matchesACL = function() {
return Parse.Promise.as(true)
return Promise.resolve(true)
};
parseLiveQueryServer._onAfterSave(message);
@@ -718,7 +718,7 @@ describe('ParseLiveQueryServer', function() {
return counter % 2 !== 0;
};
parseLiveQueryServer._matchesACL = function() {
return Parse.Promise.as(true)
return Promise.resolve(true)
};
parseLiveQueryServer._onAfterSave(message);
@@ -751,7 +751,7 @@ describe('ParseLiveQueryServer', function() {
return true;
};
parseLiveQueryServer._matchesACL = function() {
return Parse.Promise.as(true)
return Promise.resolve(true)
};
parseLiveQueryServer._onAfterSave(message);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -41,41 +41,31 @@ describe('Parse.Relation testing', () => {
});
});
it("query relation without schema", (done) => {
it("query relation without schema", async () => {
const ChildObject = Parse.Object.extend("ChildObject");
const childObjects = [];
for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x:i}));
}
Parse.Object.saveAll(childObjects, expectSuccess({
success: function() {
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
const relation = parent.relation("child");
relation.add(childObjects[0]);
parent.save(null, expectSuccess({
success: function() {
const parentAgain = new ParentObject();
parentAgain.id = parent.id;
const relation = parentAgain.relation("child");
relation.query().find(expectSuccess({
success: function(list) {
equal(list.length, 1,
"Should have gotten one element back");
equal(list[0].id, childObjects[0].id,
"Should have gotten the right value");
done();
}
}));
}
}));
}
}));
await Parse.Object.saveAll(childObjects);
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
let relation = parent.relation("child");
relation.add(childObjects[0]);
await parent.save();
const parentAgain = new ParentObject();
parentAgain.id = parent.id;
relation = parentAgain.relation("child");
const list = await relation.query().find();
equal(list.length, 1,
"Should have gotten one element back");
equal(list[0].id, childObjects[0].id,
"Should have gotten the right value");
});
it("relations are constructed right from query", (done) => {
it("relations are constructed right from query", async () => {
const ChildObject = Parse.Object.extend("ChildObject");
const childObjects = [];
@@ -83,42 +73,23 @@ describe('Parse.Relation testing', () => {
childObjects.push(new ChildObject({x: i}));
}
Parse.Object.saveAll(childObjects, {
success: function() {
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
const relation = parent.relation("child");
relation.add(childObjects[0]);
parent.save(null, {
success: function() {
const query = new Parse.Query(ParentObject);
query.get(parent.id, {
success: function(object) {
const relationAgain = object.relation("child");
relationAgain.query().find({
success: function(list) {
equal(list.length, 1,
"Should have gotten one element back");
equal(list[0].id, childObjects[0].id,
"Should have gotten the right value");
ok(!parent.dirty("child"),
"The relation should not be dirty");
done();
},
error: function() {
ok(false, "This shouldn't have failed");
done();
}
});
}
});
}
});
}
});
await Parse.Object.saveAll(childObjects);
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
const relation = parent.relation("child");
relation.add(childObjects[0]);
await parent.save();
const query = new Parse.Query(ParentObject);
const object = await query.get(parent.id);
const relationAgain = object.relation("child");
const list = await relationAgain.query().find();
equal(list.length, 1,
"Should have gotten one element back");
equal(list[0].id, childObjects[0].id,
"Should have gotten the right value");
ok(!parent.dirty("child"),
"The relation should not be dirty");
});
it("compound add and remove relation", (done) => {
@@ -191,7 +162,7 @@ describe('Parse.Relation testing', () => {
}).then(done, done.fail);
});
it_exclude_dbs(['postgres'])("queries with relations", (done) => {
it_exclude_dbs(['postgres'])("queries with relations", async () => {
const ChildObject = Parse.Object.extend("ChildObject");
const childObjects = [];
@@ -199,80 +170,59 @@ describe('Parse.Relation testing', () => {
childObjects.push(new ChildObject({x: i}));
}
Parse.Object.saveAll(childObjects, {
success: function() {
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
const relation = parent.relation("child");
relation.add(childObjects[0]);
relation.add(childObjects[1]);
relation.add(childObjects[2]);
parent.save(null, {
success: function() {
const query = relation.query();
query.equalTo("x", 2);
query.find({
success: function(list) {
equal(list.length, 1,
"There should only be one element");
ok(list[0] instanceof ChildObject,
"Should be of type ChildObject");
equal(list[0].id, childObjects[2].id,
"We should have gotten back the right result");
done();
}
});
}
});
}
});
await Parse.Object.saveAll(childObjects);
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
const relation = parent.relation("child");
relation.add(childObjects[0]);
relation.add(childObjects[1]);
relation.add(childObjects[2]);
await parent.save();
const query = relation.query();
query.equalTo("x", 2);
const list = await query.find();
equal(list.length, 1,
"There should only be one element");
ok(list[0] instanceof ChildObject,
"Should be of type ChildObject");
equal(list[0].id, childObjects[2].id,
"We should have gotten back the right result");
});
it("queries on relation fields", (done) => {
it("queries on relation fields", async () => {
const ChildObject = Parse.Object.extend("ChildObject");
const childObjects = [];
for (let i = 0; i < 10; i++) {
childObjects.push(new ChildObject({x: i}));
}
Parse.Object.saveAll(childObjects, {
success: function() {
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
const relation = parent.relation("child");
relation.add(childObjects[0]);
relation.add(childObjects[1]);
relation.add(childObjects[2]);
const parent2 = new ParentObject();
parent2.set("x", 3);
const relation2 = parent2.relation("child");
relation2.add(childObjects[4]);
relation2.add(childObjects[5]);
relation2.add(childObjects[6]);
const parents = [];
parents.push(parent);
parents.push(parent2);
Parse.Object.saveAll(parents, {
success: function() {
const query = new Parse.Query(ParentObject);
const objects = [];
objects.push(childObjects[4]);
objects.push(childObjects[9]);
query.containedIn("child", objects);
query.find({
success: function(list) {
equal(list.length, 1, "There should be only one result");
equal(list[0].id, parent2.id,
"Should have gotten back the right result");
done();
}
});
}
});
}
});
await Parse.Object.saveAll(childObjects);
const ParentObject = Parse.Object.extend("ParentObject");
const parent = new ParentObject();
parent.set("x", 4);
const relation = parent.relation("child");
relation.add(childObjects[0]);
relation.add(childObjects[1]);
relation.add(childObjects[2]);
const parent2 = new ParentObject();
parent2.set("x", 3);
const relation2 = parent2.relation("child");
relation2.add(childObjects[4]);
relation2.add(childObjects[5]);
relation2.add(childObjects[6]);
const parents = [];
parents.push(parent);
parents.push(parent2);
await Parse.Object.saveAll(parents);
const query = new Parse.Query(ParentObject);
const objects = [];
objects.push(childObjects[4]);
objects.push(childObjects[9]);
const list = await query.containedIn("child", objects).find();
equal(list.length, 1, "There should be only one result");
equal(list[0].id, parent2.id,
"Should have gotten back the right result");
});
it("queries on relation fields with multiple containedIn (regression test for #1271)", (done) => {
@@ -627,22 +577,19 @@ describe('Parse.Relation testing', () => {
Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() {
owner.relation('restaurants').add(restaurants);
return owner.save()
}).then(() => {
}).then(async () => {
const unfetchedOwner = new OwnerObject();
unfetchedOwner.id = owner.id;
const query = unfetchedOwner.relation('restaurants').query();
query.greaterThan("ratings", 4);
const mainQuery = new Parse.Query(PersonObject);
mainQuery.matchesKeyInQuery("hometown", "location", query);
mainQuery.find(expectSuccess({
success: function(results) {
equal(results.length, 1);
if (results.length > 0) {
equal(results[0].get('name'), 'Bob');
}
done();
}
}));
const results = await mainQuery.find();
equal(results.length, 1);
if (results.length > 0) {
equal(results[0].get('name'), 'Bob');
}
done();
}, (e) => {
fail(JSON.stringify(e));
done();
@@ -668,7 +615,7 @@ describe('Parse.Relation testing', () => {
Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() {
owner.relation('restaurants').add(restaurants);
return owner.save()
}).then(() => {
}).then(async () => {
const unfetchedOwner = new OwnerObject();
unfetchedOwner.id = owner.id;
const query = unfetchedOwner.relation('restaurants').query();
@@ -676,16 +623,13 @@ describe('Parse.Relation testing', () => {
const mainQuery = new Parse.Query(PersonObject);
mainQuery.doesNotMatchKeyInQuery("hometown", "location", query);
mainQuery.ascending('name');
mainQuery.find(expectSuccess({
success: function(results) {
equal(results.length, 2);
if (results.length > 0) {
equal(results[0].get('name'), 'Billy');
equal(results[1].get('name'), 'Tom');
}
done();
}
}));
const results = await mainQuery.find()
equal(results.length, 2);
if (results.length > 0) {
equal(results[0].get('name'), 'Billy');
equal(results[1].get('name'), 'Tom');
}
done();
}, (e) => {
fail(JSON.stringify(e));
done();

View File

@@ -227,7 +227,7 @@ describe('Parse Role testing', () => {
// return with result and roleId for later comparison
const promises = [admin, moderator, contentManager, superModerator].map((role) => {
return auth._getAllRolesNamesForRoleIds([role.id]).then((result) => {
return Parse.Promise.as({
return Promise.resolve({
id: role.id,
name: role.get('name'),
roleNames: result
@@ -235,7 +235,7 @@ describe('Parse Role testing', () => {
})
});
return Parse.Promise.when(promises);
return Promise.all(promises);
}).then((results) => {
results.forEach((result) => {
const id = result.id;
@@ -257,7 +257,7 @@ describe('Parse Role testing', () => {
}
});
done();
}).fail(() => {
}).catch(() => {
done();
})

View File

@@ -64,7 +64,7 @@ describe('ParseServerRESTController', () => {
expect(res.results.length).toBe(1);
expect(res.results[0].key).toEqual("value");
done();
}).fail((err) => {
}).catch((err) => {
console.log(err);
jfail(err);
done();
@@ -81,7 +81,7 @@ describe('ParseServerRESTController', () => {
// Result is in JSON format
expect(res.objectId).toEqual(userId);
done();
}).fail((err) => {
}).catch((err) => {
console.log(err);
jfail(err);
done();

File diff suppressed because it is too large Load Diff

View File

@@ -21,7 +21,7 @@ function createProduct() {
describe("test validate_receipt endpoint", () => {
beforeEach(done => {
createProduct().then(done).fail(function(){
createProduct().then(done).catch(function(){
done();
});
})
@@ -182,7 +182,7 @@ describe("test validate_receipt endpoint", () => {
expect(productAgain.get('downloadName')).toEqual(productAgain.get('download').name());
expect(productAgain.get("title")).toEqual("a new title");
done();
}).fail(function(err){
}).catch(function(err){
fail(JSON.stringify(err));
done();
});
@@ -199,7 +199,7 @@ describe("test validate_receipt endpoint", () => {
}).then(function(){
fail("Should not succeed");
done();
}).fail(function(err){
}).catch(function(err){
expect(err.code).toEqual(Parse.Error.INCORRECT_TYPE);
expect(err.message).toEqual("title is required.");
done();

View File

@@ -750,7 +750,7 @@ describe('SchemaController', () => {
hasAllPODobject().save()
.then(() => config.database.loadSchema())
.then(schema => schema.deleteField('missingField', 'HasAllPOD'))
.fail(error => {
.catch(error => {
expect(error.code).toEqual(255);
expect(error.message).toEqual('Field missingField does not exist, cannot delete.');
done();

View File

@@ -6,7 +6,7 @@ describe('SessionTokenCache', function() {
const Parse = require('parse/node');
spyOn(Parse, "Query").and.returnValue({
first: jasmine.createSpy("first").and.returnValue(Parse.Promise.as(new Parse.Object("_Session", {
first: jasmine.createSpy("first").and.returnValue(Promise.resolve(new Parse.Object("_Session", {
user: new Parse.User({id:"userId"})
}))),
equalTo: function(){}

View File

@@ -31,7 +31,7 @@ describe('Personally Identifiable Information', () => {
fetchedUser => {
expect(fetchedUser.get('email')).toBe(EMAIL);
}, e => console.error('error', e))
.done(() => done());
.then(done).catch(done.fail);
});
it('should not be able to get PII via API with object', (done) => {
@@ -42,11 +42,12 @@ describe('Personally Identifiable Information', () => {
userObj.fetch().then(
fetchedUser => {
expect(fetchedUser.get('email')).toBe(undefined);
done();
})
.fail(e => {
.catch(e => {
done.fail(JSON.stringify(e));
})
.done(() => done());
.then(done).catch(done.fail);
});
});
@@ -59,7 +60,7 @@ describe('Personally Identifiable Information', () => {
fetchedUser => {
expect(fetchedUser.get('email')).toBe(EMAIL);
}, e => console.error('error', e))
.done(() => done());
.then(done).catch(done.fail);
});
});
@@ -285,7 +286,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.get('zip')).toBe(undefined);
expect(fetchedUser.get('ssn')).toBe(undefined);
}, e => console.error('error', e))
.done(() => done());
.then(done).catch(done.fail);
});
});
@@ -300,7 +301,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.get('zip')).toBe(ZIP);
expect(fetchedUser.get('ssn')).toBe(SSN);
}, e => console.error('error', e))
.done(() => done());
.then(done).catch(done.fail);
});
});
@@ -397,7 +398,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.email).toBe(undefined);
},
e => console.error('error', e.message)
).done(() => done());
).then(done).catch(done.fail);
});
it('should get PII via REST with self credentials', (done) => {
@@ -418,7 +419,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.ssn).toBe(SSN);
},
e => console.error('error', e.message)
).done(() => done());
).then(done).catch(done.fail);
});
it('should get PII via REST using master key', (done) => {
@@ -438,7 +439,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.ssn).toBe(SSN);
},
e => console.error('error', e.message)
).done(() => done());
).then(done).catch(done.fail);
});
it('should not get PII via REST by ID', (done) => {
@@ -457,7 +458,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.email).toBe(undefined);
},
e => console.error('error', e.message)
).done(() => done());
).then(done).catch(done.fail);
});
it('should get PII via REST by ID with self credentials', (done) => {
@@ -477,7 +478,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.email).toBe(EMAIL);
},
e => console.error('error', e.message)
).done(() => done());
).then(done).catch(done.fail);
});
it('should get PII via REST by ID with master key', (done) => {
@@ -497,7 +498,7 @@ describe('Personally Identifiable Information', () => {
expect(fetchedUser.email).toBe(EMAIL);
},
e => console.error('error', e.message)
).done(() => done());
).then(done).catch(done.fail);
});
});
});

View File

@@ -42,26 +42,19 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
emailAdapter: emailAdapter,
publicServerURL: "http://localhost:8378/1"
})
.then(() => {
.then(async () => {
spyOn(emailAdapter, 'sendVerificationEmail');
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
user.setEmail('testIfEnabled@parse.com');
user.signUp(null, {
success: function(user) {
expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled();
user.fetch()
.then(() => {
expect(user.get('emailVerified')).toEqual(false);
done();
});
},
error: function() {
fail('Failed to save user');
await user.signUp();
expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled();
user.fetch()
.then(() => {
expect(user.get('emailVerified')).toEqual(false);
done();
}
});
});
});
});
@@ -77,25 +70,18 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
emailAdapter: emailAdapter,
publicServerURL: "http://localhost:8378/1"
})
.then(() => {
.then(async () => {
spyOn(emailAdapter, 'sendVerificationEmail');
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
user.signUp(null, {
success: function(user) {
expect(emailAdapter.sendVerificationEmail).not.toHaveBeenCalled();
user.fetch()
.then(() => {
expect(user.get('emailVerified')).toEqual(undefined);
done();
});
},
error: function() {
fail('Failed to save user');
await user.signUp();
expect(emailAdapter.sendVerificationEmail).not.toHaveBeenCalled();
user.fetch()
.then(() => {
expect(user.get('emailVerified')).toEqual(undefined);
done();
}
});
});
});
});
@@ -110,83 +96,62 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
verifyUserEmails: true,
emailAdapter: emailAdapter,
publicServerURL: "http://localhost:8378/1"
})
.then(() => {
spyOn(emailAdapter, 'sendVerificationEmail');
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
user.signUp(null, {
success: function(user) {
expect(emailAdapter.sendVerificationEmail).not.toHaveBeenCalled();
user.fetch()
.then((user) => {
user.set("email", "testWhenUpdating@parse.com");
return user.save();
}).then((user) => {
return user.fetch();
}).then(() => {
expect(user.get('emailVerified')).toEqual(false);
// Wait as on update email, we need to fetch the username
setTimeout(function(){
expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled();
done();
}, 200);
});
},
error: function() {
fail('Failed to save user');
}).then(async () => {
spyOn(emailAdapter, 'sendVerificationEmail');
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
await user.signUp();
expect(emailAdapter.sendVerificationEmail).not.toHaveBeenCalled();
user.fetch()
.then((user) => {
user.set("email", "testWhenUpdating@parse.com");
return user.save();
}).then((user) => {
return user.fetch();
}).then(() => {
expect(user.get('emailVerified')).toEqual(false);
// Wait as on update email, we need to fetch the username
setTimeout(function(){
expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled();
done();
}
}, 200);
});
});
});
});
it('does send a validation email with valid verification link when updating the email', done => {
it('does send a validation email with valid verification link when updating the email', async done => {
const emailAdapter = {
sendVerificationEmail: () => Promise.resolve(),
sendPasswordResetEmail: () => Promise.resolve(),
sendMail: () => Promise.resolve()
}
reconfigureServer({
await reconfigureServer({
appName: 'unused',
verifyUserEmails: true,
emailAdapter: emailAdapter,
publicServerURL: "http://localhost:8378/1"
})
.then(() => {
spyOn(emailAdapter, 'sendVerificationEmail').and.callFake((options) => {
expect(options.link).not.toBeNull();
expect(options.link).not.toMatch(/token=undefined/);
Promise.resolve();
});
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
user.signUp(null, {
success: function(user) {
expect(emailAdapter.sendVerificationEmail).not.toHaveBeenCalled();
user.fetch()
.then((user) => {
user.set("email", "testValidLinkWhenUpdating@parse.com");
return user.save();
}).then((user) => {
return user.fetch();
}).then(() => {
expect(user.get('emailVerified')).toEqual(false);
// Wait as on update email, we need to fetch the username
setTimeout(function(){
expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled();
done();
}, 200);
});
},
error: function() {
fail('Failed to save user');
done();
}
});
});
spyOn(emailAdapter, 'sendVerificationEmail').and.callFake((options) => {
expect(options.link).not.toBeNull();
expect(options.link).not.toMatch(/token=undefined/);
Promise.resolve();
});
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
await user.signUp();
expect(emailAdapter.sendVerificationEmail).not.toHaveBeenCalled();
await user.fetch()
user.set("email", "testValidLinkWhenUpdating@parse.com");
await user.save();
await user.fetch();
expect(user.get('emailVerified')).toEqual(false);
// Wait as on update email, we need to fetch the username
setTimeout(function(){
expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled();
done();
}, 200);
});
it('does send with a simple adapter', done => {
@@ -211,32 +176,25 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
emailAdapter: emailAdapter,
publicServerURL: "http://localhost:8378/1"
})
.then(() => {
.then(async () => {
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
user.set("email", "testSendSimpleAdapter@parse.com");
user.signUp(null, {
success: function(user) {
expect(calls).toBe(1);
user.fetch()
.then((user) => {
return user.save();
}).then(() => {
return Parse.User.requestPasswordReset("testSendSimpleAdapter@parse.com").catch(() => {
fail('Should not fail requesting a password');
done();
})
}).then(() => {
expect(calls).toBe(2);
done();
});
},
error: function() {
fail('Failed to save user');
await user.signUp();
expect(calls).toBe(1);
user.fetch()
.then((user) => {
return user.save();
}).then(() => {
return Parse.User.requestPasswordReset("testSendSimpleAdapter@parse.com").catch(() => {
fail('Should not fail requesting a password');
done();
})
}).then(() => {
expect(calls).toBe(2);
done();
}
});
});
});
});
@@ -535,25 +493,16 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
verifyUserEmails: false,
emailAdapter: emailAdapter,
})
.then(() => {
.then(async () => {
spyOn(emailAdapter, 'sendVerificationEmail');
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
user.signUp(null, {
success: function(user) {
user.fetch()
.then(() => {
expect(emailAdapter.sendVerificationEmail.calls.count()).toEqual(0);
expect(user.get('emailVerified')).toEqual(undefined);
done();
});
},
error: function() {
fail('Failed to save user');
done();
}
});
await user.signUp();
await user.fetch()
expect(emailAdapter.sendVerificationEmail.calls.count()).toEqual(0);
expect(user.get('emailVerified')).toEqual(undefined);
done();
});
});
@@ -574,21 +523,14 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
emailAdapter: emailAdapter,
publicServerURL: "http://localhost:8378/1"
})
.then(() => {
.then(async () => {
const user = new Parse.User();
user.setPassword("asdf");
user.setUsername("zxcv");
user.set('email', 'user@parse.com');
user.signUp(null, {
success: () => {
expect(emailSent).toBe(true);
done();
},
error: function() {
fail('Failed to save user');
done();
}
});
await user.signUp();
expect(emailSent).toBe(true);
done();
});
})
@@ -889,4 +831,6 @@ describe("Custom Pages, Email Verification, Password Reset", () => {
});
});
});
})
});

View File

@@ -21,7 +21,7 @@ describe('info logs', () => {
// Check the error log
// Regression #2639
winstonLoggerAdapter.query({
from: new Date(Date.now() - 500),
from: new Date(Date.now() - 200),
size: 100,
level: 'error'
}, (results) => {

View File

@@ -155,10 +155,6 @@ const reconfigureServer = changedConfiguration => {
const Parse = require('parse/node');
Parse.serverURL = 'http://localhost:' + port + '/1';
// This is needed because we ported a bunch of tests from the non-A+ way.
// TODO: update tests to work in an A+ way
Parse.Promise.disableAPlusCompliant();
// 10 minutes timeout
beforeAll(startDB, 10 * 60 * 1000);
@@ -239,27 +235,14 @@ const Container = Parse.Object.extend({
// Convenience method to create a new TestObject with a callback
function create(options, callback) {
const t = new TestObject(options);
t.save(null, { success: callback });
return t.save().then(callback);
}
function createTestUser(success, error) {
function createTestUser() {
const user = new Parse.User();
user.set('username', 'test');
user.set('password', 'moon-y');
const promise = user.signUp();
if (success || error) {
promise.then(function(user) {
if (success) {
success(user);
}
}, function(err) {
if (error) {
error(err);
}
});
} else {
return promise;
}
return user.signUp();
}
// Shims for compatibility with the old qunit tests.
@@ -275,37 +258,6 @@ function strictEqual(a, b, message) {
function notEqual(a, b, message) {
expect(a).not.toEqual(b, message);
}
function expectSuccess(params, done) {
return {
success: params.success,
error: function() {
fail('failure happened in expectSuccess');
done ? done() : null;
},
}
}
function expectError(errorCode, callback) {
return {
success: function(result) {
console.log('got result', result);
fail('expected error but got success');
},
error: function(obj, e) {
// Some methods provide 2 parameters.
e = e || obj;
if (errorCode !== undefined) {
if (!e) {
fail('expected a specific error but got a blank error');
return;
}
expect(e.code).toEqual(errorCode, e.message);
}
if (callback) {
callback(e);
}
},
}
}
// Because node doesn't have Parse._.contains
function arrayContains(arr, item) {
@@ -397,8 +349,6 @@ global.ok = ok;
global.equal = equal;
global.strictEqual = strictEqual;
global.notEqual = notEqual;
global.expectSuccess = expectSuccess;
global.expectError = expectError;
global.arrayContains = arrayContains;
global.jequal = jequal;
global.range = range;

View File

@@ -292,7 +292,7 @@ describe('server', () => {
}).then((obj) => {
expect(obj.id).toEqual(objId);
server.close(done);
}).fail(() => {
}).catch(() => {
server.close(done);
})
});

View File

@@ -174,7 +174,7 @@ class ParseLiveQueryServer {
// subscription, we do not need to check ACL
let originalACLCheckingPromise;
if (!isOriginalSubscriptionMatched) {
originalACLCheckingPromise = Parse.Promise.as(false);
originalACLCheckingPromise = Promise.resolve(false);
} else {
let originalACL;
if (message.originalParseObject) {
@@ -186,16 +186,18 @@ class ParseLiveQueryServer {
// subscription, we do not need to check ACL
let currentACLCheckingPromise;
if (!isCurrentSubscriptionMatched) {
currentACLCheckingPromise = Parse.Promise.as(false);
currentACLCheckingPromise = Promise.resolve(false);
} else {
const currentACL = message.currentParseObject.getACL();
currentACLCheckingPromise = this._matchesACL(currentACL, client, requestId);
}
Parse.Promise.when(
originalACLCheckingPromise,
currentACLCheckingPromise
).then((isOriginalMatched, isCurrentMatched) => {
Promise.all(
[
originalACLCheckingPromise,
currentACLCheckingPromise
]
).then(([isOriginalMatched, isCurrentMatched]) => {
logger.verbose('Original %j | Current %j | Match: %s, %s, %s, %s | Query: %s',
originalParseObject,
currentParseObject,
@@ -330,12 +332,12 @@ class ParseLiveQueryServer {
_matchesACL(acl: any, client: any, requestId: number): any {
// Return true directly if ACL isn't present, ACL is public read, or client has master key
if (!acl || acl.getPublicReadAccess() || client.hasMasterKey) {
return Parse.Promise.as(true);
return Promise.resolve(true);
}
// Check subscription sessionToken matches ACL first
const subscriptionInfo = client.getSubscriptionInfo(requestId);
if (typeof subscriptionInfo === 'undefined') {
return Parse.Promise.as(false);
return Promise.resolve(false);
}
const subscriptionSessionToken = subscriptionInfo.sessionToken;
@@ -343,11 +345,11 @@ class ParseLiveQueryServer {
return acl.getReadAccess(userId);
}).then((isSubscriptionSessionTokenMatched) => {
if (isSubscriptionSessionTokenMatched) {
return Parse.Promise.as(true);
return Promise.resolve(true);
}
// Check if the user has any roles that match the ACL
return new Parse.Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
// Resolve false right away if the acl doesn't have any roles
const acl_has_roles = Object.keys(acl.permissionsById).some(key => key.startsWith("role:"));
@@ -360,7 +362,7 @@ class ParseLiveQueryServer {
// Pass along a null if there is no user id
if (!userId) {
return Parse.Promise.as(null);
return Promise.resolve(null);
}
// Prepare a user object to query for roles
@@ -374,7 +376,7 @@ class ParseLiveQueryServer {
// Pass along an empty array (of roles) if no user
if (!user) {
return Parse.Promise.as([]);
return Promise.resolve([]);
}
// Then get the user's roles
@@ -400,7 +402,7 @@ class ParseLiveQueryServer {
}).then((isRoleMatched) => {
if(isRoleMatched) {
return Parse.Promise.as(true);
return Promise.resolve(true);
}
// Check client sessionToken matches ACL
@@ -409,9 +411,9 @@ class ParseLiveQueryServer {
return acl.getReadAccess(userId);
});
}).then((isMatched) => {
return Parse.Promise.as(isMatched);
return Promise.resolve(isMatched);
}, () => {
return Parse.Promise.as(false);
return Promise.resolve(false);
});
}

View File

@@ -7,7 +7,7 @@ function userForSessionToken(sessionToken){
q.equalTo("sessionToken", sessionToken);
return q.first({useMasterKey:true}).then(function(session){
if(!session){
return Parse.Promise.error("No session found for session token");
return Promise.reject("No session found for session token");
}
return session.get("user");
});
@@ -25,21 +25,21 @@ class SessionTokenCache {
getUserId(sessionToken: string): any {
if (!sessionToken) {
return Parse.Promise.error('Empty sessionToken');
return Promise.reject('Empty sessionToken');
}
const userId = this.cache.get(sessionToken);
if (userId) {
logger.verbose('Fetch userId %s of sessionToken %s from Cache', userId, sessionToken);
return Parse.Promise.as(userId);
return Promise.resolve(userId);
}
return userForSessionToken(sessionToken).then((user) => {
logger.verbose('Fetch userId %s of sessionToken %s from Parse', user.id, sessionToken);
const userId = user.id;
this.cache.set(sessionToken, userId);
return Parse.Promise.as(userId);
return Promise.resolve(userId);
}, (error) => {
logger.error('Can not fetch userId for sessionToken %j, error %j', sessionToken, error);
return Parse.Promise.error(error);
return Promise.reject(error);
});
}
}

View File

@@ -6,15 +6,15 @@ const Parse = require('parse/node');
function getSessionToken(options) {
if (options && typeof options.sessionToken === 'string') {
return Parse.Promise.as(options.sessionToken);
return Promise.resolve(options.sessionToken);
}
return Parse.Promise.as(null);
return Promise.resolve(null);
}
function getAuth(options = {}, config) {
const installationId = options.installationId || 'cloud';
if (options.useMasterKey) {
return Parse.Promise.as(new Auth.Auth({config, isMaster: true, installationId }));
return Promise.resolve(new Auth.Auth({config, isMaster: true, installationId }));
}
return getSessionToken(options).then((sessionToken) => {
if (sessionToken) {
@@ -25,7 +25,7 @@ function getAuth(options = {}, config) {
installationId
});
} else {
return Parse.Promise.as(new Auth.Auth({ config, installationId }));
return Promise.resolve(new Auth.Auth({ config, installationId }));
}
})
}
@@ -48,12 +48,12 @@ function ParseServerRESTController(applicationId, router) {
if (path === '/batch') {
const promises = data.requests.map((request) => {
return handleRequest(request.method, request.path, request.body, options).then((response) => {
return Parse.Promise.as({success: response});
return Promise.resolve({success: response});
}, (error) => {
return Parse.Promise.as({error: {code: error.code, error: error.message}});
return Promise.resolve({error: {code: error.code, error: error.message}});
});
});
return Parse.Promise.all(promises);
return Promise.all(promises);
}
let query;
@@ -61,7 +61,7 @@ function ParseServerRESTController(applicationId, router) {
query = data;
}
return new Parse.Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
getAuth(options, config).then((auth) => {
const request = {
body: data,

View File

@@ -1,5 +1,4 @@
import request from 'request';
import Parse from 'parse/node';
import HTTPResponse from './HTTPResponse';
import querystring from 'querystring';
import log from '../logger';
@@ -35,7 +34,6 @@ var encodeBody = function({body, headers = {}}) {
}
module.exports = function(options) {
var promise = new Parse.Promise();
var callbacks = {
success: options.success,
error: options.error
@@ -54,30 +52,30 @@ module.exports = function(options) {
}
// force the response as a buffer
options.encoding = null;
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error) {
if (callbacks.error) {
callbacks.error(error);
}
return reject(error);
}
const httpResponse = new HTTPResponse(response, body);
request(options, (error, response, body) => {
if (error) {
if (callbacks.error) {
callbacks.error(error);
// Consider <200 && >= 400 as errors
if (httpResponse.status < 200 || httpResponse.status >= 400) {
if (callbacks.error) {
callbacks.error(httpResponse);
}
return reject(httpResponse);
} else {
if (callbacks.success) {
callbacks.success(httpResponse);
}
return resolve(httpResponse);
}
return promise.reject(error);
}
const httpResponse = new HTTPResponse(response, body);
// Consider <200 && >= 400 as errors
if (httpResponse.status < 200 || httpResponse.status >= 400) {
if (callbacks.error) {
callbacks.error(httpResponse);
}
return promise.reject(httpResponse);
} else {
if (callbacks.success) {
callbacks.success(httpResponse);
}
return promise.resolve(httpResponse);
}
});
});
return promise;
};
module.exports.encodeBody = encodeBody;