diff --git a/.prettierrc b/.prettierrc index 28635227..31fa426f 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,4 +1,5 @@ semi: true trailingComma: "es5" singleQuote: true -arrowParens: "avoid" \ No newline at end of file +arrowParens: "avoid" +printWidth: 100 \ No newline at end of file diff --git a/package.json b/package.json index 65ad1725..70042179 100644 --- a/package.json +++ b/package.json @@ -105,7 +105,7 @@ "posttest": "cross-env MONGODB_VERSION=${MONGODB_VERSION:=4.0.4} MONGODB_TOPOLOGY=${MONGODB_TOPOLOGY:=standalone} MONGODB_STORAGE_ENGINE=${MONGODB_STORAGE_ENGINE:=mmapv1} mongodb-runner stop", "coverage": "cross-env MONGODB_VERSION=${MONGODB_VERSION:=4.0.4} MONGODB_TOPOLOGY=${MONGODB_TOPOLOGY:=standalone} MONGODB_STORAGE_ENGINE=${MONGODB_STORAGE_ENGINE:=mmapv1} TESTING=1 nyc jasmine", "start": "node ./bin/parse-server", - "prettier": "prettier --write {src,spec}/**/*.js", + "prettier": "prettier --write {src,spec}/{**/*,*}.js", "prepare": "npm run build", "postinstall": "node -p 'require(\"./postinstall.js\")()'" }, @@ -133,7 +133,7 @@ } }, "lint-staged": { - "{src,spec}/**/*.js": [ + "{src,spec}/{**/*,*}.js": [ "prettier --write", "eslint --fix --cache", "git add" diff --git a/spec/AccountLockoutPolicy.spec.js b/spec/AccountLockoutPolicy.spec.js index 5fac8a70..7e3f9a93 100644 --- a/spec/AccountLockoutPolicy.spec.js +++ b/spec/AccountLockoutPolicy.spec.js @@ -2,7 +2,7 @@ const Config = require('../lib/Config'); -const loginWithWrongCredentialsShouldFail = function(username, password) { +const loginWithWrongCredentialsShouldFail = function (username, password) { return new Promise((resolve, reject) => { Parse.User.logIn(username, password) .then(() => reject('login should have failed')) @@ -16,7 +16,7 @@ const loginWithWrongCredentialsShouldFail = function(username, password) { }); }; -const isAccountLockoutError = function(username, password, duration, waitTime) { +const isAccountLockoutError = function (username, password, duration, waitTime) { return new Promise((resolve, reject) => { setTimeout(() => { Parse.User.logIn(username, password) @@ -50,28 +50,17 @@ describe('Account Lockout Policy: ', () => { return user.signUp(null); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username1', - 'incorrect password 1' - ); + return loginWithWrongCredentialsShouldFail('username1', 'incorrect password 1'); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username1', - 'incorrect password 2' - ); + return loginWithWrongCredentialsShouldFail('username1', 'incorrect password 2'); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username1', - 'incorrect password 3' - ); + return loginWithWrongCredentialsShouldFail('username1', 'incorrect password 3'); }) .then(() => done()) .catch(err => { - fail( - 'allow unlimited failed login attempts failed: ' + JSON.stringify(err) - ); + fail('allow unlimited failed login attempts failed: ' + JSON.stringify(err)); done(); }); }); @@ -93,15 +82,11 @@ describe('Account Lockout Policy: ', () => { .catch(err => { if ( err && - err === - 'Account lockout duration should be greater than 0 and less than 100000' + err === 'Account lockout duration should be greater than 0 and less than 100000' ) { done(); } else { - fail( - 'set duration to an invalid number test failed: ' + - JSON.stringify(err) - ); + fail('set duration to an invalid number test failed: ' + JSON.stringify(err)); done(); } }); @@ -124,15 +109,11 @@ describe('Account Lockout Policy: ', () => { .catch(err => { if ( err && - err === - 'Account lockout threshold should be an integer greater than 0 and less than 1000' + err === 'Account lockout threshold should be an integer greater than 0 and less than 1000' ) { done(); } else { - fail( - 'set threshold to an invalid number test failed: ' + - JSON.stringify(err) - ); + fail('set threshold to an invalid number test failed: ' + JSON.stringify(err)); done(); } }); @@ -155,14 +136,11 @@ describe('Account Lockout Policy: ', () => { .catch(err => { if ( err && - err === - 'Account lockout threshold should be an integer greater than 0 and less than 1000' + err === 'Account lockout threshold should be an integer greater than 0 and less than 1000' ) { done(); } else { - fail( - 'threshold value < 1 is invalid test failed: ' + JSON.stringify(err) - ); + fail('threshold value < 1 is invalid test failed: ' + JSON.stringify(err)); done(); } }); @@ -185,15 +163,11 @@ describe('Account Lockout Policy: ', () => { .catch(err => { if ( err && - err === - 'Account lockout threshold should be an integer greater than 0 and less than 1000' + err === 'Account lockout threshold should be an integer greater than 0 and less than 1000' ) { done(); } else { - fail( - 'threshold value > 999 is invalid test failed: ' + - JSON.stringify(err) - ); + fail('threshold value > 999 is invalid test failed: ' + JSON.stringify(err)); done(); } }); @@ -216,14 +190,11 @@ describe('Account Lockout Policy: ', () => { .catch(err => { if ( err && - err === - 'Account lockout duration should be greater than 0 and less than 100000' + err === 'Account lockout duration should be greater than 0 and less than 100000' ) { done(); } else { - fail( - 'duration value < 1 is invalid test failed: ' + JSON.stringify(err) - ); + fail('duration value < 1 is invalid test failed: ' + JSON.stringify(err)); done(); } }); @@ -246,15 +217,11 @@ describe('Account Lockout Policy: ', () => { .catch(err => { if ( err && - err === - 'Account lockout duration should be greater than 0 and less than 100000' + err === 'Account lockout duration should be greater than 0 and less than 100000' ) { done(); } else { - fail( - 'duration value > 99999 is invalid test failed: ' + - JSON.stringify(err) - ); + fail('duration value > 99999 is invalid test failed: ' + JSON.stringify(err)); done(); } }); @@ -276,16 +243,10 @@ describe('Account Lockout Policy: ', () => { return user.signUp(); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username2', - 'wrong password' - ); + return loginWithWrongCredentialsShouldFail('username2', 'wrong password'); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username2', - 'wrong password' - ); + return loginWithWrongCredentialsShouldFail('username2', 'wrong password'); }) .then(() => { return isAccountLockoutError('username2', 'wrong password', 1, 1); @@ -294,10 +255,7 @@ describe('Account Lockout Policy: ', () => { done(); }) .catch(err => { - fail( - 'lock account after failed login attempts test failed: ' + - JSON.stringify(err) - ); + fail('lock account after failed login attempts test failed: ' + JSON.stringify(err)); done(); }); }); @@ -318,16 +276,10 @@ describe('Account Lockout Policy: ', () => { return user.signUp(); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username3', - 'wrong password' - ); + return loginWithWrongCredentialsShouldFail('username3', 'wrong password'); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username3', - 'wrong password' - ); + return loginWithWrongCredentialsShouldFail('username3', 'wrong password'); }) .then(() => { return isAccountLockoutError('username3', 'wrong password', 0.05, 1); @@ -340,10 +292,7 @@ describe('Account Lockout Policy: ', () => { done(); }) .catch(err => { - fail( - 'account should be locked for duration mins test failed: ' + - JSON.stringify(err) - ); + fail('account should be locked for duration mins test failed: ' + JSON.stringify(err)); done(); }); }); @@ -364,16 +313,10 @@ describe('Account Lockout Policy: ', () => { return user.signUp(); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username4', - 'wrong password' - ); + return loginWithWrongCredentialsShouldFail('username4', 'wrong password'); }) .then(() => { - return loginWithWrongCredentialsShouldFail( - 'username4', - 'wrong password' - ); + return loginWithWrongCredentialsShouldFail('username4', 'wrong password'); }) .then(() => { // allow locked user to login after 3 seconds with a valid userid and password diff --git a/spec/AdaptableController.spec.js b/spec/AdaptableController.spec.js index d0bfb164..4cda42e1 100644 --- a/spec/AdaptableController.spec.js +++ b/spec/AdaptableController.spec.js @@ -1,10 +1,8 @@ -const AdaptableController = require('../lib/Controllers/AdaptableController') - .AdaptableController; +const AdaptableController = require('../lib/Controllers/AdaptableController').AdaptableController; const FilesAdapter = require('../lib/Adapters/Files/FilesAdapter').default; -const FilesController = require('../lib/Controllers/FilesController') - .FilesController; +const FilesController = require('../lib/Controllers/FilesController').FilesController; -const MockController = function(options) { +const MockController = function (options) { AdaptableController.call(this, options); }; MockController.prototype = Object.create(AdaptableController.prototype); @@ -60,11 +58,11 @@ describe('AdaptableController', () => { it('should accept an object adapter', done => { const adapter = { - createFile: function() {}, - deleteFile: function() {}, - getFileData: function() {}, - getFileLocation: function() {}, - validateFilename: function() {}, + createFile: function () {}, + deleteFile: function () {}, + getFileData: function () {}, + getFileLocation: function () {}, + validateFilename: function () {}, }; expect(() => { new FilesController(adapter); @@ -74,11 +72,11 @@ describe('AdaptableController', () => { it('should accept an prototype based object adapter', done => { function AGoodAdapter() {} - AGoodAdapter.prototype.createFile = function() {}; - AGoodAdapter.prototype.deleteFile = function() {}; - AGoodAdapter.prototype.getFileData = function() {}; - AGoodAdapter.prototype.getFileLocation = function() {}; - AGoodAdapter.prototype.validateFilename = function() {}; + AGoodAdapter.prototype.createFile = function () {}; + AGoodAdapter.prototype.deleteFile = function () {}; + AGoodAdapter.prototype.getFileData = function () {}; + AGoodAdapter.prototype.getFileLocation = function () {}; + AGoodAdapter.prototype.validateFilename = function () {}; const adapter = new AGoodAdapter(); expect(() => { diff --git a/spec/AdapterLoader.spec.js b/spec/AdapterLoader.spec.js index 9f1f5264..af23c146 100644 --- a/spec/AdapterLoader.spec.js +++ b/spec/AdapterLoader.spec.js @@ -31,9 +31,7 @@ describe('AdapterLoader', () => { }); it('should instantiate an adapter from string that is module', done => { - const adapterPath = require('path').resolve( - './lib/Adapters/Files/FilesAdapter' - ); + const adapterPath = require('path').resolve('./lib/Adapters/Files/FilesAdapter'); const adapter = loadAdapter({ adapter: adapterPath, }); @@ -88,14 +86,14 @@ describe('AdapterLoader', () => { }); it('should fail loading an improperly configured adapter', done => { - const Adapter = function(options) { + const Adapter = function (options) { if (!options.foo) { throw 'foo is required for that adapter'; } }; const adapterOptions = { param: 'key', - doSomething: function() {}, + doSomething: function () {}, }; expect(() => { diff --git a/spec/AggregateRouter.spec.js b/spec/AggregateRouter.spec.js index e0f9bac1..665c51e8 100644 --- a/spec/AggregateRouter.spec.js +++ b/spec/AggregateRouter.spec.js @@ -1,5 +1,4 @@ -const AggregateRouter = require('../lib/Routers/AggregateRouter') - .AggregateRouter; +const AggregateRouter = require('../lib/Routers/AggregateRouter').AggregateRouter; describe('AggregateRouter', () => { it('get pipeline from Array', () => { @@ -56,9 +55,7 @@ describe('AggregateRouter', () => { try { AggregateRouter.getPipeline(body); } catch (e) { - expect(e.message).toBe( - 'Pipeline stages should only have one key found group, match' - ); + expect(e.message).toBe('Pipeline stages should only have one key found group, match'); } }); @@ -74,9 +71,7 @@ describe('AggregateRouter', () => { try { AggregateRouter.getPipeline(body); } catch (e) { - expect(e.message).toBe( - 'Pipeline stages should only have one key found group, match' - ); + expect(e.message).toBe('Pipeline stages should only have one key found group, match'); } }); }); diff --git a/spec/Analytics.spec.js b/spec/Analytics.spec.js index b608aebe..049a2795 100644 --- a/spec/Analytics.spec.js +++ b/spec/Analytics.spec.js @@ -1,6 +1,6 @@ const analyticsAdapter = { - appOpened: function() {}, - trackEvent: function() {}, + appOpened: function () {}, + trackEvent: function () {}, }; describe('AnalyticsController', () => { diff --git a/spec/AudienceRouter.spec.js b/spec/AudienceRouter.spec.js index ac75d52c..208e7834 100644 --- a/spec/AudienceRouter.spec.js +++ b/spec/AudienceRouter.spec.js @@ -2,8 +2,7 @@ const auth = require('../lib/Auth'); const Config = require('../lib/Config'); const rest = require('../lib/rest'); const request = require('../lib/request'); -const AudiencesRouter = require('../lib/Routers/AudiencesRouter') - .AudiencesRouter; +const AudiencesRouter = require('../lib/Routers/AudiencesRouter').AudiencesRouter; describe('AudiencesRouter', () => { it('uses find condition from request.body', done => { @@ -32,12 +31,7 @@ describe('AudiencesRouter', () => { rest .create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Audience', - iosAudienceRequest - ); + return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); }) .then(() => { return router.handleFind(request); @@ -79,12 +73,7 @@ describe('AudiencesRouter', () => { rest .create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Audience', - iosAudienceRequest - ); + return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); }) .then(() => { return router.handleFind(request); @@ -125,12 +114,7 @@ describe('AudiencesRouter', () => { rest .create(config, auth.nobody(config), '_Audience', androidAudienceRequest) .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Audience', - iosAudienceRequest - ); + return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); }) .then(() => { return router.handleFind(request); @@ -169,14 +153,7 @@ describe('AudiencesRouter', () => { const router = new AudiencesRouter(); rest .create(config, auth.nobody(config), '_Audience', androidAudienceRequest) - .then(() => - rest.create( - config, - auth.nobody(config), - '_Audience', - iosAudienceRequest - ) - ) + .then(() => rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest)) .then(() => router.handleFind(request)) .then(res => { const response = res.response; @@ -190,60 +167,47 @@ describe('AudiencesRouter', () => { }); }); - it_exclude_dbs(['postgres'])( - 'query installations with limit = 0 and count = 1', - done => { - const config = Config.get('test'); - const androidAudienceRequest = { - name: 'Android Users', - query: '{ "test": "android" }', - }; - const iosAudienceRequest = { - name: 'Iphone Users', - query: '{ "test": "ios" }', - }; - const request = { - config: config, - auth: auth.master(config), - body: {}, - query: { - limit: 0, - count: 1, - }, - info: {}, - }; + it_exclude_dbs(['postgres'])('query installations with limit = 0 and count = 1', done => { + const config = Config.get('test'); + const androidAudienceRequest = { + name: 'Android Users', + query: '{ "test": "android" }', + }; + const iosAudienceRequest = { + name: 'Iphone Users', + query: '{ "test": "ios" }', + }; + const request = { + config: config, + auth: auth.master(config), + body: {}, + query: { + limit: 0, + count: 1, + }, + info: {}, + }; - const router = new AudiencesRouter(); - rest - .create( - config, - auth.nobody(config), - '_Audience', - androidAudienceRequest - ) - .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Audience', - iosAudienceRequest - ); - }) - .then(() => { - return router.handleFind(request); - }) - .then(res => { - const response = res.response; - expect(response.results.length).toEqual(0); - expect(response.count).toEqual(2); - done(); - }) - .catch(err => { - fail(JSON.stringify(err)); - done(); - }); - } - ); + const router = new AudiencesRouter(); + rest + .create(config, auth.nobody(config), '_Audience', androidAudienceRequest) + .then(() => { + return rest.create(config, auth.nobody(config), '_Audience', iosAudienceRequest); + }) + .then(() => { + return router.handleFind(request); + }) + .then(res => { + const response = res.response; + expect(response.results.length).toEqual(0); + expect(response.count).toEqual(2); + done(); + }) + .catch(err => { + fail(JSON.stringify(err)); + done(); + }); + }); it('should create, read, update and delete audiences throw api', done => { Parse._request( @@ -252,54 +216,49 @@ describe('AudiencesRouter', () => { { name: 'My Audience', query: JSON.stringify({ deviceType: 'ios' }) }, { useMasterKey: true } ).then(() => { - Parse._request('GET', 'push_audiences', {}, { useMasterKey: true }).then( - results => { - expect(results.results.length).toEqual(1); - expect(results.results[0].name).toEqual('My Audience'); - expect(results.results[0].query.deviceType).toEqual('ios'); + Parse._request('GET', 'push_audiences', {}, { useMasterKey: true }).then(results => { + expect(results.results.length).toEqual(1); + expect(results.results[0].name).toEqual('My Audience'); + expect(results.results[0].query.deviceType).toEqual('ios'); + Parse._request( + 'GET', + `push_audiences/${results.results[0].objectId}`, + {}, + { useMasterKey: true } + ).then(results => { + expect(results.name).toEqual('My Audience'); + expect(results.query.deviceType).toEqual('ios'); Parse._request( - 'GET', - `push_audiences/${results.results[0].objectId}`, - {}, + 'PUT', + `push_audiences/${results.objectId}`, + { name: 'My Audience 2' }, { useMasterKey: true } - ).then(results => { - expect(results.name).toEqual('My Audience'); - expect(results.query.deviceType).toEqual('ios'); + ).then(() => { Parse._request( - 'PUT', + 'GET', `push_audiences/${results.objectId}`, - { name: 'My Audience 2' }, + {}, { useMasterKey: true } - ).then(() => { + ).then(results => { + expect(results.name).toEqual('My Audience 2'); + expect(results.query.deviceType).toEqual('ios'); Parse._request( - 'GET', + 'DELETE', `push_audiences/${results.objectId}`, {}, { useMasterKey: true } - ).then(results => { - expect(results.name).toEqual('My Audience 2'); - expect(results.query.deviceType).toEqual('ios'); - Parse._request( - 'DELETE', - `push_audiences/${results.objectId}`, - {}, - { useMasterKey: true } - ).then(() => { - Parse._request( - 'GET', - 'push_audiences', - {}, - { useMasterKey: true } - ).then(results => { + ).then(() => { + Parse._request('GET', 'push_audiences', {}, { useMasterKey: true }).then( + results => { expect(results.results.length).toEqual(0); done(); - }); - }); + } + ); }); }); }); - } - ); + }); + }); }); }); @@ -358,58 +317,54 @@ describe('AudiencesRouter', () => { ); }); - it_exclude_dbs(['postgres'])( - 'should support legacy parse.com audience fields', - done => { - const database = Config.get(Parse.applicationId).database.adapter - .database; - const now = new Date(); - Parse._request( - 'POST', - 'push_audiences', - { name: 'My Audience', query: JSON.stringify({ deviceType: 'ios' }) }, - { useMasterKey: true } - ).then(audience => { - database.collection('test__Audience').updateOne( - { _id: audience.objectId }, - { - $set: { - times_used: 1, - _last_used: now, - }, + it_exclude_dbs(['postgres'])('should support legacy parse.com audience fields', done => { + const database = Config.get(Parse.applicationId).database.adapter.database; + const now = new Date(); + Parse._request( + 'POST', + 'push_audiences', + { name: 'My Audience', query: JSON.stringify({ deviceType: 'ios' }) }, + { useMasterKey: true } + ).then(audience => { + database.collection('test__Audience').updateOne( + { _id: audience.objectId }, + { + $set: { + times_used: 1, + _last_used: now, }, - {}, - error => { - expect(error).toEqual(null); - database - .collection('test__Audience') - .find({ _id: audience.objectId }) - .toArray((error, rows) => { - expect(error).toEqual(null); - expect(rows[0]['times_used']).toEqual(1); - expect(rows[0]['_last_used']).toEqual(now); - Parse._request( - 'GET', - 'push_audiences/' + audience.objectId, - {}, - { useMasterKey: true } - ) - .then(audience => { - expect(audience.name).toEqual('My Audience'); - expect(audience.query.deviceType).toEqual('ios'); - expect(audience.timesUsed).toEqual(1); - expect(audience.lastUsed).toEqual(now.toISOString()); - done(); - }) - .catch(error => { - done.fail(error); - }); - }); - } - ); - }); - } - ); + }, + {}, + error => { + expect(error).toEqual(null); + database + .collection('test__Audience') + .find({ _id: audience.objectId }) + .toArray((error, rows) => { + expect(error).toEqual(null); + expect(rows[0]['times_used']).toEqual(1); + expect(rows[0]['_last_used']).toEqual(now); + Parse._request( + 'GET', + 'push_audiences/' + audience.objectId, + {}, + { useMasterKey: true } + ) + .then(audience => { + expect(audience.name).toEqual('My Audience'); + expect(audience.query.deviceType).toEqual('ios'); + expect(audience.timesUsed).toEqual(1); + expect(audience.lastUsed).toEqual(now.toISOString()); + done(); + }) + .catch(error => { + done.fail(error); + }); + }); + } + ); + }); + }); it('should be able to search on audiences', done => { Parse._request( diff --git a/spec/Auth.spec.js b/spec/Auth.spec.js index 0884218f..ede7eeed 100644 --- a/spec/Auth.spec.js +++ b/spec/Auth.spec.js @@ -83,8 +83,8 @@ describe('Auth', () => { it('should properly handle bcrypt upgrade', done => { const bcryptOriginal = require('bcrypt-nodejs'); const bcryptNew = require('bcryptjs'); - bcryptOriginal.hash('my1Long:password', null, null, function(err, res) { - bcryptNew.compare('my1Long:password', res, function(err, res) { + bcryptOriginal.hash('my1Long:password', null, null, function (err, res) { + bcryptNew.compare('my1Long:password', res, function (err, res) { expect(res).toBeTruthy(); done(); }); diff --git a/spec/AuthenticationAdapters.spec.js b/spec/AuthenticationAdapters.spec.js index a3f3ab5e..87679d02 100644 --- a/spec/AuthenticationAdapters.spec.js +++ b/spec/AuthenticationAdapters.spec.js @@ -1,7 +1,6 @@ const request = require('../lib/request'); const Config = require('../lib/Config'); -const defaultColumns = require('../lib/Controllers/SchemaController') - .defaultColumns; +const defaultColumns = require('../lib/Controllers/SchemaController').defaultColumns; const authenticationLoader = require('../lib/Adapters/Auth'); const path = require('path'); const responses = { @@ -49,10 +48,7 @@ describe('AuthenticationProviders', function () { jequal(typeof provider.validateAppId, 'function'); const validateAuthDataPromise = provider.validateAuthData({}, {}); const validateAppIdPromise = provider.validateAppId('app', 'key', {}); - jequal( - validateAuthDataPromise.constructor, - Promise.prototype.constructor - ); + jequal(validateAuthDataPromise.constructor, Promise.prototype.constructor); jequal(validateAppIdPromise.constructor, Promise.prototype.constructor); validateAuthDataPromise.then( () => {}, @@ -70,25 +66,20 @@ describe('AuthenticationProviders', function () { if (noResponse.includes(providerName)) { return; } - spyOn(require('../lib/Adapters/Auth/httpsRequest'), 'get').and.callFake( - options => { - if ( - options === - 'https://oauth.vk.com/access_token?client_id=appId&client_secret=appSecret&v=5.123&grant_type=client_credentials' || - options === - 'https://oauth.vk.com/access_token?client_id=appId&client_secret=appSecret&v=5.124&grant_type=client_credentials' - ) { - return { - access_token: 'access_token', - }; - } - return Promise.resolve(responses[providerName] || { id: 'userId' }); + spyOn(require('../lib/Adapters/Auth/httpsRequest'), 'get').and.callFake(options => { + if ( + options === + 'https://oauth.vk.com/access_token?client_id=appId&client_secret=appSecret&v=5.123&grant_type=client_credentials' || + options === + 'https://oauth.vk.com/access_token?client_id=appId&client_secret=appSecret&v=5.124&grant_type=client_credentials' + ) { + return { + access_token: 'access_token', + }; } - ); - spyOn( - require('../lib/Adapters/Auth/httpsRequest'), - 'request' - ).and.callFake(() => { + return Promise.resolve(responses[providerName] || { id: 'userId' }); + }); + spyOn(require('../lib/Adapters/Auth/httpsRequest'), 'request').and.callFake(() => { return Promise.resolve(responses[providerName] || { id: 'userId' }); }); const provider = require('../lib/Adapters/Auth/' + providerName); @@ -274,10 +265,7 @@ describe('AuthenticationProviders', function () { 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 - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('myoauth'), 'User should be linked to myoauth'); await model._unlinkFrom('myoauth'); @@ -290,11 +278,7 @@ describe('AuthenticationProviders', function () { const res = await config.database.adapter.find( '_User', { - fields: Object.assign( - {}, - defaultColumns._Default, - defaultColumns._Installation - ), + fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation), }, { objectId: model.id }, {} @@ -317,12 +301,8 @@ describe('AuthenticationProviders', function () { function validateAuthenticationHandler(authenticationHandler) { expect(authenticationHandler).not.toBeUndefined(); - expect(typeof authenticationHandler.getValidatorForProvider).toBe( - 'function' - ); - expect(typeof authenticationHandler.getValidatorForProvider).toBe( - 'function' - ); + expect(typeof authenticationHandler.getValidatorForProvider).toBe('function'); + expect(typeof authenticationHandler.getValidatorForProvider).toBe('function'); } function validateAuthenticationAdapter(authAdapter) { @@ -344,10 +324,7 @@ describe('AuthenticationProviders', function () { return Promise.resolve(); }, validateAuthData: function (authData) { - if ( - authData.id == validAuthData.id && - authData.token == validAuthData.token - ) { + if (authData.id == validAuthData.id && authData.token == validAuthData.token) { return Promise.resolve(); } return Promise.reject(); @@ -362,9 +339,7 @@ describe('AuthenticationProviders', function () { }); validateAuthenticationHandler(authenticationHandler); - const validator = authenticationHandler.getValidatorForProvider( - 'customAuthentication' - ); + const validator = authenticationHandler.getValidatorForProvider('customAuthentication'); validateValidator(validator); validator(validAuthData).then( @@ -387,9 +362,7 @@ describe('AuthenticationProviders', function () { }); validateAuthenticationHandler(authenticationHandler); - const validator = authenticationHandler.getValidatorForProvider( - 'customAuthentication' - ); + const validator = authenticationHandler.getValidatorForProvider('customAuthentication'); validateValidator(validator); validator({ @@ -414,9 +387,7 @@ describe('AuthenticationProviders', function () { }); validateAuthenticationHandler(authenticationHandler); - const validator = authenticationHandler.getValidatorForProvider( - 'customAuthentication' - ); + const validator = authenticationHandler.getValidatorForProvider('customAuthentication'); validateValidator(validator); validator({ @@ -439,11 +410,10 @@ describe('AuthenticationProviders', function () { appSecret: 'secret', }, }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('facebook', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'facebook', + options + ); validateAuthenticationAdapter(adapter); expect(appIds).toEqual(['a', 'b']); expect(providerOptions).toEqual(options.facebook); @@ -463,15 +433,12 @@ describe('AuthenticationProviders', function () { const authData = { access_token: 'badtoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('facebook', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'facebook', + options + ); await adapter.validateAppId(appIds, authData, providerOptions); - expect( - httpsRequest.get.calls.first().args[0].includes('appsecret_proof') - ).toBe(true); + expect(httpsRequest.get.calls.first().args[0].includes('appsecret_proof')).toBe(true); }); it('should handle Facebook appSecret for validating auth data', async () => { @@ -489,14 +456,9 @@ describe('AuthenticationProviders', function () { id: 'test', access_token: 'test', }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'facebook', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('facebook', options); await adapter.validateAuthData(authData, providerOptions); - expect( - httpsRequest.get.calls.first().args[0].includes('appsecret_proof') - ).toBe(true); + expect(httpsRequest.get.calls.first().args[0].includes('appsecret_proof')).toBe(true); }); it('properly loads a custom adapter with options', () => { @@ -507,11 +469,10 @@ describe('AuthenticationProviders', function () { appIds: ['a', 'b'], }, }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('custom', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'custom', + options + ); validateAuthenticationAdapter(adapter); expect(appIds).toEqual(['a', 'b']); expect(providerOptions).toEqual(options.custom); @@ -526,10 +487,7 @@ describe('instagram auth adapter', () => { spyOn(httpsRequest, 'get').and.callFake(() => { return Promise.resolve({ data: { id: 'userId' } }); }); - await instagram.validateAuthData( - { id: 'userId', access_token: 'the_token' }, - {} - ); + await instagram.validateAuthData({ id: 'userId', access_token: 'the_token' }, {}); expect(httpsRequest.get).toHaveBeenCalledWith( 'https://graph.instagram.com/me?fields=id&access_token=the_token' ); @@ -568,10 +526,7 @@ describe('google auth adapter', () => { it('should not decode invalid id_token', async () => { try { - await google.validateAuthData( - { id: 'the_user_id', id_token: 'the_token' }, - {} - ); + await google.validateAuthData({ id: 'the_user_id', id_token: 'the_token' }, {}); fail(); } catch (e) { expect(e.message).toBe('provided token does not decode as JWT'); @@ -701,9 +656,7 @@ describe('google play games service auth', () => { access_token: 'access_token', }); } catch (e) { - expect(e.message).toBe( - 'Google Play Games Services - authData is invalid for this user.' - ); + expect(e.message).toBe('Google Play Games Services - authData is invalid for this user.'); } }); }); @@ -746,10 +699,7 @@ describe('keycloak auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'keycloak', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', options); try { await adapter.validateAuthData(authData, providerOptions); fail(); @@ -776,10 +726,7 @@ describe('keycloak auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'keycloak', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', options); try { await adapter.validateAuthData(authData, providerOptions); fail(); @@ -806,10 +753,7 @@ describe('keycloak auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'keycloak', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', options); try { await adapter.validateAuthData(authData, providerOptions); fail(); @@ -834,10 +778,7 @@ describe('keycloak auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'keycloak', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', options); try { await adapter.validateAuthData(authData, providerOptions); fail(); @@ -870,10 +811,7 @@ describe('keycloak auth adapter', () => { roles: ['role1'], groups: ['group1'], }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'keycloak', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', options); try { await adapter.validateAuthData(authData, providerOptions); fail(); @@ -906,10 +844,7 @@ describe('keycloak auth adapter', () => { roles: ['role1'], groups: ['group1'], }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'keycloak', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', options); try { await adapter.validateAuthData(authData, providerOptions); fail(); @@ -942,10 +877,7 @@ describe('keycloak auth adapter', () => { roles: ['role1'], groups: ['group1'], }; - const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter( - 'keycloak', - options - ); + const { adapter, providerOptions } = authenticationLoader.loadAuthAdapter('keycloak', options); await adapter.validateAuthData(authData, providerOptions); expect(httpsRequest.get).toHaveBeenCalledWith({ host: 'http://example.com', @@ -967,10 +899,7 @@ describe('oauth2 auth adapter', () => { oauth2: true, }, }; - const loadedAuthAdapter = authenticationLoader.loadAuthAdapter( - 'oauth2Authentication', - options - ); + const loadedAuthAdapter = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); expect(loadedAuthAdapter.adapter).toEqual(oauth2); }); @@ -986,21 +915,14 @@ describe('oauth2 auth adapter', () => { debug: true, }, }; - const loadedAuthAdapter = authenticationLoader.loadAuthAdapter( - 'oauth2Authentication', - options - ); + const loadedAuthAdapter = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); const appIds = loadedAuthAdapter.appIds; const providerOptions = loadedAuthAdapter.providerOptions; - expect(providerOptions.tokenIntrospectionEndpointUrl).toEqual( - 'https://example.com/introspect' - ); + expect(providerOptions.tokenIntrospectionEndpointUrl).toEqual('https://example.com/introspect'); expect(providerOptions.useridField).toEqual('sub'); expect(providerOptions.appidField).toEqual('appId'); expect(appIds).toEqual(['a', 'b']); - expect(providerOptions.authorizationHeader).toEqual( - 'Basic dXNlcm5hbWU6cGFzc3dvcmQ=' - ); + expect(providerOptions.authorizationHeader).toEqual('Basic dXNlcm5hbWU6cGFzc3dvcmQ='); expect(providerOptions.debug).toEqual(true); }); @@ -1016,11 +938,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); try { await adapter.validateAppId(appIds, authData, providerOptions); } catch (e) { @@ -1041,11 +962,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); try { await adapter.validateAppId(appIds, authData, providerOptions); } catch (e) { @@ -1066,11 +986,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); try { await adapter.validateAppId(appIds, authData, providerOptions); } catch (e) { @@ -1093,11 +1012,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); try { await adapter.validateAppId(appIds, authData, providerOptions); } catch (e) { @@ -1120,11 +1038,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); spyOn(httpsRequest, 'request').and.callFake(() => { return Promise.resolve({}); }); @@ -1148,11 +1065,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); spyOn(httpsRequest, 'request').and.callFake(() => { return Promise.resolve({ active: true }); }); @@ -1178,11 +1094,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); spyOn(httpsRequest, 'request').and.callFake(() => { return Promise.resolve({ active: true, @@ -1210,11 +1125,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); spyOn(httpsRequest, 'request').and.callFake(() => { return Promise.resolve({ active: true, @@ -1242,11 +1156,10 @@ describe('oauth2 auth adapter', () => { id: 'fakeid', access_token: 'sometoken', }; - const { - adapter, - appIds, - providerOptions, - } = authenticationLoader.loadAuthAdapter('oauth2Authentication', options); + const { adapter, appIds, providerOptions } = authenticationLoader.loadAuthAdapter( + 'oauth2Authentication', + options + ); spyOn(httpsRequest, 'request').and.callFake(() => { return Promise.resolve({ active: true, @@ -1475,9 +1388,7 @@ describe('apple signin auth adapter', () => { { clientId: 'secret' } ); expect(result).toEqual(fakeClaim); - expect(jwt.verify.calls.first().args[2].algorithms).toEqual( - fakeDecodedToken.header.alg - ); + expect(jwt.verify.calls.first().args[2].algorithms).toEqual(fakeDecodedToken.header.alg); }); it('should not verify invalid id_token', async () => { @@ -1785,9 +1696,7 @@ describe('Apple Game Center Auth adapter', () => { await gcenter.validateAuthData(authData); fail(); } catch (e) { - expect(e.message).toBe( - 'Apple Game Center - invalid publicKeyUrl: invalid.com' - ); + expect(e.message).toBe('Apple Game Center - invalid publicKeyUrl: invalid.com'); } }); }); @@ -1802,9 +1711,7 @@ describe('phant auth adapter', () => { }; const { adapter } = authenticationLoader.loadAuthAdapter('phantauth', {}); - spyOn(httpsRequest, 'get').and.callFake(() => - Promise.resolve({ sub: 'invalidID' }) - ); + spyOn(httpsRequest, 'get').and.callFake(() => Promise.resolve({ sub: 'invalidID' })); try { await adapter.validateAuthData(authData); fail(); @@ -1836,9 +1743,7 @@ describe('microsoft graph auth adapter', () => { }; microsoft.validateAuthData(authData).then(done.fail, err => { expect(err.code).toBe(101); - expect(err.message).toBe( - 'Microsoft Graph auth is invalid for this user.' - ); + expect(err.message).toBe('Microsoft Graph auth is invalid for this user.'); done(); }); }); diff --git a/spec/CLI.spec.js b/spec/CLI.spec.js index a635d0f9..9cf42ca5 100644 --- a/spec/CLI.spec.js +++ b/spec/CLI.spec.js @@ -1,8 +1,7 @@ 'use strict'; const commander = require('../lib/cli/utils/commander').default; const definitions = require('../lib/cli/definitions/parse-server').default; -const liveQueryDefinitions = require('../lib/cli/definitions/parse-live-query-server') - .default; +const liveQueryDefinitions = require('../lib/cli/definitions/parse-live-query-server').default; const path = require('path'); const { spawn } = require('child_process'); @@ -14,7 +13,7 @@ const testDefinitions = { }, arg2: { env: 'PROGRAM_ARG_2', - action: function(value) { + action: function (value) { const intValue = parseInt(value); if (!Number.isInteger(intValue)) { throw 'arg2 is invalid'; @@ -77,15 +76,12 @@ describe('commander additions', () => { it('should load properly use args over env', done => { commander.loadDefinitions(testDefinitions); - commander.parse( - ['node', './CLI.spec.js', '--arg0', 'arg0Value', '--arg4', ''], - { - PROGRAM_ARG_0: 'arg0ENVValue', - PROGRAM_ARG_1: 'arg1ENVValue', - PROGRAM_ARG_2: '4', - PROGRAM_ARG_4: 'arg4ENVValue', - } - ); + commander.parse(['node', './CLI.spec.js', '--arg0', 'arg0Value', '--arg4', ''], { + PROGRAM_ARG_0: 'arg0ENVValue', + PROGRAM_ARG_1: 'arg1ENVValue', + PROGRAM_ARG_2: '4', + PROGRAM_ARG_4: 'arg4ENVValue', + }); expect(commander.arg0).toEqual('arg0Value'); expect(commander.arg1).toEqual('arg1ENVValue'); expect(commander.arg2).toEqual(4); @@ -109,13 +105,7 @@ describe('commander additions', () => { spyOn(console, 'log').and.callFake(() => {}); commander.loadDefinitions(testDefinitions); commander.parse( - [ - 'node', - './CLI.spec.js', - '--arg0', - 'arg0Value', - './spec/configs/CLIConfig.json', - ], + ['node', './CLI.spec.js', '--arg0', 'arg0Value', './spec/configs/CLIConfig.json'], { PROGRAM_ARG_0: 'arg0ENVValue', PROGRAM_ARG_1: 'arg1ENVValue', @@ -132,13 +122,7 @@ describe('commander additions', () => { commander.loadDefinitions(testDefinitions); expect(() => { commander.parse( - [ - 'node', - './CLI.spec.js', - '--arg0', - 'arg0Value', - './spec/configs/CLIConfigFail.json', - ], + ['node', './CLI.spec.js', '--arg0', 'arg0Value', './spec/configs/CLIConfigFail.json'], { PROGRAM_ARG_0: 'arg0ENVValue', PROGRAM_ARG_1: 'arg1ENVValue', @@ -151,11 +135,7 @@ describe('commander additions', () => { it('should fail when too many apps are set', done => { commander.loadDefinitions(testDefinitions); expect(() => { - commander.parse([ - 'node', - './CLI.spec.js', - './spec/configs/CLIConfigFailTooManyApps.json', - ]); + commander.parse(['node', './CLI.spec.js', './spec/configs/CLIConfigFailTooManyApps.json']); }).toThrow('Multiple apps are not supported'); done(); }); @@ -163,11 +143,7 @@ describe('commander additions', () => { it('should load config from apps', done => { spyOn(console, 'log').and.callFake(() => {}); commander.loadDefinitions(testDefinitions); - commander.parse([ - 'node', - './CLI.spec.js', - './spec/configs/CLIConfigApps.json', - ]); + commander.parse(['node', './CLI.spec.js', './spec/configs/CLIConfigApps.json']); const options = commander.getOptions(); expect(options.arg1).toBe('my_app'); expect(options.arg2).toBe(8888); @@ -179,11 +155,7 @@ describe('commander additions', () => { it('should fail when passing an invalid arguement', done => { commander.loadDefinitions(testDefinitions); expect(() => { - commander.parse([ - 'node', - './CLI.spec.js', - './spec/configs/CLIConfigUnknownArg.json', - ]); + commander.parse(['node', './CLI.spec.js', './spec/configs/CLIConfigUnknownArg.json']); }).toThrow('error: unknown option myArg'); done(); }); @@ -222,10 +194,7 @@ describe('LiveQuery definitions', () => { if (typeof definition.env !== 'undefined') { expect(typeof definition.env).toBe('string'); } - expect(typeof definition.help).toBe( - 'string', - `help for ${key} should be a string` - ); + expect(typeof definition.help).toBe('string', `help for ${key} should be a string`); if (typeof definition.required !== 'undefined') { expect(typeof definition.required).toBe('boolean'); } diff --git a/spec/CacheController.spec.js b/spec/CacheController.spec.js index 12f4269f..de071262 100644 --- a/spec/CacheController.spec.js +++ b/spec/CacheController.spec.js @@ -1,7 +1,6 @@ -const CacheController = require('../lib/Controllers/CacheController.js') - .default; +const CacheController = require('../lib/Controllers/CacheController.js').default; -describe('CacheController', function() { +describe('CacheController', function () { let FakeCacheAdapter; const FakeAppID = 'foo'; const KEY = 'hello'; diff --git a/spec/Client.spec.js b/spec/Client.spec.js index 400503d2..0de22620 100644 --- a/spec/Client.spec.js +++ b/spec/Client.spec.js @@ -1,9 +1,8 @@ const Client = require('../lib/LiveQuery/Client').Client; -const ParseWebSocket = require('../lib/LiveQuery/ParseWebSocketServer') - .ParseWebSocket; +const ParseWebSocket = require('../lib/LiveQuery/ParseWebSocketServer').ParseWebSocket; -describe('Client', function() { - it('can be initialized', function() { +describe('Client', function () { + it('can be initialized', function () { const parseWebSocket = new ParseWebSocket({}); const client = new Client(1, parseWebSocket); @@ -12,7 +11,7 @@ describe('Client', function() { expect(client.subscriptionInfos.size).toBe(0); }); - it('can push response', function() { + it('can push response', function () { const parseWebSocket = { send: jasmine.createSpy('send'), }; @@ -21,7 +20,7 @@ describe('Client', function() { expect(parseWebSocket.send).toHaveBeenCalledWith('message'); }); - it('can push error', function() { + it('can push error', function () { const parseWebSocket = { send: jasmine.createSpy('send'), }; @@ -35,7 +34,7 @@ describe('Client', function() { expect(messageJSON.reconnect).toBe(true); }); - it('can add subscription information', function() { + it('can add subscription information', function () { const subscription = {}; const fields = ['test']; const subscriptionInfo = { @@ -49,7 +48,7 @@ describe('Client', function() { expect(client.subscriptionInfos.get(1)).toBe(subscriptionInfo); }); - it('can get subscription information', function() { + it('can get subscription information', function () { const subscription = {}; const fields = ['test']; const subscriptionInfo = { @@ -63,7 +62,7 @@ describe('Client', function() { expect(subscriptionInfoAgain).toBe(subscriptionInfo); }); - it('can delete subscription information', function() { + it('can delete subscription information', function () { const subscription = {}; const fields = ['test']; const subscriptionInfo = { @@ -77,7 +76,7 @@ describe('Client', function() { expect(client.subscriptionInfos.size).toBe(0); }); - it('can generate ParseObject JSON with null selected field', function() { + it('can generate ParseObject JSON with null selected field', function () { const parseObjectJSON = { key: 'value', className: 'test', @@ -88,12 +87,10 @@ describe('Client', function() { }; const client = new Client(1, {}); - expect(client._toJSONWithFields(parseObjectJSON, null)).toBe( - parseObjectJSON - ); + expect(client._toJSONWithFields(parseObjectJSON, null)).toBe(parseObjectJSON); }); - it('can generate ParseObject JSON with undefined selected field', function() { + it('can generate ParseObject JSON with undefined selected field', function () { const parseObjectJSON = { key: 'value', className: 'test', @@ -104,12 +101,10 @@ describe('Client', function() { }; const client = new Client(1, {}); - expect(client._toJSONWithFields(parseObjectJSON, undefined)).toBe( - parseObjectJSON - ); + expect(client._toJSONWithFields(parseObjectJSON, undefined)).toBe(parseObjectJSON); }); - it('can generate ParseObject JSON with selected fields', function() { + it('can generate ParseObject JSON with selected fields', function () { const parseObjectJSON = { key: 'value', className: 'test', @@ -131,7 +126,7 @@ describe('Client', function() { }); }); - it('can generate ParseObject JSON with nonexistent selected fields', function() { + it('can generate ParseObject JSON with nonexistent selected fields', function () { const parseObjectJSON = { key: 'value', className: 'test', @@ -142,9 +137,7 @@ describe('Client', function() { test: 'test', }; const client = new Client(1, {}); - const limitedParseObject = client._toJSONWithFields(parseObjectJSON, [ - 'name', - ]); + const limitedParseObject = client._toJSONWithFields(parseObjectJSON, ['name']); expect(limitedParseObject).toEqual({ className: 'test', @@ -156,7 +149,7 @@ describe('Client', function() { expect('name' in limitedParseObject).toBe(false); }); - it('can push connect response', function() { + it('can push connect response', function () { const parseWebSocket = { send: jasmine.createSpy('send'), }; @@ -169,7 +162,7 @@ describe('Client', function() { expect(messageJSON.clientId).toBe(1); }); - it('can push subscribe response', function() { + it('can push subscribe response', function () { const parseWebSocket = { send: jasmine.createSpy('send'), }; @@ -183,7 +176,7 @@ describe('Client', function() { expect(messageJSON.requestId).toBe(2); }); - it('can push unsubscribe response', function() { + it('can push unsubscribe response', function () { const parseWebSocket = { send: jasmine.createSpy('send'), }; @@ -197,7 +190,7 @@ describe('Client', function() { expect(messageJSON.requestId).toBe(2); }); - it('can push create response', function() { + it('can push create response', function () { const parseObjectJSON = { key: 'value', className: 'test', @@ -221,7 +214,7 @@ describe('Client', function() { expect(messageJSON.object).toEqual(parseObjectJSON); }); - it('can push enter response', function() { + it('can push enter response', function () { const parseObjectJSON = { key: 'value', className: 'test', @@ -245,7 +238,7 @@ describe('Client', function() { expect(messageJSON.object).toEqual(parseObjectJSON); }); - it('can push update response', function() { + it('can push update response', function () { const parseObjectJSON = { key: 'value', className: 'test', @@ -269,7 +262,7 @@ describe('Client', function() { expect(messageJSON.object).toEqual(parseObjectJSON); }); - it('can push leave response', function() { + it('can push leave response', function () { const parseObjectJSON = { key: 'value', className: 'test', diff --git a/spec/CloudCode.Validator.spec.js b/spec/CloudCode.Validator.spec.js index b21c71e1..ef10b419 100644 --- a/spec/CloudCode.Validator.spec.js +++ b/spec/CloudCode.Validator.spec.js @@ -149,9 +149,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please login to continue.' - ); + expect(error.message).toEqual('Validation failed. Please login to continue.'); done(); }); }); @@ -195,9 +193,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please specify data for a.' - ); + expect(error.message).toEqual('Validation failed. Please specify data for a.'); done(); }); }); @@ -218,9 +214,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please specify data for a.' - ); + expect(error.message).toEqual('Validation failed. Please specify data for a.'); done(); }); }); @@ -265,9 +259,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Invalid type for data. Expected: array' - ); + expect(error.message).toEqual('Validation failed. Invalid type for data. Expected: array'); done(); }); }); @@ -292,9 +284,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Invalid type for data. Expected: string' - ); + expect(error.message).toEqual('Validation failed. Invalid type for data. Expected: string'); done(); }); }); @@ -346,9 +336,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please specify data for data.' - ); + expect(error.message).toEqual('Validation failed. Please specify data for data.'); done(); }); }); @@ -376,9 +364,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Invalid option for data. Expected: a' - ); + expect(error.message).toEqual('Validation failed. Invalid option for data. Expected: a'); done(); }); }); @@ -406,9 +392,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Invalid option for data. Expected: a, b' - ); + expect(error.message).toEqual('Validation failed. Invalid option for data. Expected: a, b'); done(); }); }); @@ -439,9 +423,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Expected data to be between 1 and 5.' - ); + expect(error.message).toEqual('Validation failed. Expected data to be between 1 and 5.'); done(); }); }); @@ -470,9 +452,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. String should be at least 5 characters' - ); + expect(error.message).toEqual('Validation failed. String should be at least 5 characters'); done(); }); }); @@ -528,9 +508,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Invalid value for data.' - ); + expect(error.message).toEqual('Validation failed. Invalid value for data.'); done(); }); }); @@ -602,9 +580,7 @@ describe('cloud validator', () => { fail('should not have been able to save without userkey'); } catch (error) { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please set data for name on your account.' - ); + expect(error.message).toEqual('Validation failed. Please set data for name on your account.'); done(); } }); @@ -754,9 +730,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please login to continue.' - ); + expect(error.message).toEqual('Validation failed. Please login to continue.'); done(); }); }); @@ -808,9 +782,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please login to continue.' - ); + expect(error.message).toEqual('Validation failed. Please login to continue.'); done(); }); }); @@ -835,9 +807,7 @@ describe('cloud validator', () => { }) .catch(error => { expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); - expect(error.message).toEqual( - 'Validation failed. Please specify data for bar.' - ); + expect(error.message).toEqual('Validation failed. Please specify data for bar.'); done(); }); }); diff --git a/spec/CloudCode.spec.js b/spec/CloudCode.spec.js index a5a89f33..139c919a 100644 --- a/spec/CloudCode.spec.js +++ b/spec/CloudCode.spec.js @@ -24,25 +24,19 @@ describe('Cloud Code', () => { cloud: __dirname + '/cloud/cloudCodeRelativeFile.js', }).then(() => { Parse.Cloud.run('cloudCodeInFile', {}).then(result => { - expect(result).toEqual( - 'It is possible to define cloud code in a file.' - ); + 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', {}).then(result => { - expect(result).toEqual( - 'It is possible to define cloud code in a file.' - ); - done(); - }); - } - ); + reconfigureServer({ cloud: './spec/cloud/cloudCodeAbsoluteFile.js' }).then(() => { + Parse.Cloud.run('cloudCodeInFile', {}).then(result => { + expect(result).toEqual('It is possible to define cloud code in a file.'); + done(); + }); + }); }); it('can create functions', done => { @@ -137,9 +131,7 @@ describe('Cloud Code', () => { obj.set('foo', 'bar'); obj.save().then( function () { - fail( - 'Should not have been able to save BeforeSaveFailWithErrorCode class.' - ); + fail('Should not have been able to save BeforeSaveFailWithErrorCode class.'); done(); }, function (error) { @@ -851,18 +843,10 @@ describe('Cloud Code', () => { expect(req.params.dateList[0].getTime()).toBe(1463907600000); expect(req.params.complexStructure.date[0] instanceof Date).toBe(true); expect(req.params.complexStructure.date[0].getTime()).toBe(1463907600000); - expect(req.params.complexStructure.deepDate.date[0] instanceof Date).toBe( - true - ); - expect(req.params.complexStructure.deepDate.date[0].getTime()).toBe( - 1463907600000 - ); - expect( - req.params.complexStructure.deepDate2[0].date instanceof Date - ).toBe(true); - expect(req.params.complexStructure.deepDate2[0].date.getTime()).toBe( - 1463907600000 - ); + expect(req.params.complexStructure.deepDate.date[0] instanceof Date).toBe(true); + expect(req.params.complexStructure.deepDate.date[0].getTime()).toBe(1463907600000); + expect(req.params.complexStructure.deepDate2[0].date instanceof Date).toBe(true); + expect(req.params.complexStructure.deepDate2[0].date.getTime()).toBe(1463907600000); // Regression for #2294 expect(req.params.file instanceof Parse.File).toBe(true); expect(req.params.file.url()).toEqual('https://some.url'); @@ -1291,9 +1275,7 @@ describe('Cloud Code', () => { }); const TestObject = Parse.Object.extend('TestObject'); - const BeforeSaveUnchangedObject = Parse.Object.extend( - 'BeforeSaveUnchanged' - ); + const BeforeSaveUnchangedObject = Parse.Object.extend('BeforeSaveUnchanged'); const BeforeSaveChangedObject = Parse.Object.extend('BeforeSaveChanged'); const aTestObject = new TestObject(); @@ -1303,27 +1285,19 @@ describe('Cloud Code', () => { .then(aTestObject => { const aBeforeSaveUnchangedObject = new BeforeSaveUnchangedObject(); aBeforeSaveUnchangedObject.set('aTestObject', aTestObject); - expect( - aBeforeSaveUnchangedObject.get('aTestObject').get('foo') - ).toEqual('bar'); + expect(aBeforeSaveUnchangedObject.get('aTestObject').get('foo')).toEqual('bar'); return aBeforeSaveUnchangedObject.save(); }) .then(aBeforeSaveUnchangedObject => { - expect( - aBeforeSaveUnchangedObject.get('aTestObject').get('foo') - ).toEqual('bar'); + expect(aBeforeSaveUnchangedObject.get('aTestObject').get('foo')).toEqual('bar'); const aBeforeSaveChangedObject = new BeforeSaveChangedObject(); aBeforeSaveChangedObject.set('aTestObject', aTestObject); - expect(aBeforeSaveChangedObject.get('aTestObject').get('foo')).toEqual( - 'bar' - ); + expect(aBeforeSaveChangedObject.get('aTestObject').get('foo')).toEqual('bar'); return aBeforeSaveChangedObject.save(); }) .then(aBeforeSaveChangedObject => { - expect(aBeforeSaveChangedObject.get('aTestObject').get('foo')).toEqual( - 'bar' - ); + expect(aBeforeSaveChangedObject.get('aTestObject').get('foo')).toEqual('bar'); expect(aBeforeSaveChangedObject.get('foo')).toEqual('baz'); done(); }); @@ -1479,13 +1453,13 @@ describe('Cloud Code', () => { obj.set('points', 10); obj.set('num', 10); obj.save(null, { useMasterKey: true }).then(function () { - Parse.Cloud.run('cloudIncrementClassFunction', { objectId: obj.id }).then( - function (savedObj) { - expect(savedObj.get('num')).toEqual(1); - expect(savedObj.get('points')).toEqual(0); - done(); - } - ); + Parse.Cloud.run('cloudIncrementClassFunction', { objectId: obj.id }).then(function ( + savedObj + ) { + expect(savedObj.get('num')).toEqual(1); + expect(savedObj.get('points')).toEqual(0); + done(); + }); }); }); @@ -2241,9 +2215,7 @@ describe('afterFind hooks', () => { return req.query; }); - const obj0 = new Parse.Object('MyObject') - .set('white', true) - .set('black', true); + const obj0 = new Parse.Object('MyObject').set('white', true).set('black', true); obj0.save().then(() => { new Parse.Query('MyObject').first().then(result => { expect(result.get('white')).toBe(true); @@ -2254,9 +2226,7 @@ describe('afterFind hooks', () => { }); it('should not alter select', done => { - const obj0 = new Parse.Object('MyObject') - .set('white', true) - .set('black', true); + const obj0 = new Parse.Object('MyObject').set('white', true).set('black', true); obj0.save().then(() => { new Parse.Query('MyObject').first().then(result => { expect(result.get('white')).toBe(true); @@ -2336,14 +2306,10 @@ describe('afterFind hooks', () => { it('should validate triggers correctly', () => { expect(() => { Parse.Cloud.beforeSave('_Session', () => {}); - }).toThrow( - 'Only the afterLogout trigger is allowed for the _Session class.' - ); + }).toThrow('Only the afterLogout trigger is allowed for the _Session class.'); expect(() => { Parse.Cloud.afterSave('_Session', () => {}); - }).toThrow( - 'Only the afterLogout trigger is allowed for the _Session class.' - ); + }).toThrow('Only the afterLogout trigger is allowed for the _Session class.'); expect(() => { Parse.Cloud.beforeSave('_PushStatus', () => {}); }).toThrow('Only afterSave is allowed on _PushStatus'); @@ -2352,44 +2318,28 @@ describe('afterFind hooks', () => { }).not.toThrow(); expect(() => { Parse.Cloud.beforeLogin(() => {}); - }).not.toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).not.toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.beforeLogin('_User', () => {}); - }).not.toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).not.toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.beforeLogin(Parse.User, () => {}); - }).not.toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).not.toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.beforeLogin('SomeClass', () => {}); - }).toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.afterLogin(() => {}); - }).not.toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).not.toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.afterLogin('_User', () => {}); - }).not.toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).not.toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.afterLogin(Parse.User, () => {}); - }).not.toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).not.toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.afterLogin('SomeClass', () => {}); - }).toThrow( - 'Only the _User class is allowed for the beforeLogin and afterLogin triggers' - ); + }).toThrow('Only the _User class is allowed for the beforeLogin and afterLogin triggers'); expect(() => { Parse.Cloud.afterLogout(() => {}); }).not.toThrow(); @@ -2398,14 +2348,10 @@ describe('afterFind hooks', () => { }).not.toThrow(); expect(() => { Parse.Cloud.afterLogout('_User', () => {}); - }).toThrow( - 'Only the _Session class is allowed for the afterLogout trigger.' - ); + }).toThrow('Only the _Session class is allowed for the afterLogout trigger.'); expect(() => { Parse.Cloud.afterLogout('SomeClass', () => {}); - }).toThrow( - 'Only the _Session class is allowed for the afterLogout trigger.' - ); + }).toThrow('Only the _Session class is allowed for the afterLogout trigger.'); }); it('should skip afterFind hooks for aggregate', done => { @@ -2723,17 +2669,14 @@ describe('beforeLogin hook', () => { const createFileSpy = spyOn(mockAdapter, 'createFile').and.callThrough(); Parse.Cloud.beforeSaveFile(() => { const newFile = new Parse.File('some-file.txt'); - newFile._url = - 'http://www.somewhere.com/parse/files/some-app-id/some-file.txt'; + newFile._url = 'http://www.somewhere.com/parse/files/some-app-id/some-file.txt'; return newFile; }); const file = new Parse.File('popeye.txt', [1, 2, 3], 'text/plain'); const result = await file.save({ useMasterKey: true }); expect(result).toBe(file); expect(result._name).toBe('some-file.txt'); - expect(result._url).toBe( - 'http://www.somewhere.com/parse/files/some-app-id/some-file.txt' - ); + expect(result._url).toBe('http://www.somewhere.com/parse/files/some-app-id/some-file.txt'); expect(createFileSpy).not.toHaveBeenCalled(); }); @@ -2785,11 +2728,7 @@ describe('beforeLogin hook', () => { Parse.Cloud.beforeSaveFile(async req => { expect(req.triggerName).toEqual('beforeSaveFile'); expect(req.fileSize).toBe(3); - const newFile = new Parse.File( - 'donald_duck.pdf', - [4, 5, 6], - 'application/pdf' - ); + const newFile = new Parse.File('donald_duck.pdf', [4, 5, 6], 'application/pdf'); newFile.setMetadata({ foo: 'bar' }); newFile.setTags({ tagA: 'some-tag' }); return newFile; @@ -2814,9 +2753,7 @@ describe('beforeLogin hook', () => { newOptions ); const expectedFileName = 'donald_duck.pdf'; - expect(file._name.indexOf(expectedFileName)).toBe( - file._name.length - expectedFileName.length - ); + expect(file._name.indexOf(expectedFileName)).toBe(file._name.length - expectedFileName.length); }); it('beforeSaveFile should contain metadata and tags saved from client', async () => { @@ -2868,8 +2805,7 @@ describe('beforeLogin hook', () => { Parse.Cloud.beforeSaveFile(req => { expect(req.fileSize).toBe(3); const newFile = new Parse.File('some-file.txt'); - newFile._url = - 'http://www.somewhere.com/parse/files/some-app-id/some-file.txt'; + newFile._url = 'http://www.somewhere.com/parse/files/some-app-id/some-file.txt'; return newFile; }); Parse.Cloud.afterSaveFile(req => { @@ -2879,9 +2815,7 @@ describe('beforeLogin hook', () => { const result = await file.save({ useMasterKey: true }); expect(result).toBe(result); expect(result._name).toBe('some-file.txt'); - expect(result._url).toBe( - 'http://www.somewhere.com/parse/files/some-app-id/some-file.txt' - ); + expect(result._url).toBe('http://www.somewhere.com/parse/files/some-app-id/some-file.txt'); expect(createFileSpy).not.toHaveBeenCalled(); }); @@ -2920,11 +2854,7 @@ describe('beforeLogin hook', () => { Parse.Cloud.beforeSaveFile(async req => { expect(req.fileSize).toBe(3); expect(req.master).toBe(true); - const newFile = new Parse.File( - 'donald_duck.pdf', - [4, 5, 6, 7, 8, 9], - 'application/pdf' - ); + const newFile = new Parse.File('donald_duck.pdf', [4, 5, 6, 7, 8, 9], 'application/pdf'); return newFile; }); Parse.Cloud.afterSaveFile(async req => { diff --git a/spec/CloudCodeLogger.spec.js b/spec/CloudCodeLogger.spec.js index 85de9476..78888193 100644 --- a/spec/CloudCodeLogger.spec.js +++ b/spec/CloudCodeLogger.spec.js @@ -1,5 +1,4 @@ -const LoggerController = require('../lib/Controllers/LoggerController') - .LoggerController; +const LoggerController = require('../lib/Controllers/LoggerController').LoggerController; const WinstonLoggerAdapter = require('../lib/Adapters/Logger/WinstonLoggerAdapter') .WinstonLoggerAdapter; const fs = require('fs'); @@ -23,10 +22,7 @@ describe('Cloud Code Logger', () => { .then(() => Parse.User.logIn(user.get('username'), 'abc')); }) .then(() => { - spy = spyOn( - Config.get('test').loggerController.adapter, - 'log' - ).and.callThrough(); + spy = spyOn(Config.get('test').loggerController.adapter, 'log').and.callThrough(); }); }); @@ -34,10 +30,7 @@ describe('Cloud Code Logger', () => { // see helpers.js:afterEach it('should expose log to functions', () => { - const spy = spyOn( - Config.get('test').loggerController, - 'log' - ).and.callThrough(); + const spy = spyOn(Config.get('test').loggerController, 'log').and.callThrough(); Parse.Cloud.define('loggerTest', req => { req.log.info('logTest', 'info log', { info: 'some log' }); req.log.error('logTest', 'error log', { error: 'there was an error' }); @@ -54,9 +47,7 @@ describe('Cloud Code Logger', () => { expect(cloudFunctionMessage.args[1][0]).toMatch( /Ran cloud function loggerTest for user [^ ]* with:\n {2}Input: {}\n {2}Result: {}/ ); - expect(cloudFunctionMessage.args[1][1].functionName).toEqual( - 'loggerTest' - ); + expect(cloudFunctionMessage.args[1][1].functionName).toEqual('loggerTest'); expect(errorMessage.args[0]).toBe('error'); expect(errorMessage.args[1][2].error).toBe('there was an error'); expect(errorMessage.args[1][0]).toBe('logTest'); @@ -106,14 +97,10 @@ describe('Cloud Code Logger', () => { expect(cloudTriggerMessage[2].user).toBe(user.id); expect(errorMessage[0]).toBe('error'); expect(errorMessage[3].error).toBe('there was an error'); - expect(errorMessage[1] + ' ' + errorMessage[2]).toBe( - 'beforeSave MyObject error log' - ); + expect(errorMessage[1] + ' ' + errorMessage[2]).toBe('beforeSave MyObject error log'); expect(infoMessage[0]).toBe('info'); expect(infoMessage[3].info).toBe('some log'); - expect(infoMessage[1] + ' ' + infoMessage[2]).toBe( - 'beforeSave MyObject info log' - ); + expect(infoMessage[1] + ' ' + infoMessage[2]).toBe('beforeSave MyObject info log'); done(); }); }); diff --git a/spec/DatabaseController.spec.js b/spec/DatabaseController.spec.js index 77cd6d03..988248c8 100644 --- a/spec/DatabaseController.spec.js +++ b/spec/DatabaseController.spec.js @@ -76,9 +76,7 @@ describe('DatabaseController', function () { schemaController.testPermissionsForClassName .withArgs(CLASS_NAME, ACL_GROUP, OPERATION) .and.returnValue(true); - schemaController.getClassLevelPermissions - .withArgs(CLASS_NAME) - .and.returnValue(clp); + schemaController.getClassLevelPermissions.withArgs(CLASS_NAME).and.returnValue(clp); const output = databaseController.addPointerPermissions( schemaController, @@ -100,9 +98,7 @@ describe('DatabaseController', function () { schemaController.testPermissionsForClassName .withArgs(CLASS_NAME, ACL_GROUP, OPERATION) .and.returnValue(false); - schemaController.getClassLevelPermissions - .withArgs(CLASS_NAME) - .and.returnValue(clp); + schemaController.getClassLevelPermissions.withArgs(CLASS_NAME).and.returnValue(clp); schemaController.getExpectedType .withArgs(CLASS_NAME, 'user') .and.returnValue({ type: 'Pointer' }); @@ -127,9 +123,7 @@ describe('DatabaseController', function () { schemaController.testPermissionsForClassName .withArgs(CLASS_NAME, ACL_GROUP, OPERATION) .and.returnValue(false); - schemaController.getClassLevelPermissions - .withArgs(CLASS_NAME) - .and.returnValue(clp); + schemaController.getClassLevelPermissions.withArgs(CLASS_NAME).and.returnValue(clp); schemaController.getExpectedType .withArgs(CLASS_NAME, 'users') .and.returnValue({ type: 'Array' }); @@ -157,9 +151,7 @@ describe('DatabaseController', function () { schemaController.testPermissionsForClassName .withArgs(CLASS_NAME, ACL_GROUP, OPERATION) .and.returnValue(false); - schemaController.getClassLevelPermissions - .withArgs(CLASS_NAME) - .and.returnValue(clp); + schemaController.getClassLevelPermissions.withArgs(CLASS_NAME).and.returnValue(clp); schemaController.getExpectedType .withArgs(CLASS_NAME, 'user') .and.returnValue({ type: 'Object' }); @@ -187,9 +179,7 @@ describe('DatabaseController', function () { schemaController.testPermissionsForClassName .withArgs(CLASS_NAME, ACL_GROUP, OPERATION) .and.returnValue(false); - schemaController.getClassLevelPermissions - .withArgs(CLASS_NAME) - .and.returnValue(clp); + schemaController.getClassLevelPermissions.withArgs(CLASS_NAME).and.returnValue(clp); schemaController.getExpectedType .withArgs(CLASS_NAME, 'user') .and.returnValue({ type: 'Pointer' }); @@ -216,9 +206,7 @@ describe('DatabaseController', function () { schemaController.testPermissionsForClassName .withArgs(CLASS_NAME, ACL_GROUP, OPERATION) .and.returnValue(false); - schemaController.getClassLevelPermissions - .withArgs(CLASS_NAME) - .and.returnValue(clp); + schemaController.getClassLevelPermissions.withArgs(CLASS_NAME).and.returnValue(clp); schemaController.getExpectedType .withArgs(CLASS_NAME, 'user') .and.returnValue({ type: 'Pointer' }); @@ -255,9 +243,7 @@ describe('DatabaseController', function () { schemaController.testPermissionsForClassName .withArgs(CLASS_NAME, ACL_GROUP, OPERATION) .and.returnValue(false); - schemaController.getClassLevelPermissions - .withArgs(CLASS_NAME) - .and.returnValue(clp); + schemaController.getClassLevelPermissions.withArgs(CLASS_NAME).and.returnValue(clp); schemaController.getExpectedType .withArgs(CLASS_NAME, 'user') .and.returnValue({ type: 'Number' }); @@ -282,15 +268,7 @@ describe('DatabaseController', function () { }); function buildCLP(pointerNames) { - const OPERATIONS = [ - 'count', - 'find', - 'get', - 'create', - 'update', - 'delete', - 'addField', - ]; + const OPERATIONS = ['count', 'find', 'get', 'create', 'update', 'delete', 'addField']; const clp = OPERATIONS.reduce((acc, op) => { acc[op] = {}; diff --git a/spec/EmailVerificationToken.spec.js b/spec/EmailVerificationToken.spec.js index ccbb09d2..b109f7f2 100644 --- a/spec/EmailVerificationToken.spec.js +++ b/spec/EmailVerificationToken.spec.js @@ -324,9 +324,7 @@ describe('Email Verification Token Expiration: ', () => { expect(typeof user).toBe('object'); expect(user.emailVerified).toEqual(true); expect(typeof user._email_verify_token).toBe('undefined'); - expect(typeof user._email_verify_token_expires_at).toBe( - 'undefined' - ); + expect(typeof user._email_verify_token_expires_at).toBe('undefined'); done(); }) .catch(error => { @@ -791,9 +789,7 @@ describe('Email Verification Token Expiration: ', () => { .then(response => { expect(response.status).toBe(400); expect(response.data.code).toBe(Parse.Error.INVALID_EMAIL_ADDRESS); - expect(response.data.error).toBe( - 'you must provide a valid email string' - ); + expect(response.data.error).toBe('you must provide a valid email string'); expect(sendVerificationEmailCallCount).toBe(0); expect(sendEmailOptions).not.toBeDefined(); done(); @@ -833,9 +829,7 @@ describe('Email Verification Token Expiration: ', () => { .fetch() .then(() => { expect(user.get('emailVerified')).toEqual(false); - expect(typeof user.get('_email_verify_token_expires_at')).toBe( - 'undefined' - ); + expect(typeof user.get('_email_verify_token_expires_at')).toBe('undefined'); expect(sendEmailOptions).toBeDefined(); done(); }) diff --git a/spec/EnableExpressErrorHandler.spec.js b/spec/EnableExpressErrorHandler.spec.js index 52cb985c..fa73d21f 100644 --- a/spec/EnableExpressErrorHandler.spec.js +++ b/spec/EnableExpressErrorHandler.spec.js @@ -1,7 +1,7 @@ const request = require('../lib/request'); describe('Enable express error handler', () => { - it('should call the default handler in case of error, like updating a non existing object', async (done) => { + it('should call the default handler in case of error, like updating a non existing object', async done => { const parseServer = await reconfigureServer( Object.assign({}, defaultConfiguration, { enableExpressErrorHandler: true, diff --git a/spec/EnableSingleSchemaCache.spec.js b/spec/EnableSingleSchemaCache.spec.js index 6e8e5a23..45873c52 100644 --- a/spec/EnableSingleSchemaCache.spec.js +++ b/spec/EnableSingleSchemaCache.spec.js @@ -53,6 +53,6 @@ describe('Enable single schema cache', () => { }); }); -const fakeRequestForConfig = function() { +const fakeRequestForConfig = function () { return Config.get('test'); }; diff --git a/spec/EventEmitterPubSub.spec.js b/spec/EventEmitterPubSub.spec.js index 9117662b..00358646 100644 --- a/spec/EventEmitterPubSub.spec.js +++ b/spec/EventEmitterPubSub.spec.js @@ -1,14 +1,13 @@ -const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub') - .EventEmitterPubSub; +const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub').EventEmitterPubSub; -describe('EventEmitterPubSub', function() { - it('can publish and subscribe', function() { +describe('EventEmitterPubSub', function () { + it('can publish and subscribe', function () { const publisher = EventEmitterPubSub.createPublisher(); const subscriber = EventEmitterPubSub.createSubscriber(); subscriber.subscribe('testChannel'); // Register mock checked for subscriber let isChecked = false; - subscriber.on('message', function(channel, message) { + subscriber.on('message', function (channel, message) { isChecked = true; expect(channel).toBe('testChannel'); expect(message).toBe('testMessage'); @@ -19,14 +18,14 @@ describe('EventEmitterPubSub', function() { expect(isChecked).toBe(true); }); - it('can unsubscribe', function() { + it('can unsubscribe', function () { const publisher = EventEmitterPubSub.createPublisher(); const subscriber = EventEmitterPubSub.createSubscriber(); subscriber.subscribe('testChannel'); subscriber.unsubscribe('testChannel'); // Register mock checked for subscriber let isCalled = false; - subscriber.on('message', function() { + subscriber.on('message', function () { isCalled = true; }); @@ -35,7 +34,7 @@ describe('EventEmitterPubSub', function() { expect(isCalled).toBe(false); }); - it('can unsubscribe not subscribing channel', function() { + it('can unsubscribe not subscribing channel', function () { const subscriber = EventEmitterPubSub.createSubscriber(); // Make sure subscriber does not throw exception diff --git a/spec/FilesController.spec.js b/spec/FilesController.spec.js index a6dc604c..5b6a3d4a 100644 --- a/spec/FilesController.spec.js +++ b/spec/FilesController.spec.js @@ -1,11 +1,9 @@ -const LoggerController = require('../lib/Controllers/LoggerController') - .LoggerController; +const LoggerController = require('../lib/Controllers/LoggerController').LoggerController; const WinstonLoggerAdapter = require('../lib/Adapters/Logger/WinstonLoggerAdapter') .WinstonLoggerAdapter; const GridFSBucketAdapter = require('../lib/Adapters/Files/GridFSBucketAdapter') .GridFSBucketAdapter; -const GridStoreAdapter = require('../lib/Adapters/Files/GridStoreAdapter') - .GridStoreAdapter; +const GridStoreAdapter = require('../lib/Adapters/Files/GridStoreAdapter').GridStoreAdapter; const Config = require('../lib/Config'); const FilesController = require('../lib/Controllers/FilesController').default; const databaseURI = 'mongodb://localhost:27017/parse'; @@ -26,9 +24,7 @@ const mockAdapter = { describe('FilesController', () => { it('should properly expand objects', done => { const config = Config.get(Parse.applicationId); - const gridStoreAdapter = new GridFSBucketAdapter( - 'mongodb://localhost:27017/parse' - ); + const gridStoreAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse'); const filesController = new FilesController(gridStoreAdapter); const result = filesController.expandFilesInObject(config, function () {}); @@ -58,16 +54,12 @@ describe('FilesController', () => { () => setImmediate(() => Promise.resolve('done')) ) .then(() => new Promise(resolve => setTimeout(resolve, 200))) - .then(() => - logController.getLogs({ from: Date.now() - 1000, size: 1000 }) - ) + .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. - const log1 = logs.find( - x => x.message === 'Error creating a file: it failed with xyz' - ); + const log1 = logs.find(x => x.message === 'Error creating a file: it failed with xyz'); expect(log1.level).toBe('error'); const log2 = logs.find(x => x.message === 'it failed with xyz'); @@ -93,9 +85,7 @@ describe('FilesController', () => { it('should add a unique hash to the file name when the preserveFileName option is false', done => { const config = Config.get(Parse.applicationId); - const gridStoreAdapter = new GridFSBucketAdapter( - 'mongodb://localhost:27017/parse' - ); + const gridStoreAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse'); spyOn(gridStoreAdapter, 'createFile'); gridStoreAdapter.createFile.and.returnValue(Promise.resolve()); const fileName = 'randomFileName.pdf'; @@ -116,9 +106,7 @@ describe('FilesController', () => { it('should not add a unique hash to the file name when the preserveFileName option is true', done => { const config = Config.get(Parse.applicationId); - const gridStoreAdapter = new GridFSBucketAdapter( - 'mongodb://localhost:27017/parse' - ); + const gridStoreAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse'); spyOn(gridStoreAdapter, 'createFile'); gridStoreAdapter.createFile.and.returnValue(Promise.resolve()); const fileName = 'randomFileName.pdf'; @@ -129,9 +117,7 @@ describe('FilesController', () => { filesController.createFile(config, fileName); expect(gridStoreAdapter.createFile).toHaveBeenCalledTimes(1); - expect(gridStoreAdapter.createFile.calls.mostRecent().args[0]).toEqual( - fileName - ); + expect(gridStoreAdapter.createFile.calls.mostRecent().args[0]).toEqual(fileName); done(); }); @@ -146,18 +132,14 @@ describe('FilesController', () => { }); it('should reject slashes in file names', done => { - const gridStoreAdapter = new GridFSBucketAdapter( - 'mongodb://localhost:27017/parse' - ); + const gridStoreAdapter = new GridFSBucketAdapter('mongodb://localhost:27017/parse'); const fileName = 'foo/randomFileName.pdf'; expect(gridStoreAdapter.validateFilename(fileName)).not.toBe(null); done(); }); it('should also reject slashes in file names', done => { - const gridStoreAdapter = new GridStoreAdapter( - 'mongodb://localhost:27017/parse' - ); + const gridStoreAdapter = new GridStoreAdapter('mongodb://localhost:27017/parse'); const fileName = 'foo/randomFileName.pdf'; expect(gridStoreAdapter.validateFilename(fileName)).not.toBe(null); done(); diff --git a/spec/GridFSBucketStorageAdapter.spec.js b/spec/GridFSBucketStorageAdapter.spec.js index 1e55d687..10bb7569 100644 --- a/spec/GridFSBucketStorageAdapter.spec.js +++ b/spec/GridFSBucketStorageAdapter.spec.js @@ -1,5 +1,4 @@ -const GridStoreAdapter = require('../lib/Adapters/Files/GridStoreAdapter') - .GridStoreAdapter; +const GridStoreAdapter = require('../lib/Adapters/Files/GridStoreAdapter').GridStoreAdapter; const GridFSBucketAdapter = require('../lib/Adapters/Files/GridFSBucketAdapter') .GridFSBucketAdapter; const { randomString } = require('../lib/cryptoUtils'); diff --git a/spec/GridStoreAdapter.spec.js b/spec/GridStoreAdapter.spec.js index ba6288b1..145b8e0e 100644 --- a/spec/GridStoreAdapter.spec.js +++ b/spec/GridStoreAdapter.spec.js @@ -1,8 +1,7 @@ const MongoClient = require('mongodb').MongoClient; const GridStore = require('mongodb').GridStore; -const GridStoreAdapter = require('../lib/Adapters/Files/GridStoreAdapter') - .GridStoreAdapter; +const GridStoreAdapter = require('../lib/Adapters/Files/GridStoreAdapter').GridStoreAdapter; const Config = require('../lib/Config'); const FilesController = require('../lib/Controllers/FilesController').default; @@ -14,11 +13,7 @@ describe_only_db('mongo')('GridStoreAdapter', () => { const gridStoreAdapter = new GridStoreAdapter(databaseURI); const db = await gridStoreAdapter._connect(); await db.dropDatabase(); - const filesController = new FilesController( - gridStoreAdapter, - Parse.applicationId, - {} - ); + const filesController = new FilesController(gridStoreAdapter, Parse.applicationId, {}); // save original unlink before redefinition const originalUnlink = GridStore.prototype.unlink; @@ -26,7 +21,7 @@ describe_only_db('mongo')('GridStoreAdapter', () => { let gridStoreMode; // new unlink method that will capture the mode in which GridStore was opened - GridStore.prototype.unlink = function() { + GridStore.prototype.unlink = function () { // restore original unlink during first call GridStore.prototype.unlink = originalUnlink; diff --git a/spec/HTTPRequest.spec.js b/spec/HTTPRequest.spec.js index 2e1921b3..aa141706 100644 --- a/spec/HTTPRequest.spec.js +++ b/spec/HTTPRequest.spec.js @@ -11,26 +11,26 @@ const httpRequestServer = 'http://localhost:' + port; function startServer(done) { const app = express(); app.use(bodyParser.json({ type: '*/*' })); - app.get('/hello', function(req, res) { + app.get('/hello', function (req, res) { res.json({ response: 'OK' }); }); - app.get('/404', function(req, res) { + app.get('/404', function (req, res) { res.status(404); res.send('NO'); }); - app.get('/301', function(req, res) { + app.get('/301', function (req, res) { res.status(301); res.location('/hello'); res.send(); }); - app.post('/echo', function(req, res) { + app.post('/echo', function (req, res) { res.json(req.body); }); - app.get('/qs', function(req, res) { + app.get('/qs', function (req, res) { res.json(req.query); }); @@ -50,7 +50,7 @@ describe('httpRequest', () => { it('should do /hello', done => { httpRequest({ url: httpRequestServer + '/hello', - }).then(function(httpResponse) { + }).then(function (httpResponse) { expect(httpResponse.status).toBe(200); expect(httpResponse.buffer).toEqual(new Buffer('{"response":"OK"}')); expect(httpResponse.text).toEqual('{"response":"OK"}'); @@ -62,7 +62,7 @@ describe('httpRequest', () => { it('should do not follow redirects by default', done => { httpRequest({ url: httpRequestServer + '/301', - }).then(function(httpResponse) { + }).then(function (httpResponse) { expect(httpResponse.status).toBe(301); done(); }, done.fail); @@ -72,7 +72,7 @@ describe('httpRequest', () => { httpRequest({ url: httpRequestServer + '/301', followRedirects: true, - }).then(function(httpResponse) { + }).then(function (httpResponse) { expect(httpResponse.status).toBe(200); expect(httpResponse.buffer).toEqual(new Buffer('{"response":"OK"}')); expect(httpResponse.text).toEqual('{"response":"OK"}'); @@ -86,12 +86,12 @@ describe('httpRequest', () => { httpRequest({ url: httpRequestServer + '/404', }).then( - function() { + function () { calls++; fail('should not succeed'); done(); }, - function(httpResponse) { + function (httpResponse) { calls++; expect(calls).toBe(1); expect(httpResponse.status).toBe(404); @@ -114,12 +114,12 @@ describe('httpRequest', () => { 'Content-Type': 'application/json', }, }).then( - function(httpResponse) { + function (httpResponse) { expect(httpResponse.status).toBe(200); expect(httpResponse.data).toEqual({ foo: 'bar' }); done(); }, - function() { + function () { fail('should not fail'); done(); } @@ -132,9 +132,7 @@ describe('httpRequest', () => { }; const result = httpRequest.encodeBody(options); 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(); }); @@ -169,7 +167,7 @@ describe('httpRequest', () => { it('should fail gracefully', done => { httpRequest({ url: 'http://not a good url', - }).then(done.fail, function(error) { + }).then(done.fail, function (error) { expect(error).not.toBeUndefined(); expect(error).not.toBeNull(); done(); @@ -183,12 +181,12 @@ describe('httpRequest', () => { foo: 'bar', }, }).then( - function(httpResponse) { + function (httpResponse) { expect(httpResponse.status).toBe(200); expect(httpResponse.data).toEqual({ foo: 'bar' }); done(); }, - function() { + function () { fail('should not fail'); done(); } @@ -200,12 +198,12 @@ describe('httpRequest', () => { url: httpRequestServer + '/qs', params: 'foo=bar&foo2=bar2', }).then( - function(httpResponse) { + function (httpResponse) { expect(httpResponse.status).toBe(200); expect(httpResponse.data).toEqual({ foo: 'bar', foo2: 'bar2' }); done(); }, - function() { + function () { fail('should not fail'); done(); } diff --git a/spec/Idempotency.spec.js b/spec/Idempotency.spec.js index a8f78e67..c2ef8665 100644 --- a/spec/Idempotency.spec.js +++ b/spec/Idempotency.spec.js @@ -21,12 +21,7 @@ describe_only_db('mongo')('Idempotency', () => { { reqId: reqId }, { limit: 1 } ); - await rest.del( - config, - auth.master(config), - '_Idempotency', - res.results[0].objectId - ); + await rest.del(config, auth.master(config), '_Idempotency', res.results[0].objectId); } async function setup(options) { await reconfigureServer({ @@ -42,13 +37,7 @@ describe_only_db('mongo')('Idempotency', () => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 200000; } await setup({ - paths: [ - 'functions/.*', - 'jobs/.*', - 'classes/.*', - 'users', - 'installations', - ], + paths: ['functions/.*', 'jobs/.*', 'classes/.*', 'users', 'installations'], ttl: 30, }); }); @@ -218,9 +207,7 @@ describe_only_db('mongo')('Idempotency', () => { }); it('should re-throw any other error unchanged when writing request entry fails for any other reason', async () => { - spyOn(rest, 'create').and.rejectWith( - new Parse.Error(0, 'some other error') - ); + spyOn(rest, 'create').and.rejectWith(new Parse.Error(0, 'some other error')); Parse.Cloud.define('myFunction', () => {}); const params = { method: 'POST', diff --git a/spec/InMemoryCache.spec.js b/spec/InMemoryCache.spec.js index d3aeeb03..4a474b7f 100644 --- a/spec/InMemoryCache.spec.js +++ b/spec/InMemoryCache.spec.js @@ -1,6 +1,6 @@ const InMemoryCache = require('../lib/Adapters/Cache/InMemoryCache').default; -describe('InMemoryCache', function() { +describe('InMemoryCache', function () { const BASE_TTL = { ttl: 100, }; @@ -13,7 +13,7 @@ describe('InMemoryCache', function() { const VALUE = 'world'; function wait(sleep) { - return new Promise(function(resolve) { + return new Promise(function (resolve) { setTimeout(resolve, sleep); }); } diff --git a/spec/InMemoryCacheAdapter.spec.js b/spec/InMemoryCacheAdapter.spec.js index e0352782..add976fb 100644 --- a/spec/InMemoryCacheAdapter.spec.js +++ b/spec/InMemoryCacheAdapter.spec.js @@ -1,12 +1,11 @@ -const InMemoryCacheAdapter = require('../lib/Adapters/Cache/InMemoryCacheAdapter') - .default; +const InMemoryCacheAdapter = require('../lib/Adapters/Cache/InMemoryCacheAdapter').default; -describe('InMemoryCacheAdapter', function() { +describe('InMemoryCacheAdapter', function () { const KEY = 'hello'; const VALUE = 'world'; function wait(sleep) { - return new Promise(function(resolve) { + return new Promise(function (resolve) { setTimeout(resolve, sleep); }); } @@ -17,12 +16,7 @@ describe('InMemoryCacheAdapter', function() { }); // Verify all methods return promises. - Promise.all([ - cache.put(KEY, VALUE), - cache.del(KEY), - cache.get(KEY), - cache.clear(), - ]).then(() => { + Promise.all([cache.put(KEY, VALUE), cache.del(KEY), cache.get(KEY), cache.clear()]).then(() => { done(); }); }); diff --git a/spec/InstallationsRouter.spec.js b/spec/InstallationsRouter.spec.js index 91935e64..8e5a80c1 100644 --- a/spec/InstallationsRouter.spec.js +++ b/spec/InstallationsRouter.spec.js @@ -1,8 +1,7 @@ const auth = require('../lib/Auth'); const Config = require('../lib/Config'); const rest = require('../lib/rest'); -const InstallationsRouter = require('../lib/Routers/InstallationsRouter') - .InstallationsRouter; +const InstallationsRouter = require('../lib/Routers/InstallationsRouter').InstallationsRouter; describe('InstallationsRouter', () => { it('uses find condition from request.body', done => { @@ -29,19 +28,9 @@ describe('InstallationsRouter', () => { const router = new InstallationsRouter(); rest - .create( - config, - auth.nobody(config), - '_Installation', - androidDeviceRequest - ) + .create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Installation', - iosDeviceRequest - ); + return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); }) .then(() => { return router.handleFind(request); @@ -81,19 +70,9 @@ describe('InstallationsRouter', () => { const router = new InstallationsRouter(); rest - .create( - config, - auth.nobody(config), - '_Installation', - androidDeviceRequest - ) + .create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Installation', - iosDeviceRequest - ); + return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); }) .then(() => { return router.handleFind(request); @@ -132,19 +111,9 @@ describe('InstallationsRouter', () => { Config.get('test'); const router = new InstallationsRouter(); rest - .create( - config, - auth.nobody(config), - '_Installation', - androidDeviceRequest - ) + .create(config, auth.nobody(config), '_Installation', androidDeviceRequest) .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Installation', - iosDeviceRequest - ); + return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); }) .then(() => { return router.handleFind(request); @@ -182,20 +151,8 @@ describe('InstallationsRouter', () => { const router = new InstallationsRouter(); rest - .create( - config, - auth.nobody(config), - '_Installation', - androidDeviceRequest - ) - .then(() => - rest.create( - config, - auth.nobody(config), - '_Installation', - iosDeviceRequest - ) - ) + .create(config, auth.nobody(config), '_Installation', androidDeviceRequest) + .then(() => rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest)) .then(() => router.handleFind(request)) .then(res => { const response = res.response; @@ -230,18 +187,8 @@ describe('InstallationsRouter', () => { }; const router = new InstallationsRouter(); - await rest.create( - config, - auth.nobody(config), - '_Installation', - androidDeviceRequest - ); - await rest.create( - config, - auth.nobody(config), - '_Installation', - iosDeviceRequest - ); + await rest.create(config, auth.nobody(config), '_Installation', androidDeviceRequest); + await rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); let res = await router.handleFind(request); let response = res.response; expect(response.results.length).toEqual(2); @@ -256,58 +203,45 @@ describe('InstallationsRouter', () => { expect(response.count).toEqual(2); }); - it_exclude_dbs(['postgres'])( - 'query installations with limit = 0 and count = 1', - done => { - const config = Config.get('test'); - const androidDeviceRequest = { - installationId: '12345678-abcd-abcd-abcd-123456789abc', - deviceType: 'android', - }; - const iosDeviceRequest = { - installationId: '12345678-abcd-abcd-abcd-123456789abd', - deviceType: 'ios', - }; - const request = { - config: config, - auth: auth.master(config), - body: {}, - query: { - limit: 0, - count: 1, - }, - info: {}, - }; + it_exclude_dbs(['postgres'])('query installations with limit = 0 and count = 1', done => { + const config = Config.get('test'); + const androidDeviceRequest = { + installationId: '12345678-abcd-abcd-abcd-123456789abc', + deviceType: 'android', + }; + const iosDeviceRequest = { + installationId: '12345678-abcd-abcd-abcd-123456789abd', + deviceType: 'ios', + }; + const request = { + config: config, + auth: auth.master(config), + body: {}, + query: { + limit: 0, + count: 1, + }, + info: {}, + }; - const router = new InstallationsRouter(); - rest - .create( - config, - auth.nobody(config), - '_Installation', - androidDeviceRequest - ) - .then(() => { - return rest.create( - config, - auth.nobody(config), - '_Installation', - iosDeviceRequest - ); - }) - .then(() => { - return router.handleFind(request); - }) - .then(res => { - const response = res.response; - expect(response.results.length).toEqual(0); - expect(response.count).toEqual(2); - done(); - }) - .catch(err => { - fail(JSON.stringify(err)); - done(); - }); - } - ); + const router = new InstallationsRouter(); + rest + .create(config, auth.nobody(config), '_Installation', androidDeviceRequest) + .then(() => { + return rest.create(config, auth.nobody(config), '_Installation', iosDeviceRequest); + }) + .then(() => { + return router.handleFind(request); + }) + .then(res => { + const response = res.response; + expect(response.results.length).toEqual(0); + expect(response.count).toEqual(2); + done(); + }) + .catch(err => { + fail(JSON.stringify(err)); + done(); + }); + }); }); diff --git a/spec/JobSchedule.spec.js b/spec/JobSchedule.spec.js index feb37ec6..853eb201 100644 --- a/spec/JobSchedule.spec.js +++ b/spec/JobSchedule.spec.js @@ -47,19 +47,13 @@ describe('JobSchedule', () => { it('should reject access when not using masterKey (/jobs)', done => { request( - Object.assign( - { url: Parse.serverURL + '/cloud_code/jobs' }, - defaultOptions - ) + Object.assign({ url: Parse.serverURL + '/cloud_code/jobs' }, defaultOptions) ).then(done.fail, () => done()); }); it('should reject access when not using masterKey (/jobs/data)', done => { request( - Object.assign( - { url: Parse.serverURL + '/cloud_code/jobs/data' }, - defaultOptions - ) + Object.assign({ url: Parse.serverURL + '/cloud_code/jobs/data' }, defaultOptions) ).then(done.fail, () => done()); }); @@ -82,12 +76,10 @@ describe('JobSchedule', () => { }); it('should allow access when using masterKey (GET /jobs)', done => { - request( - Object.assign( - { url: Parse.serverURL + '/cloud_code/jobs' }, - masterKeyOptions - ) - ).then(done, done.fail); + request(Object.assign({ url: Parse.serverURL + '/cloud_code/jobs' }, masterKeyOptions)).then( + done, + done.fail + ); }); it('should create a job schedule', done => { @@ -107,10 +99,7 @@ describe('JobSchedule', () => { }) .then(() => { return request( - Object.assign( - { url: Parse.serverURL + '/cloud_code/jobs' }, - masterKeyOptions - ) + Object.assign({ url: Parse.serverURL + '/cloud_code/jobs' }, masterKeyOptions) ); }) .then(res => { @@ -267,10 +256,7 @@ describe('JobSchedule', () => { }) .then(() => { return request( - Object.assign( - { url: Parse.serverURL + '/cloud_code/jobs/data' }, - masterKeyOptions - ) + Object.assign({ url: Parse.serverURL + '/cloud_code/jobs/data' }, masterKeyOptions) ); }) .then(response => { diff --git a/spec/LdapAuth.spec.js b/spec/LdapAuth.spec.js index 321d8de1..3294dfb0 100644 --- a/spec/LdapAuth.spec.js +++ b/spec/LdapAuth.spec.js @@ -13,10 +13,7 @@ it('Should fail with missing options', done => { }); it('Should return a resolved promise when validating the app id', done => { - ldap - .validateAppId() - .then(done) - .catch(done.fail); + ldap.validateAppId().then(done).catch(done.fail); }); it('Should succeed with right credentials', done => { @@ -59,8 +56,7 @@ it('Should succeed if user is in given group', done => { url: `ldap://localhost:${port}`, dn: 'uid={{id}}, o=example', groupCn: 'powerusers', - groupFilter: - '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', + groupFilter: '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', }; ldap @@ -78,8 +74,7 @@ it('Should fail if user is not in given group', done => { url: `ldap://localhost:${port}`, dn: 'uid={{id}}, o=example', groupCn: 'groupTheUserIsNotIn', - groupFilter: - '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', + groupFilter: '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', }; ldap @@ -100,8 +95,7 @@ it('Should fail if the LDAP server does not allow searching inside the provided url: `ldap://localhost:${port}`, dn: 'uid={{id}}, o=example', groupCn: 'powerusers', - groupFilter: - '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', + groupFilter: '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', }; ldap @@ -122,8 +116,7 @@ it('Should fail if the LDAP server encounters an error while searching', done => url: `ldap://localhost:${port}`, dn: 'uid={{id}}, o=example', groupCn: 'powerusers', - groupFilter: - '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', + groupFilter: '(&(uniqueMember=uid={{id}}, o=example)(objectClass=groupOfUniqueNames))', }; ldap diff --git a/spec/LoggerController.spec.js b/spec/LoggerController.spec.js index a98e7d63..7b2e7867 100644 --- a/spec/LoggerController.spec.js +++ b/spec/LoggerController.spec.js @@ -1,5 +1,4 @@ -const LoggerController = require('../lib/Controllers/LoggerController') - .LoggerController; +const LoggerController = require('../lib/Controllers/LoggerController').LoggerController; const WinstonLoggerAdapter = require('../lib/Adapters/Logger/WinstonLoggerAdapter') .WinstonLoggerAdapter; @@ -13,7 +12,7 @@ describe('LoggerController', () => { expect(() => { loggerController .getLogs(query) - .then(function(res) { + .then(function (res) { expect(res.length).not.toBe(0); done(); }) @@ -28,9 +27,7 @@ describe('LoggerController', () => { expect(LoggerController.validDateTime()).toBe(null); expect(LoggerController.validDateTime('String')).toBe(null); expect(LoggerController.validDateTime(123456).getTime()).toBe(123456); - expect( - LoggerController.validDateTime('2016-01-01Z00:00:00').getTime() - ).toBe(1451606400000); + expect(LoggerController.validDateTime('2016-01-01Z00:00:00').getTime()).toBe(1451606400000); done(); }); @@ -77,7 +74,7 @@ describe('LoggerController', () => { expect(() => { loggerController .getLogs(query) - .then(function(res) { + .then(function (res) { expect(res.length).not.toBe(0); done(); }) @@ -122,7 +119,7 @@ describe('LoggerController', () => { expect(() => { loggerController .getLogs(query) - .then(function(res) { + .then(function (res) { expect(res.length).not.toBe(0); done(); }) diff --git a/spec/LogsRouter.spec.js b/spec/LogsRouter.spec.js index 014486d8..7a70ef9f 100644 --- a/spec/LogsRouter.spec.js +++ b/spec/LogsRouter.spec.js @@ -2,8 +2,7 @@ const request = require('../lib/request'); const LogsRouter = require('../lib/Routers/LogsRouter').LogsRouter; -const LoggerController = require('../lib/Controllers/LoggerController') - .LoggerController; +const LoggerController = require('../lib/Controllers/LoggerController').LoggerController; const WinstonLoggerAdapter = require('../lib/Adapters/Logger/WinstonLoggerAdapter') .WinstonLoggerAdapter; @@ -77,11 +76,10 @@ describe('LogsRouter', () => { it('does scrub simple passwords on GET login', done => { reconfigureServer({ verbose: true, - }).then(function() { + }).then(function () { request({ headers: headers, - url: - 'http://localhost:8378/1/login?username=test&password=simplepass.com', + url: 'http://localhost:8378/1/login?username=test&password=simplepass.com', }) .catch(() => {}) .then(() => { @@ -92,9 +90,7 @@ describe('LogsRouter', () => { const body = response.data; expect(response.status).toEqual(200); // 4th entry is our actual GET request - expect(body[2].url).toEqual( - '/1/login?username=test&password=********' - ); + expect(body[2].url).toEqual('/1/login?username=test&password=********'); expect(body[2].message).toEqual( 'REQUEST for [GET] /1/login?username=test&password=********: {}' ); @@ -111,7 +107,7 @@ describe('LogsRouter', () => { reconfigureServer({ verbose: true, }) - .then(function() { + .then(function () { return request({ headers: headers, // using urlencoded password, 'simple @,/?:&=+$#pass.com' @@ -127,9 +123,7 @@ describe('LogsRouter', () => { const body = response.data; expect(response.status).toEqual(200); // 4th entry is our actual GET request - expect(body[2].url).toEqual( - '/1/login?username=test&password=********' - ); + expect(body[2].url).toEqual('/1/login?username=test&password=********'); expect(body[2].message).toEqual( 'REQUEST for [GET] /1/login?username=test&password=********: {}' ); @@ -146,7 +140,7 @@ describe('LogsRouter', () => { it('does not have password field in POST login', done => { reconfigureServer({ verbose: true, - }).then(function() { + }).then(function () { request({ method: 'POST', headers: headers, diff --git a/spec/Middlewares.spec.js b/spec/Middlewares.spec.js index 8c1ae6c9..2c380152 100644 --- a/spec/Middlewares.spec.js +++ b/spec/Middlewares.spec.js @@ -298,9 +298,7 @@ describe('middlewares', () => { headers[key] = value; }, }; - const allowCrossDomain = middlewares.allowCrossDomain( - fakeReq.body._ApplicationId - ); + const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId); allowCrossDomain(fakeReq, res, () => {}); expect(Object.keys(headers).length).toBe(4); expect(headers['Access-Control-Expose-Headers']).toBe( @@ -318,21 +316,15 @@ describe('middlewares', () => { headers[key] = value; }, }; - const allowCrossDomain = middlewares.allowCrossDomain( - fakeReq.body._ApplicationId - ); + const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId); allowCrossDomain(fakeReq, res, () => {}); - expect(headers['Access-Control-Allow-Headers']).toContain( - middlewares.DEFAULT_ALLOWED_HEADERS - ); + expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS); AppCache.put(fakeReq.body._ApplicationId, { allowHeaders: [], }); allowCrossDomain(fakeReq, res, () => {}); - expect(headers['Access-Control-Allow-Headers']).toContain( - middlewares.DEFAULT_ALLOWED_HEADERS - ); + expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS); }); it('should append custom headers to Access-Control-Allow-Headers if allowHeaders provided', () => { @@ -345,16 +337,10 @@ describe('middlewares', () => { headers[key] = value; }, }; - const allowCrossDomain = middlewares.allowCrossDomain( - fakeReq.body._ApplicationId - ); + const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId); allowCrossDomain(fakeReq, res, () => {}); - expect(headers['Access-Control-Allow-Headers']).toContain( - 'Header-1, Header-2' - ); - expect(headers['Access-Control-Allow-Headers']).toContain( - middlewares.DEFAULT_ALLOWED_HEADERS - ); + expect(headers['Access-Control-Allow-Headers']).toContain('Header-1, Header-2'); + expect(headers['Access-Control-Allow-Headers']).toContain(middlewares.DEFAULT_ALLOWED_HEADERS); }); it('should set default Access-Control-Allow-Origin if allowOrigin is empty', () => { @@ -367,9 +353,7 @@ describe('middlewares', () => { headers[key] = value; }, }; - const allowCrossDomain = middlewares.allowCrossDomain( - fakeReq.body._ApplicationId - ); + const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId); allowCrossDomain(fakeReq, res, () => {}); expect(headers['Access-Control-Allow-Origin']).toEqual('*'); }); @@ -384,13 +368,9 @@ describe('middlewares', () => { headers[key] = value; }, }; - const allowCrossDomain = middlewares.allowCrossDomain( - fakeReq.body._ApplicationId - ); + const allowCrossDomain = middlewares.allowCrossDomain(fakeReq.body._ApplicationId); allowCrossDomain(fakeReq, res, () => {}); - expect(headers['Access-Control-Allow-Origin']).toEqual( - 'https://parseplatform.org/' - ); + expect(headers['Access-Control-Allow-Origin']).toEqual('https://parseplatform.org/'); }); it('should use user provided on field userFromJWT', done => { diff --git a/spec/MockAdapter.js b/spec/MockAdapter.js index 3deaaaae..b1fcd416 100644 --- a/spec/MockAdapter.js +++ b/spec/MockAdapter.js @@ -1,4 +1,4 @@ -module.exports = function(options) { +module.exports = function (options) { return { options: options, }; diff --git a/spec/MockLdapServer.js b/spec/MockLdapServer.js index 767d56fe..fc31b1f4 100644 --- a/spec/MockLdapServer.js +++ b/spec/MockLdapServer.js @@ -3,14 +3,14 @@ const ldapjs = require('ldapjs'); function newServer(port, dn, provokeSearchError = false) { const server = ldapjs.createServer(); - server.bind('o=example', function(req, res, next) { + server.bind('o=example', function (req, res, next) { if (req.dn.toString() !== dn || req.credentials !== 'secret') return next(new ldapjs.InvalidCredentialsError()); res.end(); return next(); }); - server.search('o=example', function(req, res, next) { + server.search('o=example', function (req, res, next) { if (provokeSearchError) { res.end(ldapjs.LDAP_SIZE_LIMIT_EXCEEDED); return next(); diff --git a/spec/MockPushAdapter.js b/spec/MockPushAdapter.js index 6c7c2e3d..bb31a365 100644 --- a/spec/MockPushAdapter.js +++ b/spec/MockPushAdapter.js @@ -1,8 +1,8 @@ -module.exports = function(options) { +module.exports = function (options) { return { options: options, - send: function() {}, - getValidPushTypes: function() { + send: function () {}, + getValidPushTypes: function () { return Object.keys(options.options); }, }; diff --git a/spec/MongoStorageAdapter.spec.js b/spec/MongoStorageAdapter.spec.js index 35637ebf..b63da316 100644 --- a/spec/MongoStorageAdapter.spec.js +++ b/spec/MongoStorageAdapter.spec.js @@ -1,10 +1,8 @@ 'use strict'; -const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter') - .default; +const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; const { MongoClient } = require('mongodb'); -const databaseURI = - 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; +const databaseURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; const request = require('../lib/request'); const Config = require('../lib/Config'); const TestUtils = require('../lib/TestUtils'); @@ -19,16 +17,13 @@ const fakeClient = { // and will eventually be moved into their own repo describe_only_db('mongo')('MongoStorageAdapter', () => { beforeEach(done => { - new MongoStorageAdapter({ uri: databaseURI }) - .deleteAllClasses() - .then(done, fail); + new MongoStorageAdapter({ uri: databaseURI }).deleteAllClasses().then(done, fail); }); it('auto-escapes symbols in auth information', () => { spyOn(MongoClient, 'connect').and.returnValue(Promise.resolve(fakeClient)); new MongoStorageAdapter({ - uri: - 'mongodb://user!with@+ symbols:password!with@+ symbols@localhost:1234/parse', + uri: 'mongodb://user!with@+ symbols:password!with@+ symbols@localhost:1234/parse', }).connect(); expect(MongoClient.connect).toHaveBeenCalledWith( 'mongodb://user!with%40%2B%20symbols:password!with%40%2B%20symbols@localhost:1234/parse', @@ -39,8 +34,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { it("doesn't double escape already URI-encoded information", () => { spyOn(MongoClient, 'connect').and.returnValue(Promise.resolve(fakeClient)); new MongoStorageAdapter({ - uri: - 'mongodb://user!with%40%2B%20symbols:password!with%40%2B%20symbols@localhost:1234/parse', + uri: 'mongodb://user!with%40%2B%20symbols:password!with%40%2B%20symbols@localhost:1234/parse', }).connect(); expect(MongoClient.connect).toHaveBeenCalledWith( 'mongodb://user!with%40%2B%20symbols:password!with%40%2B%20symbols@localhost:1234/parse', @@ -83,9 +77,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); adapter .createObject('Foo', { fields: {} }, { objectId: 'abcde' }) - .then(() => - adapter._rawFind('Foo', { $where: `sleep(${maxTimeMS / 2})` }) - ) + .then(() => adapter._rawFind('Foo', { $where: `sleep(${maxTimeMS / 2})` })) .then( () => done(), err => { @@ -102,9 +94,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); adapter .createObject('Foo', { fields: {} }, { objectId: 'abcde' }) - .then(() => - adapter._rawFind('Foo', { $where: `sleep(${maxTimeMS * 2})` }) - ) + .then(() => adapter._rawFind('Foo', { $where: `sleep(${maxTimeMS * 2})` })) .then( () => { done.fail('Find succeeded despite taking too long!'); @@ -314,9 +304,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { it('getClass if not exists', async () => { const adapter = new MongoStorageAdapter({ uri: databaseURI }); - await expectAsync(adapter.getClass('UnknownClass')).toBeRejectedWith( - undefined - ); + await expectAsync(adapter.getClass('UnknownClass')).toBeRejectedWith(undefined); }); it('should use index for caseInsensitive query', async () => { @@ -357,9 +345,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { obj.set('test', 1); await obj.save(); const schemaBeforeDeletion = await new Parse.Schema('MyObject').get(); - await database.adapter.deleteFields('MyObject', schemaBeforeDeletion, [ - 'test', - ]); + await database.adapter.deleteFields('MyObject', schemaBeforeDeletion, ['test']); const schemaAfterDeletion = await new Parse.Schema('MyObject').get(); expect(schemaBeforeDeletion.fields.test).toBeDefined(); expect(schemaAfterDeletion.fields.test).toBeUndefined(); @@ -371,12 +357,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { obj.set('test', 1); await obj.save(); const schemaBeforeDeletion = await new Parse.Schema('MyObject').get(); - await database.adapter.ensureIndex('MyObject', schemaBeforeDeletion, [ - 'test', - ]); - await database.adapter.deleteFields('MyObject', schemaBeforeDeletion, [ - 'test', - ]); + await database.adapter.ensureIndex('MyObject', schemaBeforeDeletion, ['test']); + await database.adapter.deleteFields('MyObject', schemaBeforeDeletion, ['test']); const schemaAfterDeletion = await new Parse.Schema('MyObject').get(); expect(schemaBeforeDeletion.fields.test).toBeDefined(); expect(schemaAfterDeletion.fields.test).toBeUndefined(); @@ -410,12 +392,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { const myObject = new Parse.Object('MyObject'); await myObject.save(); - const databaseAdapter = Config.get(Parse.applicationId).database - .adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'command' - ).and.callThrough(); + const databaseAdapter = Config.get(Parse.applicationId).database.adapter; + spyOn(databaseAdapter.database.serverConfig, 'command').and.callThrough(); await request({ method: 'POST', @@ -434,14 +412,10 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); let found = false; - databaseAdapter.database.serverConfig.command.calls - .all() - .forEach(call => { - found = true; - expect(call.args[2].session.transaction.state).not.toBe( - 'NO_TRANSACTION' - ); - }); + databaseAdapter.database.serverConfig.command.calls.all().forEach(call => { + found = true; + expect(call.args[2].session.transaction.state).not.toBe('NO_TRANSACTION'); + }); expect(found).toBe(true); }); @@ -449,12 +423,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { const myObject = new Parse.Object('MyObject'); await myObject.save(); - const databaseAdapter = Config.get(Parse.applicationId).database - .adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'command' - ).and.callThrough(); + const databaseAdapter = Config.get(Parse.applicationId).database.adapter; + spyOn(databaseAdapter.database.serverConfig, 'command').and.callThrough(); await request({ method: 'POST', @@ -473,12 +443,10 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); let found = false; - databaseAdapter.database.serverConfig.command.calls - .all() - .forEach(call => { - found = true; - expect(call.args[2].session).toBe(undefined); - }); + databaseAdapter.database.serverConfig.command.calls.all().forEach(call => { + found = true; + expect(call.args[2].session).toBe(undefined); + }); expect(found).toBe(true); }); @@ -486,12 +454,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { const myObject = new Parse.Object('MyObject'); await myObject.save(); - const databaseAdapter = Config.get(Parse.applicationId).database - .adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'command' - ).and.callThrough(); + const databaseAdapter = Config.get(Parse.applicationId).database.adapter; + spyOn(databaseAdapter.database.serverConfig, 'command').and.callThrough(); await request({ method: 'POST', @@ -509,12 +473,10 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); let found = false; - databaseAdapter.database.serverConfig.command.calls - .all() - .forEach(call => { - found = true; - expect(call.args[2].session).toBe(undefined); - }); + databaseAdapter.database.serverConfig.command.calls.all().forEach(call => { + found = true; + expect(call.args[2].session).toBe(undefined); + }); expect(found).toBe(true); }); @@ -522,12 +484,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { const myObject = new Parse.Object('MyObject'); await myObject.save(); - const databaseAdapter = Config.get(Parse.applicationId).database - .adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'command' - ).and.callThrough(); + const databaseAdapter = Config.get(Parse.applicationId).database.adapter; + spyOn(databaseAdapter.database.serverConfig, 'command').and.callThrough(); await request({ method: 'PUT', @@ -537,22 +495,16 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); let found = false; - databaseAdapter.database.serverConfig.command.calls - .all() - .forEach(call => { - found = true; - expect(call.args[2].session).toBe(undefined); - }); + databaseAdapter.database.serverConfig.command.calls.all().forEach(call => { + found = true; + expect(call.args[2].session).toBe(undefined); + }); expect(found).toBe(true); }); it('should not use transactions when using SDK insert', async () => { - const databaseAdapter = Config.get(Parse.applicationId).database - .adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'insert' - ).and.callThrough(); + const databaseAdapter = Config.get(Parse.applicationId).database.adapter; + spyOn(databaseAdapter.database.serverConfig, 'insert').and.callThrough(); const myObject = new Parse.Object('MyObject'); await myObject.save(); @@ -565,12 +517,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); it('should not use transactions when using SDK update', async () => { - const databaseAdapter = Config.get(Parse.applicationId).database - .adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'update' - ).and.callThrough(); + const databaseAdapter = Config.get(Parse.applicationId).database.adapter; + spyOn(databaseAdapter.database.serverConfig, 'update').and.callThrough(); const myObject = new Parse.Object('MyObject'); await myObject.save(); @@ -586,12 +534,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); it('should not use transactions when using SDK delete', async () => { - const databaseAdapter = Config.get(Parse.applicationId).database - .adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'remove' - ).and.callThrough(); + const databaseAdapter = Config.get(Parse.applicationId).database.adapter; + spyOn(databaseAdapter.database.serverConfig, 'remove').and.callThrough(); const myObject = new Parse.Object('MyObject'); await myObject.save(); diff --git a/spec/MongoTransform.spec.js b/spec/MongoTransform.spec.js index c62a2a98..6834a6b2 100644 --- a/spec/MongoTransform.spec.js +++ b/spec/MongoTransform.spec.js @@ -460,11 +460,7 @@ describe('parseObjectToMongoObjectForCreate', () => { it('$regex in $all list', done => { const input = { arrayField: { - $all: [ - { $regex: '^\\Qone\\E' }, - { $regex: '^\\Qtwo\\E' }, - { $regex: '^\\Qthree\\E' }, - ], + $all: [{ $regex: '^\\Qone\\E' }, { $regex: '^\\Qtwo\\E' }, { $regex: '^\\Qthree\\E' }], }, }; const outputValue = { @@ -625,9 +621,7 @@ describe('relativeTimeToDate', () => { describe('Error cases', () => { it('should error if string is completely gibberish', () => { - expect( - transform.relativeTimeToDate('gibberishasdnklasdnjklasndkl123j123') - ).toEqual({ + expect(transform.relativeTimeToDate('gibberishasdnklasdnjklasndkl123j123')).toEqual({ status: 'error', info: "Time should either start with 'in' or end with 'ago'", }); diff --git a/spec/NullCacheAdapter.spec.js b/spec/NullCacheAdapter.spec.js index 8c240eef..f5d5e508 100644 --- a/spec/NullCacheAdapter.spec.js +++ b/spec/NullCacheAdapter.spec.js @@ -1,7 +1,6 @@ -const NullCacheAdapter = require('../lib/Adapters/Cache/NullCacheAdapter') - .default; +const NullCacheAdapter = require('../lib/Adapters/Cache/NullCacheAdapter').default; -describe('NullCacheAdapter', function() { +describe('NullCacheAdapter', function () { const KEY = 'hello'; const VALUE = 'world'; @@ -11,12 +10,7 @@ describe('NullCacheAdapter', function() { }); // Verify all methods return promises. - Promise.all([ - cache.put(KEY, VALUE), - cache.del(KEY), - cache.get(KEY), - cache.clear(), - ]).then(() => { + Promise.all([cache.put(KEY, VALUE), cache.del(KEY), cache.get(KEY), cache.clear()]).then(() => { done(); }); }); diff --git a/spec/OAuth1.spec.js b/spec/OAuth1.spec.js index 8d256f75..3234394c 100644 --- a/spec/OAuth1.spec.js +++ b/spec/OAuth1.spec.js @@ -1,6 +1,6 @@ const OAuth = require('../lib/Adapters/Auth/OAuth1Client'); -describe('OAuth', function() { +describe('OAuth', function () { it('Nonce should have right length', done => { jequal(OAuth.nonce().length, 30); done(); @@ -39,12 +39,7 @@ describe('OAuth', function() { const consumer_secret = 'world'; const auth_token_secret = 'secret'; - request = OAuth.signRequest( - request, - oauth_params, - consumer_secret, - auth_token_secret - ); + request = OAuth.signRequest(request, oauth_params, consumer_secret, auth_token_secret); jequal( request.headers['Authorization'], 'OAuth oauth_consumer_key="hello", oauth_nonce="AAAAAAAAAAAAAAAAA", oauth_signature="8K95bpQcDi9Nd2GkhumTVcw4%2BXw%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="123450000", oauth_token="token", oauth_version="1.0"' @@ -101,7 +96,7 @@ describe('OAuth', function() { const path = '/1.1/help/configuration.json'; const params = { lang: 'en' }; const oauthClient = new OAuth(options); - oauthClient.get(path, params).then(function(data) { + oauthClient.get(path, params).then(function (data) { validateCannotAuthenticateError(data, done); }); }); @@ -118,7 +113,7 @@ describe('OAuth', function() { const path = '/1.1/account/settings.json'; const oauthClient = new OAuth(options); - oauthClient.post(path, null, body).then(function(data) { + oauthClient.post(path, null, body).then(function (data) { validateCannotAuthenticateError(data, done); }); }); @@ -137,11 +132,11 @@ describe('OAuth', function() { const oauthClient = new OAuth(options); oauthClient .post(path, null, body) - .then(function() { + .then(function () { jequal(false, true); done(); }) - .catch(function() { + .catch(function () { jequal(true, true); done(); }); diff --git a/spec/Parse.Push.spec.js b/spec/Parse.Push.spec.js index 6a424935..b0fd60e8 100644 --- a/spec/Parse.Push.spec.js +++ b/spec/Parse.Push.spec.js @@ -9,11 +9,11 @@ const delayPromise = delay => { }; describe('Parse.Push', () => { - const setup = function() { + const setup = function () { const sendToInstallationSpy = jasmine.createSpy(); const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { const badge = body.data.badge; const promises = installations.map(installation => { sendToInstallationSpy(installation); @@ -32,7 +32,7 @@ describe('Parse.Push', () => { }); return Promise.all(promises); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios', 'android']; }, }; @@ -49,14 +49,8 @@ describe('Parse.Push', () => { const installations = []; while (installations.length != 10) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); - installation.set( - 'deviceToken', - 'device_token_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); + installation.set('deviceToken', 'device_token_' + installations.length); installation.set('badge', installations.length); installation.set('originalBadge', installations.length); installation.set('deviceType', 'ios'); @@ -200,9 +194,7 @@ describe('Parse.Push', () => { try { expect(body.results.length).toEqual(1); expect(body.results[0].query).toEqual('{"deviceType":"ios"}'); - expect(body.results[0].payload).toEqual( - '{"badge":"increment","alert":"Hello world!"}' - ); + expect(body.results[0].payload).toEqual('{"badge":"increment","alert":"Hello world!"}'); } catch (e) { jfail(e); } @@ -246,7 +238,7 @@ describe('Parse.Push', () => { }); }); - const successfulAny = function(body, installations) { + const successfulAny = function (body, installations) { const promises = installations.map(device => { return Promise.resolve({ transmitted: true, @@ -257,7 +249,7 @@ describe('Parse.Push', () => { return Promise.all(promises); }; - const provideInstallations = function(num) { + const provideInstallations = function (num) { if (!num) { num = 2; } @@ -266,10 +258,7 @@ describe('Parse.Push', () => { while (installations.length !== num) { // add Android installations 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('deviceType', 'android'); installations.push(installation); @@ -279,14 +268,14 @@ describe('Parse.Push', () => { }; const losingAdapter = { - send: function(body, installations) { + send: function (body, installations) { // simulate having lost an installation before this was called // thus invalidating our 'count' in _PushStatus installations.pop(); return successfulAny(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['android']; }, }; @@ -346,10 +335,7 @@ describe('Parse.Push', () => { // add 1 iOS installation which we will omit & add later on const iOSInstallation = new Parse.Object('_Installation'); - iOSInstallation.set( - 'installationId', - 'installation_' + installations.length - ); + iOSInstallation.set('installationId', 'installation_' + installations.length); iOSInstallation.set('deviceToken', 'device_token_' + installations.length); iOSInstallation.set('deviceType', 'ios'); installations.push(iOSInstallation); @@ -357,14 +343,14 @@ describe('Parse.Push', () => { reconfigureServer({ push: { adapter: { - send: function(body, installations) { + send: function (body, installations) { // simulate having added an installation before this was called // thus invalidating our 'count' in _PushStatus installations.push(iOSInstallation); return successfulAny(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['android']; }, }, @@ -469,14 +455,8 @@ describe('Parse.Push', () => { while (iOSInstallations.length !== devices / 100) { const iOSInstallation = new Parse.Object('_Installation'); - iOSInstallation.set( - 'installationId', - 'installation_' + installations.length - ); - iOSInstallation.set( - 'deviceToken', - 'device_token_' + installations.length - ); + iOSInstallation.set('installationId', 'installation_' + installations.length); + iOSInstallation.set('deviceToken', 'device_token_' + installations.length); iOSInstallation.set('deviceType', 'ios'); installations.push(iOSInstallation); iOSInstallations.push(iOSInstallation); @@ -485,14 +465,14 @@ describe('Parse.Push', () => { reconfigureServer({ push: { adapter: { - send: function(body, installations) { + send: function (body, installations) { // simulate having added an installation before this was called // thus invalidating our 'count' in _PushStatus installations.push(iOSInstallations.pop()); return successfulAny(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['android']; }, }, diff --git a/spec/ParseACL.spec.js b/spec/ParseACL.spec.js index 80e5a400..a55f40cd 100644 --- a/spec/ParseACL.spec.js +++ b/spec/ParseACL.spec.js @@ -9,7 +9,7 @@ describe('Parse.ACL', () => { const user = new Parse.User(); ok( !user.setACL("Ceci n'est pas un ACL.", { - error: function(user, error) { + error: function (user, error) { equal(error.code, -1); done(); }, @@ -466,7 +466,7 @@ describe('Parse.ACL', () => { await Parse.User.logOut(); // Find const query = new Parse.Query(TestObject); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 0); done(); }); @@ -747,7 +747,7 @@ describe('Parse.ACL', () => { // Start making requests by the public. Parse.User.logOut().then(() => { const query = new Parse.Query(TestObject); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 0); done(); }); @@ -846,7 +846,7 @@ describe('Parse.ACL', () => { await Parse.Object.saveAll([object1, object2]); const query = new Parse.Query(TestObject); query.equalTo('foo', 'bar'); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 2); done(); }); diff --git a/spec/ParseAPI.spec.js b/spec/ParseAPI.spec.js index dd987164..0a8c1475 100644 --- a/spec/ParseAPI.spec.js +++ b/spec/ParseAPI.spec.js @@ -38,12 +38,7 @@ describe_only_db('mongo')('miscellaneous', () => { }) .then(() => { const config = Config.get(appId); - return config.database.adapter.find( - 'TestObject', - { fields: {} }, - {}, - {} - ); + return config.database.adapter.find('TestObject', { fields: {} }, {}, {}); }) .then(results => { expect(results.length).toEqual(1); @@ -270,11 +265,7 @@ describe('miscellaneous', function () { const config = Config.get('test'); 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(() => { const user = new Parse.User(); user.setPassword('asdf'); @@ -1115,8 +1106,7 @@ describe('miscellaneous', function () { request({ method: 'DELETE', headers: headers, - url: - 'http://localhost:8378/1/classes/GameScore/' + response.data.objectId, + url: 'http://localhost:8378/1/classes/GameScore/' + response.data.objectId, }).then(() => { expect(triggerTime).toEqual(2); done(); @@ -1278,9 +1268,7 @@ describe('miscellaneous', function () { }, e => { expect(e.code).toEqual(Parse.Error.SCRIPT_FAILED); - expect(e.message).toEqual( - 'Invalid function: "somethingThatDoesDefinitelyNotExist"' - ); + expect(e.message).toEqual('Invalid function: "somethingThatDoesDefinitelyNotExist"'); done(); } ); @@ -1611,9 +1599,7 @@ describe('miscellaneous', function () { fail('Should not succeed'); }) .catch(response => { - expect(response.data.error).toEqual( - 'unauthorized: master key is required' - ); + expect(response.data.error).toEqual('unauthorized: master key is required'); done(); }); }); @@ -1756,9 +1742,7 @@ describe_only_db('mongo')('legacy _acl', () => { .then(() => { const config = Config.get('test'); const adapter = config.database.adapter; - return adapter - ._adaptiveCollection('Report') - .then(collection => collection.find({})); + return adapter._adaptiveCollection('Report').then(collection => collection.find({})); }) .then(results => { expect(results.length).toBe(1); diff --git a/spec/ParseCloudCodePublisher.spec.js b/spec/ParseCloudCodePublisher.spec.js index 905b0cbb..3435d44b 100644 --- a/spec/ParseCloudCodePublisher.spec.js +++ b/spec/ParseCloudCodePublisher.spec.js @@ -2,8 +2,8 @@ const ParseCloudCodePublisher = require('../lib/LiveQuery/ParseCloudCodePublishe .ParseCloudCodePublisher; const Parse = require('parse/node'); -describe('ParseCloudCodePublisher', function() { - beforeEach(function(done) { +describe('ParseCloudCodePublisher', function () { + beforeEach(function (done) { // Mock ParsePubSub const mockParsePubSub = { createPublisher: jasmine.createSpy('publish').and.returnValue({ @@ -15,15 +15,11 @@ describe('ParseCloudCodePublisher', function() { on: jasmine.createSpy('on'), }), }; - jasmine.mockLibrary( - '../lib/LiveQuery/ParsePubSub', - 'ParsePubSub', - mockParsePubSub - ); + jasmine.mockLibrary('../lib/LiveQuery/ParsePubSub', 'ParsePubSub', mockParsePubSub); done(); }); - it('can initialize', function() { + it('can initialize', function () { const config = {}; new ParseCloudCodePublisher(config); @@ -31,7 +27,7 @@ describe('ParseCloudCodePublisher', function() { expect(ParsePubSub.createPublisher).toHaveBeenCalledWith(config); }); - it('can handle cloud code afterSave request', function() { + it('can handle cloud code afterSave request', function () { const publisher = new ParseCloudCodePublisher({}); publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage'); const request = {}; @@ -43,7 +39,7 @@ describe('ParseCloudCodePublisher', function() { ); }); - it('can handle cloud code afterDelete request', function() { + it('can handle cloud code afterDelete request', function () { const publisher = new ParseCloudCodePublisher({}); publisher._onCloudCodeMessage = jasmine.createSpy('onCloudCodeMessage'); const request = {}; @@ -55,7 +51,7 @@ describe('ParseCloudCodePublisher', function() { ); }); - it('can handle cloud code request', function() { + it('can handle cloud code request', function () { const publisher = new ParseCloudCodePublisher({}); const currentParseObject = new Parse.Object('Test'); currentParseObject.set('key', 'value'); @@ -74,7 +70,7 @@ describe('ParseCloudCodePublisher', function() { expect(message.originalParseObject).toEqual(request.original._toFullJSON()); }); - afterEach(function() { + afterEach(function () { jasmine.restoreLibrary('../lib/LiveQuery/ParsePubSub', 'ParsePubSub'); }); }); diff --git a/spec/ParseFile.spec.js b/spec/ParseFile.spec.js index bb1c5c51..410d15c8 100644 --- a/spec/ParseFile.spec.js +++ b/spec/ParseFile.spec.js @@ -27,9 +27,7 @@ describe('Parse.File testing', () => { }).then(response => { const b = response.data; expect(b.name).toMatch(/_file.txt$/); - expect(b.url).toMatch( - /^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/ - ); + expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/); request({ url: b.url }).then(response => { const body = response.text; expect(body).toEqual('argle bargle'); @@ -51,9 +49,7 @@ describe('Parse.File testing', () => { }).then(response => { const b = response.data; expect(b.name).toMatch(/_file.html/); - expect(b.url).toMatch( - /^http:\/\/localhost:8378\/1\/files\/test\/.*file.html$/ - ); + expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.html$/); request({ url: b.url }).then(response => { const body = response.text; try { @@ -80,9 +76,7 @@ describe('Parse.File testing', () => { }).then(response => { const b = response.data; expect(b.name).toMatch(/_file.txt$/); - expect(b.url).toMatch( - /^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/ - ); + expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*file.txt$/); request({ url: b.url }).then(response => { expect(response.text).toEqual('argle bargle'); done(); @@ -105,9 +99,7 @@ describe('Parse.File testing', () => { }).then(response => { const b = response.data; expect(b.name).toMatch(/_testfile.txt$/); - expect(b.url).toMatch( - /^http:\/\/localhost:8378\/1\/files\/test\/.*testfile.txt$/ - ); + expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*testfile.txt$/); request({ url: b.url }).then(response => { const body = response.text; expect(body).toEqual('check one two'); @@ -149,9 +141,7 @@ describe('Parse.File testing', () => { body: 'the file body', }).then(response => { const b = response.data; - expect(b.url).toMatch( - /^http:\/\/localhost:8378\/1\/files\/test\/.*thefile.jpg$/ - ); + expect(b.url).toMatch(/^http:\/\/localhost:8378\/1\/files\/test\/.*thefile.jpg$/); // missing X-Parse-Master-Key header request({ method: 'DELETE', @@ -304,19 +294,19 @@ describe('Parse.File testing', () => { let firstName; let secondName; - const firstSave = file.save().then(function() { + const firstSave = file.save().then(function () { firstName = file.name(); }); - const secondSave = file.save().then(function() { + const secondSave = file.save().then(function () { secondName = file.name(); }); Promise.all([firstSave, secondSave]).then( - function() { + function () { equal(firstName, secondName); done(); }, - function(error) { + function (error) { ok(false, error); done(); } @@ -484,9 +474,7 @@ describe('Parse.File testing', () => { }) .then(result => { const fileAgain = result.get('oldfile'); - expect(fileAgain.url()).toEqual( - 'http://files.parsetfss.com/test/tfss-123.txt' - ); + expect(fileAgain.url()).toEqual('http://files.parsetfss.com/test/tfss-123.txt'); done(); }) .catch(e => { diff --git a/spec/ParseGeoPoint.spec.js b/spec/ParseGeoPoint.spec.js index 3b57412f..83868e8d 100644 --- a/spec/ParseGeoPoint.spec.js +++ b/spec/ParseGeoPoint.spec.js @@ -76,25 +76,22 @@ 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', - async done => { - const point = new Parse.GeoPoint(20, 20); - const obj = new TestObject(); - obj.set('locationOne', point); - await obj.save(); - obj.set('locationTwo', point); - obj.save().then( - () => { - fail('expected error'); - }, - err => { - equal(err.code, Parse.Error.INCORRECT_TYPE); - 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); + 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', async done => { const line = []; @@ -120,7 +117,7 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance large', done => { const objects = []; - [0, 1, 2].map(function(i) { + [0, 1, 2].map(function (i) { const obj = new TestObject(); const point = new Parse.GeoPoint(0.0, i * 45.0); obj.set('location', point); @@ -148,7 +145,7 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance medium', async () => { const objects = []; - [0, 1, 2].map(function(i) { + [0, 1, 2].map(function (i) { const obj = new TestObject(); const point = new Parse.GeoPoint(0.0, i * 45.0); obj.set('location', point); @@ -167,7 +164,7 @@ describe('Parse.GeoPoint testing', () => { it('geo max distance small', async () => { const objects = []; - [0, 1, 2].map(function(i) { + [0, 1, 2].map(function (i) { const obj = new TestObject(); const point = new Parse.GeoPoint(0.0, i * 45.0); obj.set('location', point); @@ -183,7 +180,7 @@ describe('Parse.GeoPoint testing', () => { equal(results[0].get('index'), 0); }); - const makeSomeGeoPoints = function() { + const makeSomeGeoPoints = function () { const sacramento = new TestObject(); sacramento.set('location', new Parse.GeoPoint(38.52, -121.5)); sacramento.set('name', 'Sacramento'); @@ -445,7 +442,13 @@ describe('Parse.GeoPoint testing', () => { const obj3 = new Parse.Object('Polygon', { location: outbound }); const polygon = { __type: 'Polygon', - coordinates: [[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]], + coordinates: [ + [0, 0], + [10, 0], + [10, 10], + [0, 10], + [0, 0], + ], }; Parse.Object.saveAll([obj1, obj2, obj3]) .then(() => { @@ -478,7 +481,10 @@ describe('Parse.GeoPoint testing', () => { const obj = new Parse.Object('Polygon', { location: point }); const polygon = { __type: 'Polygon', - coordinates: [[0, 0], [10, 0]], + coordinates: [ + [0, 0], + [10, 0], + ], }; obj .save() @@ -516,7 +522,11 @@ describe('Parse.GeoPoint testing', () => { const obj = new Parse.Object('Polygon', { location: point }); const polygon = { __type: 'Polygon', - coordinates: [[0, 0], [181, 0], [0, 10]], + coordinates: [ + [0, 0], + [181, 0], + [0, 10], + ], }; obj .save() @@ -736,11 +746,7 @@ describe('Parse.GeoPoint testing', () => { await Parse.Object.saveAll([obj1, obj2]); - const q = new Parse.Query(TestObject).withinKilometers( - 'location', - inside, - 5 - ); + const q = new Parse.Query(TestObject).withinKilometers('location', inside, 5); const count = await q.count(); equal(count, 1); @@ -756,16 +762,8 @@ describe('Parse.GeoPoint testing', () => { await Parse.Object.saveAll([obj1, obj2, obj3]); - const q1 = new Parse.Query(TestObject).withinKilometers( - 'location', - inside, - 5 - ); - const q2 = new Parse.Query(TestObject).withinKilometers( - 'location', - middle, - 5 - ); + const q1 = new Parse.Query(TestObject).withinKilometers('location', inside, 5); + const q2 = new Parse.Query(TestObject).withinKilometers('location', middle, 5); const query = Parse.Query.or(q1, q2); const count = await query.count(); @@ -784,10 +782,7 @@ describe('Parse.GeoPoint testing', () => { }); await Parse.Object.saveAll([tmp, tmp2]); const query = new Parse.Query(TestObject); - query.notEqualTo( - 'location', - new Parse.GeoPoint({ latitude: 0, longitude: 0 }) - ); + query.notEqualTo('location', new Parse.GeoPoint({ latitude: 0, longitude: 0 })); const results = await query.find(); expect(results.length).toEqual(1); }); diff --git a/spec/ParseGraphQLClassNameTransformer.spec.js b/spec/ParseGraphQLClassNameTransformer.spec.js index c2a89e2f..d8a4dd60 100644 --- a/spec/ParseGraphQLClassNameTransformer.spec.js +++ b/spec/ParseGraphQLClassNameTransformer.spec.js @@ -1,11 +1,12 @@ -const { - transformClassNameToGraphQL, -} = require('../lib/GraphQL/transformers/className'); +const { transformClassNameToGraphQL } = require('../lib/GraphQL/transformers/className'); describe('transformClassNameToGraphQL', () => { it('should remove starting _ and tansform first letter to upper case', () => { - expect( - ['_User', '_user', 'User', 'user'].map(transformClassNameToGraphQL) - ).toEqual(['User', 'User', 'User', 'User']); + expect(['_User', '_user', 'User', 'user'].map(transformClassNameToGraphQL)).toEqual([ + 'User', + 'User', + 'User', + 'User', + ]); }); }); diff --git a/spec/ParseGraphQLController.spec.js b/spec/ParseGraphQLController.spec.js index 2d214c2f..4aff8473 100644 --- a/spec/ParseGraphQLController.spec.js +++ b/spec/ParseGraphQLController.spec.js @@ -37,10 +37,7 @@ describe('ParseGraphQLController', () => { const defaultFind = databaseController.find.bind(databaseController); databaseController.find = async (className, query, ...args) => { - if ( - className === GraphQLConfigClassName && - isEqual(query, { objectId: GraphQLConfigId }) - ) { + if (className === GraphQLConfigClassName && isEqual(query, { objectId: GraphQLConfigId })) { const graphQLConfigRecord = getConfigFromDb(); return graphQLConfigRecord ? [graphQLConfigRecord] : []; } else { @@ -49,12 +46,7 @@ describe('ParseGraphQLController', () => { }; const defaultUpdate = databaseController.update.bind(databaseController); - databaseController.update = async ( - className, - query, - update, - fullQueryOptions - ) => { + databaseController.update = async (className, query, update, fullQueryOptions) => { databaseUpdateArgs = [className, query, update, fullQueryOptions]; if ( className === GraphQLConfigClassName && @@ -89,9 +81,7 @@ describe('ParseGraphQLController', () => { cacheController, mountGraphQL: false, }) - ).toThrow( - 'ParseGraphQLController requires a "databaseController" to be instantiated.' - ); + ).toThrow('ParseGraphQLController requires a "databaseController" to be instantiated.'); }); it('should construct without a cacheController', () => { expect( @@ -197,13 +187,13 @@ describe('ParseGraphQLController', () => { describe('updateGraphQLConfig', () => { const successfulUpdateResponse = { response: { result: true } }; - it('should throw if graphQLConfig is not provided', async function() { + it('should throw if graphQLConfig is not provided', async function () { const parseGraphQLController = new ParseGraphQLController({ databaseController, }); - expectAsync( - parseGraphQLController.updateGraphQLConfig() - ).toBeRejectedWith('You must provide a graphQLConfig!'); + expectAsync(parseGraphQLController.updateGraphQLConfig()).toBeRejectedWith( + 'You must provide a graphQLConfig!' + ); }); it('should correct update the graphQLConfig object using the databaseController', async () => { @@ -235,32 +225,22 @@ describe('ParseGraphQLController', () => { const parseGraphQLController = new ParseGraphQLController({ databaseController, }); - expectAsync( - parseGraphQLController.updateGraphQLConfig([]) - ).toBeRejected(); - expectAsync( - parseGraphQLController.updateGraphQLConfig(function() {}) - ).toBeRejected(); - expectAsync( - parseGraphQLController.updateGraphQLConfig(Promise.resolve({})) - ).toBeRejected(); - expectAsync( - parseGraphQLController.updateGraphQLConfig('') - ).toBeRejected(); - expectAsync( - parseGraphQLController.updateGraphQLConfig({}) - ).toBeResolvedTo(successfulUpdateResponse); + expectAsync(parseGraphQLController.updateGraphQLConfig([])).toBeRejected(); + expectAsync(parseGraphQLController.updateGraphQLConfig(function () {})).toBeRejected(); + expectAsync(parseGraphQLController.updateGraphQLConfig(Promise.resolve({}))).toBeRejected(); + expectAsync(parseGraphQLController.updateGraphQLConfig('')).toBeRejected(); + expectAsync(parseGraphQLController.updateGraphQLConfig({})).toBeResolvedTo( + successfulUpdateResponse + ); }); it('should throw if graphQLConfig has an invalid root key', async () => { const parseGraphQLController = new ParseGraphQLController({ databaseController, }); - expectAsync( - parseGraphQLController.updateGraphQLConfig({ invalidKey: true }) - ).toBeRejected(); - expectAsync( - parseGraphQLController.updateGraphQLConfig({}) - ).toBeResolvedTo(successfulUpdateResponse); + expectAsync(parseGraphQLController.updateGraphQLConfig({ invalidKey: true })).toBeRejected(); + expectAsync(parseGraphQLController.updateGraphQLConfig({})).toBeResolvedTo( + successfulUpdateResponse + ); }); it('should throw if graphQLConfig has invalid class filters', async () => { const parseGraphQLController = new ParseGraphQLController({ @@ -298,9 +278,7 @@ describe('ParseGraphQLController', () => { const parseGraphQLController = new ParseGraphQLController({ databaseController, }); - expectAsync( - parseGraphQLController.updateGraphQLConfig({ classConfigs: {} }) - ).toBeRejected(); + expectAsync(parseGraphQLController.updateGraphQLConfig({ classConfigs: {} })).toBeRejected(); expectAsync( parseGraphQLController.updateGraphQLConfig({ classConfigs: [null] }) ).toBeRejected(); @@ -314,9 +292,9 @@ describe('ParseGraphQLController', () => { classConfigs: [{ className: 'ValidClass' }, null], }) ).toBeRejected(); - expectAsync( - parseGraphQLController.updateGraphQLConfig({ classConfigs: [] }) - ).toBeResolvedTo(successfulUpdateResponse); + expectAsync(parseGraphQLController.updateGraphQLConfig({ classConfigs: [] })).toBeResolvedTo( + successfulUpdateResponse + ); expectAsync( parseGraphQLController.updateGraphQLConfig({ classConfigs: [ @@ -939,34 +917,26 @@ describe('ParseGraphQLController', () => { let cacheBeforeValue; let cacheAfterValue; - cacheBeforeValue = await cacheController.graphQL.get( - mountedController.configCacheKey - ); + cacheBeforeValue = await cacheController.graphQL.get(mountedController.configCacheKey); expect(cacheBeforeValue).toBeNull(); await mountedController.updateGraphQLConfig({ enabledForClasses: ['SuperCar'], }); - cacheAfterValue = await cacheController.graphQL.get( - mountedController.configCacheKey - ); + cacheAfterValue = await cacheController.graphQL.get(mountedController.configCacheKey); expect(cacheAfterValue).toEqual({ enabledForClasses: ['SuperCar'] }); // reset removeConfigFromDb(); cacheController.graphQL.clear(); - cacheBeforeValue = await cacheController.graphQL.get( - unmountedController.configCacheKey - ); + cacheBeforeValue = await cacheController.graphQL.get(unmountedController.configCacheKey); expect(cacheBeforeValue).toBeNull(); await unmountedController.updateGraphQLConfig({ enabledForClasses: ['SuperCar'], }); - cacheAfterValue = await cacheController.graphQL.get( - unmountedController.configCacheKey - ); + cacheAfterValue = await cacheController.graphQL.get(unmountedController.configCacheKey); expect(cacheAfterValue).toBeNull(); }); }); diff --git a/spec/ParseGraphQLSchema.spec.js b/spec/ParseGraphQLSchema.spec.js index 3b368b57..e7568344 100644 --- a/spec/ParseGraphQLSchema.spec.js +++ b/spec/ParseGraphQLSchema.spec.js @@ -28,9 +28,9 @@ describe('ParseGraphQLSchema', () => { expect(() => new ParseGraphQLSchema()).toThrow( 'You must provide a parseGraphQLController instance!' ); - expect( - () => new ParseGraphQLSchema({ parseGraphQLController: {} }) - ).toThrow('You must provide a databaseController instance!'); + expect(() => new ParseGraphQLSchema({ parseGraphQLController: {} })).toThrow( + 'You must provide a databaseController instance!' + ); expect( () => new ParseGraphQLSchema({ @@ -74,17 +74,13 @@ describe('ParseGraphQLSchema', () => { await new Promise(resolve => setTimeout(resolve, 200)); await parseGraphQLSchema.load(); expect(parseClasses).not.toBe(parseGraphQLSchema.parseClasses); - expect(parseClassesString).not.toBe( - parseGraphQLSchema.parseClassesString - ); + expect(parseClassesString).not.toBe(parseGraphQLSchema.parseClassesString); expect(parseClassTypes).not.toBe(parseGraphQLSchema.parseClassTypes); expect(graphQLSchema).not.toBe(parseGraphQLSchema.graphQLSchema); expect(graphQLTypes).not.toBe(parseGraphQLSchema.graphQLTypes); expect(graphQLQueries).not.toBe(parseGraphQLSchema.graphQLQueries); expect(graphQLMutations).not.toBe(parseGraphQLSchema.graphQLMutations); - expect(graphQLSubscriptions).not.toBe( - parseGraphQLSchema.graphQLSubscriptions - ); + expect(graphQLSubscriptions).not.toBe(parseGraphQLSchema.graphQLSubscriptions); }); it('should load a brand new GraphQL Schema if graphQLConfig changes', async () => { @@ -117,17 +113,13 @@ describe('ParseGraphQLSchema', () => { await new Promise(resolve => setTimeout(resolve, 200)); await parseGraphQLSchema.load(); expect(parseClasses).not.toBe(parseGraphQLSchema.parseClasses); - expect(parseClassesString).not.toBe( - parseGraphQLSchema.parseClassesString - ); + expect(parseClassesString).not.toBe(parseGraphQLSchema.parseClassesString); expect(parseClassTypes).not.toBe(parseGraphQLSchema.parseClassTypes); expect(graphQLSchema).not.toBe(parseGraphQLSchema.graphQLSchema); expect(graphQLTypes).not.toBe(parseGraphQLSchema.graphQLTypes); expect(graphQLQueries).not.toBe(parseGraphQLSchema.graphQLQueries); expect(graphQLMutations).not.toBe(parseGraphQLSchema.graphQLMutations); - expect(graphQLSubscriptions).not.toBe( - parseGraphQLSchema.graphQLSubscriptions - ); + expect(graphQLSubscriptions).not.toBe(parseGraphQLSchema.graphQLSubscriptions); }); }); @@ -152,9 +144,7 @@ describe('ParseGraphQLSchema', () => { expect(parseGraphQLSchema.addGraphQLType(type)).toBe(type); expect(parseGraphQLSchema.graphQLTypes).toContain(type); expect( - parseGraphQLSchema.addGraphQLType( - new GraphQLObjectType({ name: 'SomeClass' }) - ) + parseGraphQLSchema.addGraphQLType(new GraphQLObjectType({ name: 'SomeClass' })) ).toBeUndefined(); expect(logged).toBeTruthy(); }); @@ -175,10 +165,7 @@ describe('ParseGraphQLSchema', () => { expect(parseGraphQLSchema.addGraphQLType(type, true)).toBe(type); expect(parseGraphQLSchema.graphQLTypes).toContain(type); expect(() => - parseGraphQLSchema.addGraphQLType( - new GraphQLObjectType({ name: 'SomeClass' }), - true - ) + parseGraphQLSchema.addGraphQLType(new GraphQLObjectType({ name: 'SomeClass' }), true) ).toThrowError( 'Type SomeClass could not be added to the auto schema because it collided with an existing type.' ); @@ -201,9 +188,7 @@ describe('ParseGraphQLSchema', () => { }); await parseGraphQLSchema.load(); expect( - parseGraphQLSchema.addGraphQLType( - new GraphQLObjectType({ name: 'String' }) - ) + parseGraphQLSchema.addGraphQLType(new GraphQLObjectType({ name: 'String' })) ).toBeUndefined(); expect(logged).toBeTruthy(); }); @@ -244,13 +229,9 @@ describe('ParseGraphQLSchema', () => { }); await parseGraphQLSchema.load(); const field = {}; - expect(parseGraphQLSchema.addGraphQLQuery('someClasses', field)).toBe( - field - ); + expect(parseGraphQLSchema.addGraphQLQuery('someClasses', field)).toBe(field); expect(parseGraphQLSchema.graphQLQueries['someClasses']).toBe(field); - expect( - parseGraphQLSchema.addGraphQLQuery('someClasses', {}) - ).toBeUndefined(); + expect(parseGraphQLSchema.addGraphQLQuery('someClasses', {})).toBeUndefined(); expect(logged).toBeTruthy(); }); @@ -267,13 +248,9 @@ describe('ParseGraphQLSchema', () => { }); await parseGraphQLSchema.load(); const field = {}; - expect(parseGraphQLSchema.addGraphQLQuery('someClasses', field)).toBe( - field - ); + expect(parseGraphQLSchema.addGraphQLQuery('someClasses', field)).toBe(field); expect(parseGraphQLSchema.graphQLQueries['someClasses']).toBe(field); - expect(() => - parseGraphQLSchema.addGraphQLQuery('someClasses', {}, true) - ).toThrowError( + expect(() => parseGraphQLSchema.addGraphQLQuery('someClasses', {}, true)).toThrowError( 'Query someClasses could not be added to the auto schema because it collided with an existing field.' ); }); @@ -312,9 +289,7 @@ describe('ParseGraphQLSchema', () => { await parseGraphQLSchema.load(); delete parseGraphQLSchema.graphQLQueries.viewer; const field = {}; - expect( - parseGraphQLSchema.addGraphQLQuery('viewer', field, true, true) - ).toBe(field); + expect(parseGraphQLSchema.addGraphQLQuery('viewer', field, true, true)).toBe(field); expect(parseGraphQLSchema.graphQLQueries['viewer']).toBe(field); }); }); @@ -337,15 +312,9 @@ describe('ParseGraphQLSchema', () => { }); await parseGraphQLSchema.load(); const field = {}; - expect( - parseGraphQLSchema.addGraphQLMutation('createSomeClass', field) - ).toBe(field); - expect(parseGraphQLSchema.graphQLMutations['createSomeClass']).toBe( - field - ); - expect( - parseGraphQLSchema.addGraphQLMutation('createSomeClass', {}) - ).toBeUndefined(); + expect(parseGraphQLSchema.addGraphQLMutation('createSomeClass', field)).toBe(field); + expect(parseGraphQLSchema.graphQLMutations['createSomeClass']).toBe(field); + expect(parseGraphQLSchema.addGraphQLMutation('createSomeClass', {})).toBeUndefined(); expect(logged).toBeTruthy(); }); @@ -362,15 +331,9 @@ describe('ParseGraphQLSchema', () => { }); await parseGraphQLSchema.load(); const field = {}; - expect( - parseGraphQLSchema.addGraphQLMutation('createSomeClass', field) - ).toBe(field); - expect(parseGraphQLSchema.graphQLMutations['createSomeClass']).toBe( - field - ); - expect(() => - parseGraphQLSchema.addGraphQLMutation('createSomeClass', {}, true) - ).toThrowError( + expect(parseGraphQLSchema.addGraphQLMutation('createSomeClass', field)).toBe(field); + expect(parseGraphQLSchema.graphQLMutations['createSomeClass']).toBe(field); + expect(() => parseGraphQLSchema.addGraphQLMutation('createSomeClass', {}, true)).toThrowError( 'Mutation createSomeClass could not be added to the auto schema because it collided with an existing field.' ); }); @@ -391,9 +354,7 @@ describe('ParseGraphQLSchema', () => { appId, }); await parseGraphQLSchema.load(); - expect( - parseGraphQLSchema.addGraphQLMutation('signUp', {}) - ).toBeUndefined(); + expect(parseGraphQLSchema.addGraphQLMutation('signUp', {})).toBeUndefined(); expect(logged).toBeTruthy(); }); @@ -411,9 +372,7 @@ describe('ParseGraphQLSchema', () => { await parseGraphQLSchema.load(); delete parseGraphQLSchema.graphQLMutations.signUp; const field = {}; - expect( - parseGraphQLSchema.addGraphQLMutation('signUp', field, true, true) - ).toBe(field); + expect(parseGraphQLSchema.addGraphQLMutation('signUp', field, true, true)).toBe(field); expect(parseGraphQLSchema.graphQLMutations['signUp']).toBe(field); }); }); @@ -483,17 +442,11 @@ describe('ParseGraphQLSchema', () => { const mutations2 = parseGraphQLSchema.graphQLMutations; expect(schema1).not.toBe(schema2); expect(types1).not.toBe(types2); - expect(types1.map(type => type.name).sort()).toEqual( - types2.map(type => type.name).sort() - ); + expect(types1.map(type => type.name).sort()).toEqual(types2.map(type => type.name).sort()); expect(queries1).not.toBe(queries2); - expect(Object.keys(queries1).sort()).toEqual( - Object.keys(queries2).sort() - ); + expect(Object.keys(queries1).sort()).toEqual(Object.keys(queries2).sort()); expect(mutations1).not.toBe(mutations2); - expect(Object.keys(mutations1).sort()).toEqual( - Object.keys(mutations2).sort() - ); + expect(Object.keys(mutations1).sort()).toEqual(Object.keys(mutations2).sort()); }); it('should not generate duplicate types when colliding the same name', async () => { @@ -519,17 +472,11 @@ describe('ParseGraphQLSchema', () => { const mutations2 = parseGraphQLSchema.graphQLMutations; expect(schema1).not.toBe(schema2); expect(types1).not.toBe(types2); - expect(types1.map(type => type.name).sort()).toEqual( - types2.map(type => type.name).sort() - ); + expect(types1.map(type => type.name).sort()).toEqual(types2.map(type => type.name).sort()); expect(queries1).not.toBe(queries2); - expect(Object.keys(queries1).sort()).toEqual( - Object.keys(queries2).sort() - ); + expect(Object.keys(queries1).sort()).toEqual(Object.keys(queries2).sort()); expect(mutations1).not.toBe(mutations2); - expect(Object.keys(mutations1).sort()).toEqual( - Object.keys(mutations2).sort() - ); + expect(Object.keys(mutations1).sort()).toEqual(Object.keys(mutations2).sort()); }); it('should not generate duplicate queries when query name collide', async () => { @@ -553,14 +500,10 @@ describe('ParseGraphQLSchema', () => { const mutations2 = parseGraphQLSchema.graphQLMutations; expect(schema1).not.toBe(schema2); expect(queries1).not.toBe(queries2); - expect(Object.keys(queries1).sort()).toEqual( - Object.keys(queries2).sort() - ); + expect(Object.keys(queries1).sort()).toEqual(Object.keys(queries2).sort()); expect(mutations1).not.toBe(mutations2); expect( - Object.keys(mutations1) - .concat('createCars', 'updateCars', 'deleteCars') - .sort() + Object.keys(mutations1).concat('createCars', 'updateCars', 'deleteCars').sort() ).toEqual(Object.keys(mutations2).sort()); }); }); diff --git a/spec/ParseGraphQLServer.spec.js b/spec/ParseGraphQLServer.spec.js index bac3e418..5bba32f2 100644 --- a/spec/ParseGraphQLServer.spec.js +++ b/spec/ParseGraphQLServer.spec.js @@ -32,12 +32,7 @@ const ReadPreference = require('mongodb').ReadPreference; const { v4: uuidv4 } = require('uuid'); function handleError(e) { - if ( - e && - e.networkError && - e.networkError.result && - e.networkError.result.errors - ) { + if (e && e.networkError && e.networkError.result && e.networkError.result.errors) { fail(e.networkError.result.errors); } else { fail(e); @@ -59,9 +54,7 @@ describe('ParseGraphQLServer', () => { describe('constructor', () => { it('should require a parseServer instance', () => { - expect(() => new ParseGraphQLServer()).toThrow( - 'You must provide a parseServer instance!' - ); + expect(() => new ParseGraphQLServer()).toThrow('You must provide a parseServer instance!'); }); it('should require config.graphQLPath', () => { @@ -97,9 +90,7 @@ describe('ParseGraphQLServer', () => { const parseGraphQLServer = new ParseGraphQLServer(parseServer, { graphQLPath: 'graphql', }); - expect(parseGraphQLServer.parseGraphQLSchema.log.adapter).toBe( - loggerAdapter - ); + expect(parseGraphQLServer.parseGraphQLSchema.log.adapter).toBe(loggerAdapter); }); }); @@ -112,9 +103,7 @@ describe('ParseGraphQLServer', () => { it("should return schema and context with req's info, config and auth", async () => { const options = await parseGraphQLServer._getGraphQLOptions(req); - expect(options.schema).toEqual( - parseGraphQLServer.parseGraphQLSchema.graphQLSchema - ); + expect(options.schema).toEqual(parseGraphQLServer.parseGraphQLSchema.graphQLSchema); expect(options.context.info).toEqual(req.info); expect(options.context.config).toEqual(req.config); expect(options.context.auth).toEqual(req.auth); @@ -124,30 +113,18 @@ describe('ParseGraphQLServer', () => { const originalLoad = parseGraphQLServer.parseGraphQLSchema.load; let counter = 0; parseGraphQLServer.parseGraphQLSchema.load = () => ++counter; - expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual( - 1 - ); - expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual( - 2 - ); - expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual( - 3 - ); + expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual(1); + expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual(2); + expect((await parseGraphQLServer._getGraphQLOptions(req)).schema).toEqual(3); parseGraphQLServer.parseGraphQLSchema.load = originalLoad; }); }); describe('_transformMaxUploadSizeToBytes', () => { it('should transform to bytes', () => { - expect(parseGraphQLServer._transformMaxUploadSizeToBytes('20mb')).toBe( - 20971520 - ); - expect(parseGraphQLServer._transformMaxUploadSizeToBytes('333Gb')).toBe( - 357556027392 - ); - expect( - parseGraphQLServer._transformMaxUploadSizeToBytes('123456KB') - ).toBe(126418944); + expect(parseGraphQLServer._transformMaxUploadSizeToBytes('20mb')).toBe(20971520); + expect(parseGraphQLServer._transformMaxUploadSizeToBytes('333Gb')).toBe(357556027392); + expect(parseGraphQLServer._transformMaxUploadSizeToBytes('123456KB')).toBe(126418944); }); }); @@ -159,9 +136,7 @@ describe('ParseGraphQLServer', () => { expect(() => parseGraphQLServer.applyGraphQL({})).toThrow( 'You must provide an Express.js app instance!' ); - expect(() => - parseGraphQLServer.applyGraphQL(new express()) - ).not.toThrow(); + expect(() => parseGraphQLServer.applyGraphQL(new express())).not.toThrow(); }); it('should apply middlewares at config.graphQLPath', () => { @@ -188,9 +163,7 @@ describe('ParseGraphQLServer', () => { expect(() => parseGraphQLServer.applyPlayground({})).toThrow( 'You must provide an Express.js app instance!' ); - expect(() => - parseGraphQLServer.applyPlayground(new express()) - ).not.toThrow(); + expect(() => parseGraphQLServer.applyPlayground(new express())).not.toThrow(); }); it('should require initialization with config.playgroundPath', () => { @@ -224,9 +197,7 @@ describe('ParseGraphQLServer', () => { new ParseGraphQLServer(parseServer, { graphQLPath: 'graphql', }).createSubscriptions({}) - ).toThrow( - 'You must provide a config.subscriptionsPath to createSubscriptions!' - ); + ).toThrow('You must provide a config.subscriptionsPath to createSubscriptions!'); }); }); @@ -255,9 +226,9 @@ describe('ParseGraphQLServer', () => { throw new Error('Network request failed'); }, }; - await expectAsync( - parseGraphQLServer.setGraphQLConfig({}) - ).toBeRejectedWith(new Error('Network request failed')); + await expectAsync(parseGraphQLServer.setGraphQLConfig({})).toBeRejectedWith( + new Error('Network request failed') + ); }); it('should return the response from parseGraphQLController', async () => { parseGraphQLServer.parseGraphQLController = { @@ -265,9 +236,9 @@ describe('ParseGraphQLServer', () => { return { response: { result: true } }; }, }; - await expectAsync( - parseGraphQLServer.setGraphQLConfig({}) - ).toBeResolvedTo({ response: { result: true } }); + await expectAsync(parseGraphQLServer.setGraphQLConfig({})).toBeResolvedTo({ + response: { result: true }, + }); }); }); @@ -374,10 +345,7 @@ describe('ParseGraphQLServer', () => { {} ); } catch (err) { - if ( - !(err instanceof Parse.Error) || - err.message !== 'Class GraphQLClass already exists.' - ) { + if (!(err instanceof Parse.Error) || err.message !== 'Class GraphQLClass already exists.') { throw err; } } @@ -456,9 +424,7 @@ describe('ParseGraphQLServer', () => { link: split( ({ query }) => { const { kind, operation } = getMainDefinition(query); - return ( - kind === 'OperationDefinition' && operation === 'subscription' - ); + return kind === 'OperationDefinition' && operation === 'subscription'; }, wsLink, httpLink @@ -641,10 +607,7 @@ describe('ParseGraphQLServer', () => { }) ).data['__type']; expect(fileType.kind).toEqual('OBJECT'); - expect(fileType.fields.map(field => field.name).sort()).toEqual([ - 'name', - 'url', - ]); + expect(fileType.fields.map(field => field.name).sort()).toEqual(['name', 'url']); }); it('should have Class interface type', async () => { @@ -687,9 +650,7 @@ describe('ParseGraphQLServer', () => { }) ).data['__type']; expect(readPreferenceType.kind).toEqual('ENUM'); - expect( - readPreferenceType.enumValues.map(value => value.name).sort() - ).toEqual([ + expect(readPreferenceType.enumValues.map(value => value.name).sort()).toEqual([ 'NEAREST', 'PRIMARY', 'PRIMARY_PREFERRED', @@ -731,16 +692,10 @@ describe('ParseGraphQLServer', () => { }) ).data['__schema'].types.map(type => type.name); - const expectedTypes = [ - 'ParseObject', - 'Date', - 'FileInfo', - 'ReadPreference', - 'Upload', - ]; - expect( - expectedTypes.every(type => schemaTypes.indexOf(type) !== -1) - ).toBeTruthy(JSON.stringify(schemaTypes.types)); + const expectedTypes = ['ParseObject', 'Date', 'FileInfo', 'ReadPreference', 'Upload']; + expect(expectedTypes.every(type => schemaTypes.indexOf(type) !== -1)).toBeTruthy( + JSON.stringify(schemaTypes.types) + ); }); }); @@ -845,10 +800,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(createFilePayloadFields).toEqual([ - 'clientMutationId', - 'fileInfo', - ]); + expect(createFilePayloadFields).toEqual(['clientMutationId', 'fileInfo']); }); it('should have clientMutationId in call function input', async () => { @@ -870,11 +822,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(callFunctionInputFields).toEqual([ - 'clientMutationId', - 'functionName', - 'params', - ]); + expect(callFunctionInputFields).toEqual(['clientMutationId', 'functionName', 'params']); }); it('should have clientMutationId in call function payload', async () => { @@ -896,10 +844,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(callFunctionPayloadFields).toEqual([ - 'clientMutationId', - 'result', - ]); + expect(callFunctionPayloadFields).toEqual(['clientMutationId', 'result']); }); it('should have clientMutationId in sign up mutation input', async () => { @@ -959,11 +904,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(inputFields).toEqual([ - 'clientMutationId', - 'password', - 'username', - ]); + expect(inputFields).toEqual(['clientMutationId', 'password', 'username']); }); it('should have clientMutationId in log in mutation payload', async () => { @@ -1043,11 +984,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(inputFields).toEqual([ - 'clientMutationId', - 'name', - 'schemaFields', - ]); + expect(inputFields).toEqual(['clientMutationId', 'name', 'schemaFields']); }); it('should have clientMutationId in createClass mutation payload', async () => { @@ -1087,11 +1024,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(inputFields).toEqual([ - 'clientMutationId', - 'name', - 'schemaFields', - ]); + expect(inputFields).toEqual(['clientMutationId', 'name', 'schemaFields']); }); it('should have clientMutationId in updateClass mutation payload', async () => { @@ -1176,10 +1109,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(createObjectInputFields).toEqual([ - 'clientMutationId', - 'fields', - ]); + expect(createObjectInputFields).toEqual(['clientMutationId', 'fields']); }); it('should have clientMutationId in custom create object mutation payload', async () => { @@ -1204,10 +1134,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(createObjectPayloadFields).toEqual([ - 'clientMutationId', - 'someClass', - ]); + expect(createObjectPayloadFields).toEqual(['clientMutationId', 'someClass']); }); it('should have clientMutationId in custom update object mutation input', async () => { @@ -1232,11 +1159,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(createObjectInputFields).toEqual([ - 'clientMutationId', - 'fields', - 'id', - ]); + expect(createObjectInputFields).toEqual(['clientMutationId', 'fields', 'id']); }); it('should have clientMutationId in custom update object mutation payload', async () => { @@ -1261,10 +1184,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(createObjectPayloadFields).toEqual([ - 'clientMutationId', - 'someClass', - ]); + expect(createObjectPayloadFields).toEqual(['clientMutationId', 'someClass']); }); it('should have clientMutationId in custom delete object mutation input', async () => { @@ -1314,10 +1234,7 @@ describe('ParseGraphQLServer', () => { .map(field => field.name) .sort(); - expect(createObjectPayloadFields).toEqual([ - 'clientMutationId', - 'someClass', - ]); + expect(createObjectPayloadFields).toEqual(['clientMutationId', 'someClass']); }); }); @@ -1351,9 +1268,9 @@ describe('ParseGraphQLServer', () => { 'CreateUserFieldsInput', 'UpdateUserFieldsInput', ]; - expect( - expectedTypes.every(type => schemaTypes.indexOf(type) !== -1) - ).toBeTruthy(JSON.stringify(schemaTypes)); + expect(expectedTypes.every(type => schemaTypes.indexOf(type) !== -1)).toBeTruthy( + JSON.stringify(schemaTypes) + ); }); it('should ArrayResult contains all types', async () => { @@ -1799,9 +1716,7 @@ describe('ParseGraphQLServer', () => { apolloClient.query({ query: gql` mutation InvalidCreateSuperCar { - createSuperCar( - input: { fields: { engine: "diesel", mileage: 1000 } } - ) { + createSuperCar(input: { fields: { engine: "diesel", mileage: 1000 } }) { superCar { id } @@ -1815,9 +1730,7 @@ describe('ParseGraphQLServer', () => { query: gql` mutation ValidCreateSuperCar { createSuperCar( - input: { - fields: { engine: "diesel", doors: 5, price: "£10000" } - } + input: { fields: { engine: "diesel", doors: 5, price: "£10000" } } ) { superCar { id @@ -1834,9 +1747,7 @@ describe('ParseGraphQLServer', () => { apolloClient.query({ query: gql` mutation InvalidUpdateSuperCar($id: ID!) { - updateSuperCar( - input: { id: $id, fields: { engine: "petrol" } } - ) { + updateSuperCar(input: { id: $id, fields: { engine: "petrol" } }) { clientMutationId } } @@ -1851,9 +1762,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.query({ query: gql` mutation ValidUpdateSuperCar($id: ID!) { - updateSuperCar( - input: { id: $id, fields: { mileage: 2000 } } - ) { + updateSuperCar(input: { id: $id, fields: { mileage: 2000 } }) { clientMutationId } } @@ -1893,15 +1802,9 @@ describe('ParseGraphQLServer', () => { } `, }); - expect( - __type.inputFields.find(o => o.name === 'price').type.kind - ).toEqual('SCALAR'); - expect( - __type.inputFields.find(o => o.name === 'engine').type.kind - ).toEqual('NON_NULL'); - expect( - __type.inputFields.find(o => o.name === 'doors').type.kind - ).toEqual('NON_NULL'); + expect(__type.inputFields.find(o => o.name === 'price').type.kind).toEqual('SCALAR'); + expect(__type.inputFields.find(o => o.name === 'engine').type.kind).toEqual('NON_NULL'); + expect(__type.inputFields.find(o => o.name === 'doors').type.kind).toEqual('NON_NULL'); const { data: { __type: __type2 }, @@ -1919,15 +1822,9 @@ describe('ParseGraphQLServer', () => { } `, }); - expect( - __type2.fields.find(o => o.name === 'price').type.kind - ).toEqual('SCALAR'); - expect( - __type2.fields.find(o => o.name === 'engine').type.kind - ).toEqual('NON_NULL'); - expect( - __type2.fields.find(o => o.name === 'doors').type.kind - ).toEqual('NON_NULL'); + expect(__type2.fields.find(o => o.name === 'price').type.kind).toEqual('SCALAR'); + expect(__type2.fields.find(o => o.name === 'engine').type.kind).toEqual('NON_NULL'); + expect(__type2.fields.find(o => o.name === 'doors').type.kind).toEqual('NON_NULL'); }); it('should only allow the supplied output fields for a class', async () => { @@ -2086,11 +1983,7 @@ describe('ParseGraphQLServer', () => { apolloClient.query({ query: gql` query FindSuperCar { - superCars( - where: { - insuranceCertificate: { equalTo: "private-file.pdf" } - } - ) { + superCars(where: { insuranceCertificate: { equalTo: "private-file.pdf" } }) { count } } @@ -2358,12 +2251,8 @@ describe('ParseGraphQLServer', () => { `, }); - expect(findResult.data.someClasses.edges[0].node.objectId).toBe( - obj1.id - ); - expect(findResult.data.someClasses.edges[1].node.objectId).toBe( - obj2.id - ); + expect(findResult.data.someClasses.edges[0].node.objectId).toBe(obj1.id); + expect(findResult.data.someClasses.edges[1].node.objectId).toBe(obj2.id); const nodeResult = await apolloClient.query({ query: gql` @@ -2390,14 +2279,10 @@ describe('ParseGraphQLServer', () => { }, }); - expect(nodeResult.data.node1.id).toBe( - findResult.data.someClasses.edges[0].node.id - ); + expect(nodeResult.data.node1.id).toBe(findResult.data.someClasses.edges[0].node.id); expect(nodeResult.data.node1.objectId).toBe(obj1.id); expect(nodeResult.data.node1.someField).toBe('some value 1'); - expect(nodeResult.data.node2.id).toBe( - findResult.data.someClasses.edges[1].node.id - ); + expect(nodeResult.data.node2.id).toBe(findResult.data.someClasses.edges[1].node.id); expect(nodeResult.data.node2.objectId).toBe(obj2.id); expect(nodeResult.data.node2.someField).toBe('some value 2'); }); @@ -2422,16 +2307,10 @@ describe('ParseGraphQLServer', () => { addStrings: [{ name: "stringField" }] addArrays: [{ name: "arrayField" }] addPointers: [ - { - name: "pointerField" - targetClassName: "SecondaryObject" - } + { name: "pointerField", targetClassName: "SecondaryObject" } ] addRelations: [ - { - name: "relationField" - targetClassName: "SecondaryObject" - } + { name: "relationField", targetClassName: "SecondaryObject" } ] } } @@ -2526,10 +2405,7 @@ describe('ParseGraphQLServer', () => { $id6: ID! ) { secondaryObject1: updateSecondaryObject( - input: { - id: $id1 - fields: { someField: "some value 11" } - } + input: { id: $id1, fields: { someField: "some value 11" } } ) { secondaryObject { id @@ -2538,10 +2414,7 @@ describe('ParseGraphQLServer', () => { } } secondaryObject2: updateSecondaryObject( - input: { - id: $id2 - fields: { someField: "some value 22" } - } + input: { id: $id2, fields: { someField: "some value 22" } } ) { secondaryObject { id @@ -2549,10 +2422,7 @@ describe('ParseGraphQLServer', () => { } } secondaryObject3: updateSecondaryObject( - input: { - id: $id3 - fields: { someField: "some value 33" } - } + input: { id: $id3, fields: { someField: "some value 33" } } ) { secondaryObject { objectId @@ -2560,10 +2430,7 @@ describe('ParseGraphQLServer', () => { } } secondaryObject4: updateSecondaryObject( - input: { - id: $id4 - fields: { someField: "some value 44" } - } + input: { id: $id4, fields: { someField: "some value 44" } } ) { secondaryObject { id @@ -2571,20 +2438,14 @@ describe('ParseGraphQLServer', () => { } } secondaryObject5: updateSecondaryObject( - input: { - id: $id5 - fields: { someField: "some value 55" } - } + input: { id: $id5, fields: { someField: "some value 55" } } ) { secondaryObject { id } } secondaryObject6: updateSecondaryObject( - input: { - id: $id6 - fields: { someField: "some value 66" } - } + input: { id: $id6, fields: { someField: "some value 66" } } ) { secondaryObject { objectId @@ -2593,24 +2454,12 @@ describe('ParseGraphQLServer', () => { } `, variables: { - id1: - createSecondaryObjectsResult.data.secondaryObject1 - .secondaryObject.id, - id2: - createSecondaryObjectsResult.data.secondaryObject2 - .secondaryObject.id, - id3: - createSecondaryObjectsResult.data.secondaryObject3 - .secondaryObject.objectId, - id4: - createSecondaryObjectsResult.data.secondaryObject4 - .secondaryObject.objectId, - id5: - createSecondaryObjectsResult.data.secondaryObject5 - .secondaryObject.id, - id6: - createSecondaryObjectsResult.data.secondaryObject6 - .secondaryObject.objectId, + id1: createSecondaryObjectsResult.data.secondaryObject1.secondaryObject.id, + id2: createSecondaryObjectsResult.data.secondaryObject2.secondaryObject.id, + id3: createSecondaryObjectsResult.data.secondaryObject3.secondaryObject.objectId, + id4: createSecondaryObjectsResult.data.secondaryObject4.secondaryObject.objectId, + id5: createSecondaryObjectsResult.data.secondaryObject5.secondaryObject.id, + id6: createSecondaryObjectsResult.data.secondaryObject6.secondaryObject.objectId, }, context: { headers: { @@ -2621,39 +2470,26 @@ describe('ParseGraphQLServer', () => { const deleteSecondaryObjectsResult = await apolloClient.mutate({ mutation: gql` - mutation DeleteSecondaryObjects( - $id1: ID! - $id3: ID! - $id5: ID! - $id6: ID! - ) { - secondaryObject1: deleteSecondaryObject( - input: { id: $id1 } - ) { + mutation DeleteSecondaryObjects($id1: ID!, $id3: ID!, $id5: ID!, $id6: ID!) { + secondaryObject1: deleteSecondaryObject(input: { id: $id1 }) { secondaryObject { id objectId someField } } - secondaryObject3: deleteSecondaryObject( - input: { id: $id3 } - ) { + secondaryObject3: deleteSecondaryObject(input: { id: $id3 }) { secondaryObject { objectId someField } } - secondaryObject5: deleteSecondaryObject( - input: { id: $id5 } - ) { + secondaryObject5: deleteSecondaryObject(input: { id: $id5 }) { secondaryObject { id } } - secondaryObject6: deleteSecondaryObject( - input: { id: $id6 } - ) { + secondaryObject6: deleteSecondaryObject(input: { id: $id6 }) { secondaryObject { objectId } @@ -2661,18 +2497,10 @@ describe('ParseGraphQLServer', () => { } `, variables: { - id1: - updateSecondaryObjectsResult.data.secondaryObject1 - .secondaryObject.id, - id3: - updateSecondaryObjectsResult.data.secondaryObject3 - .secondaryObject.objectId, - id5: - updateSecondaryObjectsResult.data.secondaryObject5 - .secondaryObject.id, - id6: - updateSecondaryObjectsResult.data.secondaryObject6 - .secondaryObject.objectId, + id1: updateSecondaryObjectsResult.data.secondaryObject1.secondaryObject.id, + id3: updateSecondaryObjectsResult.data.secondaryObject3.secondaryObject.objectId, + id5: updateSecondaryObjectsResult.data.secondaryObject5.secondaryObject.id, + id6: updateSecondaryObjectsResult.data.secondaryObject6.secondaryObject.objectId, }, context: { headers: { @@ -2696,12 +2524,8 @@ describe('ParseGraphQLServer', () => { } `, variables: { - id2: - updateSecondaryObjectsResult.data.secondaryObject2 - .secondaryObject.id, - id4: - updateSecondaryObjectsResult.data.secondaryObject4 - .secondaryObject.objectId, + id2: updateSecondaryObjectsResult.data.secondaryObject2.secondaryObject.id, + id4: updateSecondaryObjectsResult.data.secondaryObject4.secondaryObject.objectId, }, context: { headers: { @@ -2726,12 +2550,7 @@ describe('ParseGraphQLServer', () => { { OR: [ { id: { equalTo: $id2 } } - { - AND: [ - { id: { equalTo: $id4 } } - { objectId: { equalTo: $id4 } } - ] - } + { AND: [{ id: { equalTo: $id4 } }, { objectId: { equalTo: $id4 } }] } ] } { id: { notEqualTo: $id1 } } @@ -2755,20 +2574,12 @@ describe('ParseGraphQLServer', () => { } `, variables: { - id1: - deleteSecondaryObjectsResult.data.secondaryObject1 - .secondaryObject.objectId, + id1: deleteSecondaryObjectsResult.data.secondaryObject1.secondaryObject.objectId, id2: getSecondaryObjectsResult.data.secondaryObject2.id, - id3: - deleteSecondaryObjectsResult.data.secondaryObject3 - .secondaryObject.objectId, + id3: deleteSecondaryObjectsResult.data.secondaryObject3.secondaryObject.objectId, id4: getSecondaryObjectsResult.data.secondaryObject4.objectId, - id5: - deleteSecondaryObjectsResult.data.secondaryObject5 - .secondaryObject.id, - id6: - deleteSecondaryObjectsResult.data.secondaryObject6 - .secondaryObject.objectId, + id5: deleteSecondaryObjectsResult.data.secondaryObject5.secondaryObject.id, + id6: deleteSecondaryObjectsResult.data.secondaryObject6.secondaryObject.objectId, }, context: { headers: { @@ -2777,27 +2588,19 @@ describe('ParseGraphQLServer', () => { }, }); - expect( - findSecondaryObjectsResult.data.secondaryObjects.count - ).toEqual(2); + expect(findSecondaryObjectsResult.data.secondaryObjects.count).toEqual(2); expect( findSecondaryObjectsResult.data.secondaryObjects.edges .map(value => value.node.someField) .sort() ).toEqual(['some value 22', 'some value 44']); expect( - findSecondaryObjectsResult.data.secondaryObjects.edges[0].node - .id - ).toBeLessThan( - findSecondaryObjectsResult.data.secondaryObjects.edges[1].node - .id - ); + findSecondaryObjectsResult.data.secondaryObjects.edges[0].node.id + ).toBeLessThan(findSecondaryObjectsResult.data.secondaryObjects.edges[1].node.id); expect( - findSecondaryObjectsResult.data.secondaryObjects.edges[0].node - .objectId + findSecondaryObjectsResult.data.secondaryObjects.edges[0].node.objectId ).toBeLessThan( - findSecondaryObjectsResult.data.secondaryObjects.edges[1].node - .objectId + findSecondaryObjectsResult.data.secondaryObjects.edges[1].node.objectId ); const createPrimaryObjectResult = await apolloClient.mutate({ @@ -2813,9 +2616,7 @@ describe('ParseGraphQLServer', () => { stringField: "some value" arrayField: [1, "abc", $pointer] pointerField: { link: $secondaryObject2 } - relationField: { - add: [$secondaryObject2, $secondaryObject4] - } + relationField: { add: [$secondaryObject2, $secondaryObject4] } } } ) { @@ -2852,13 +2653,10 @@ describe('ParseGraphQLServer', () => { pointer: { __type: 'Pointer', className: 'SecondaryObject', - objectId: - getSecondaryObjectsResult.data.secondaryObject4.objectId, + objectId: getSecondaryObjectsResult.data.secondaryObject4.objectId, }, - secondaryObject2: - getSecondaryObjectsResult.data.secondaryObject2.id, - secondaryObject4: - getSecondaryObjectsResult.data.secondaryObject4.objectId, + secondaryObject2: getSecondaryObjectsResult.data.secondaryObject2.id, + secondaryObject4: getSecondaryObjectsResult.data.secondaryObject4.objectId, }, context: { headers: { @@ -2879,9 +2677,7 @@ describe('ParseGraphQLServer', () => { id: $id fields: { pointerField: { link: $secondaryObject4 } - relationField: { - remove: [$secondaryObject2, $secondaryObject4] - } + relationField: { remove: [$secondaryObject2, $secondaryObject4] } } } ) { @@ -2915,13 +2711,9 @@ describe('ParseGraphQLServer', () => { } `, variables: { - id: - createPrimaryObjectResult.data.createPrimaryObject - .primaryObject.id, - secondaryObject2: - getSecondaryObjectsResult.data.secondaryObject2.id, - secondaryObject4: - getSecondaryObjectsResult.data.secondaryObject4.objectId, + id: createPrimaryObjectResult.data.createPrimaryObject.primaryObject.id, + secondaryObject2: getSecondaryObjectsResult.data.secondaryObject2.id, + secondaryObject4: getSecondaryObjectsResult.data.secondaryObject4.objectId, }, context: { headers: { @@ -2931,20 +2723,18 @@ describe('ParseGraphQLServer', () => { }); expect( - createPrimaryObjectResult.data.createPrimaryObject.primaryObject - .stringField + createPrimaryObjectResult.data.createPrimaryObject.primaryObject.stringField ).toEqual('some value'); expect( - createPrimaryObjectResult.data.createPrimaryObject.primaryObject - .arrayField + createPrimaryObjectResult.data.createPrimaryObject.primaryObject.arrayField ).toEqual([ { __typename: 'Element', value: 1 }, { __typename: 'Element', value: 'abc' }, { __typename: 'SecondaryObject', someField: 'some value 44' }, ]); expect( - createPrimaryObjectResult.data.createPrimaryObject.primaryObject - .pointerField.someField + createPrimaryObjectResult.data.createPrimaryObject.primaryObject.pointerField + .someField ).toEqual('some value 22'); expect( createPrimaryObjectResult.data.createPrimaryObject.primaryObject.relationField.edges @@ -2952,24 +2742,21 @@ describe('ParseGraphQLServer', () => { .sort() ).toEqual(['some value 22', 'some value 44']); expect( - updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject - .stringField + updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject.stringField ).toEqual('some value'); expect( - updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject - .arrayField + updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject.arrayField ).toEqual([ { __typename: 'Element', value: 1 }, { __typename: 'Element', value: 'abc' }, { __typename: 'SecondaryObject', someField: 'some value 44' }, ]); expect( - updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject - .pointerField.someField + updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject.pointerField + .someField ).toEqual('some value 44'); expect( - updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject - .relationField.edges + updatePrimaryObjectResult.data.updatePrimaryObject.primaryObject.relationField.edges ).toEqual([]); } catch (e) { handleError(e); @@ -2984,9 +2771,7 @@ describe('ParseGraphQLServer', () => { const result = await apolloClient.mutate({ mutation: gql` mutation { - class1: createClass( - input: { name: "Class1", clientMutationId: "cmid1" } - ) { + class1: createClass(input: { name: "Class1", clientMutationId: "cmid1" }) { clientMutationId class { name @@ -2997,11 +2782,7 @@ describe('ParseGraphQLServer', () => { } } class2: createClass( - input: { - name: "Class2" - schemaFields: null - clientMutationId: "cmid2" - } + input: { name: "Class2", schemaFields: null, clientMutationId: "cmid2" } ) { clientMutationId class { @@ -3013,11 +2794,7 @@ describe('ParseGraphQLServer', () => { } } class3: createClass( - input: { - name: "Class3" - schemaFields: {} - clientMutationId: "cmid3" - } + input: { name: "Class3", schemaFields: {}, clientMutationId: "cmid3" } ) { clientMutationId class { @@ -3190,9 +2967,9 @@ describe('ParseGraphQLServer', () => { clientMutationId: result.data[fieldName].clientMutationId, class: { name: result.data[fieldName].class.name, - schemaFields: result.data[ - fieldName - ].class.schemaFields.sort((a, b) => (a.name > b.name ? 1 : -1)), + schemaFields: result.data[fieldName].class.schemaFields.sort((a, b) => + a.name > b.name ? 1 : -1 + ), __typename: result.data[fieldName].class.__typename, }, __typename: result.data[fieldName].__typename, @@ -3480,12 +3257,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.OPERATION_FORBIDDEN - ); - expect(e.graphQLErrors[0].message).toEqual( - 'unauthorized: master key is required' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); + expect(e.graphQLErrors[0].message).toEqual('unauthorized: master key is required'); } }); @@ -3515,12 +3288,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.INVALID_KEY_NAME - ); - expect(e.graphQLErrors[0].message).toEqual( - 'Duplicated field name: someField' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.INVALID_KEY_NAME); + expect(e.graphQLErrors[0].message).toEqual('Duplicated field name: someField'); } }); @@ -3764,8 +3533,8 @@ describe('ParseGraphQLServer', () => { }, }, }); - getResult.data.class.schemaFields = getResult.data.class.schemaFields.sort( - (a, b) => (a.name > b.name ? 1 : -1) + getResult.data.class.schemaFields = getResult.data.class.schemaFields.sort((a, b) => + a.name > b.name ? 1 : -1 ); expect(getResult.data).toEqual({ class: { @@ -3858,12 +3627,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.OPERATION_FORBIDDEN - ); - expect(e.graphQLErrors[0].message).toEqual( - 'unauthorized: master key is required' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); + expect(e.graphQLErrors[0].message).toEqual('unauthorized: master key is required'); } }); @@ -3914,12 +3679,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.INVALID_KEY_NAME - ); - expect(e.graphQLErrors[0].message).toEqual( - 'Duplicated field name: someField' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.INVALID_KEY_NAME); + expect(e.graphQLErrors[0].message).toEqual('Duplicated field name: someField'); } }); @@ -3946,12 +3707,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.INVALID_CLASS_NAME - ); - expect(e.graphQLErrors[0].message).toEqual( - 'Class SomeInexistentClass does not exist.' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.INVALID_CLASS_NAME); + expect(e.graphQLErrors[0].message).toEqual('Class SomeInexistentClass does not exist.'); } }); @@ -4055,12 +3812,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.INVALID_CLASS_NAME - ); - expect(e.graphQLErrors[0].message).toEqual( - 'Class MyNewClass does not exist.' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.INVALID_CLASS_NAME); + expect(e.graphQLErrors[0].message).toEqual('Class MyNewClass does not exist.'); } } catch (e) { handleError(e); @@ -4099,12 +3852,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.OPERATION_FORBIDDEN - ); - expect(e.graphQLErrors[0].message).toEqual( - 'unauthorized: master key is required' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); + expect(e.graphQLErrors[0].message).toEqual('unauthorized: master key is required'); } }); @@ -4126,12 +3875,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.INVALID_CLASS_NAME - ); - expect(e.graphQLErrors[0].message).toEqual( - 'Class SomeInexistentClass does not exist.' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.INVALID_CLASS_NAME); + expect(e.graphQLErrors[0].message).toEqual('Class SomeInexistentClass does not exist.'); } }); @@ -4148,12 +3893,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.OPERATION_FORBIDDEN - ); - expect(e.graphQLErrors[0].message).toEqual( - 'unauthorized: master key is required' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); + expect(e.graphQLErrors[0].message).toEqual('unauthorized: master key is required'); } }); @@ -4170,12 +3911,8 @@ describe('ParseGraphQLServer', () => { }); fail('should fail'); } catch (e) { - expect(e.graphQLErrors[0].extensions.code).toEqual( - Parse.Error.OPERATION_FORBIDDEN - ); - expect(e.graphQLErrors[0].message).toEqual( - 'unauthorized: master key is required' - ); + expect(e.graphQLErrors[0].extensions.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); + expect(e.graphQLErrors[0].message).toEqual('unauthorized: master key is required'); } }); }); @@ -4214,82 +3951,69 @@ describe('ParseGraphQLServer', () => { expect(new Date(result.updatedAt)).toEqual(obj.updatedAt); }); - it_only_db('mongo')( - 'should return child objects in array fields', - async () => { - const obj1 = new Parse.Object('Customer'); - const obj2 = new Parse.Object('SomeClass'); - const obj3 = new Parse.Object('Customer'); + it_only_db('mongo')('should return child objects in array fields', async () => { + const obj1 = new Parse.Object('Customer'); + const obj2 = new Parse.Object('SomeClass'); + const obj3 = new Parse.Object('Customer'); - obj1.set('someCustomerField', 'imCustomerOne'); - const arrayField = [42.42, 42, 'string', true]; - obj1.set('arrayField', arrayField); - await obj1.save(); + obj1.set('someCustomerField', 'imCustomerOne'); + const arrayField = [42.42, 42, 'string', true]; + obj1.set('arrayField', arrayField); + await obj1.save(); - obj2.set('someClassField', 'imSomeClassTwo'); - await obj2.save(); + obj2.set('someClassField', 'imSomeClassTwo'); + await obj2.save(); - obj3.set('manyRelations', [obj1, obj2]); - await obj3.save(); + obj3.set('manyRelations', [obj1, obj2]); + await obj3.save(); - await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); + await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const result = ( - await apolloClient.query({ - query: gql` - query GetCustomer($id: ID!) { - customer(id: $id) { - objectId - manyRelations { - ... on Customer { - objectId - someCustomerField - arrayField { - ... on Element { - value - } + const result = ( + await apolloClient.query({ + query: gql` + query GetCustomer($id: ID!) { + customer(id: $id) { + objectId + manyRelations { + ... on Customer { + objectId + someCustomerField + arrayField { + ... on Element { + value } } - ... on SomeClass { - objectId - someClassField - } } - createdAt - updatedAt + ... on SomeClass { + objectId + someClassField + } } + createdAt + updatedAt } - `, - variables: { - id: obj3.id, - }, - }) - ).data.customer; + } + `, + variables: { + id: obj3.id, + }, + }) + ).data.customer; - expect(result.objectId).toEqual(obj3.id); - expect(result.manyRelations.length).toEqual(2); + expect(result.objectId).toEqual(obj3.id); + expect(result.manyRelations.length).toEqual(2); - const customerSubObject = result.manyRelations.find( - o => o.objectId === obj1.id - ); - const someClassSubObject = result.manyRelations.find( - o => o.objectId === obj2.id - ); + const customerSubObject = result.manyRelations.find(o => o.objectId === obj1.id); + const someClassSubObject = result.manyRelations.find(o => o.objectId === obj2.id); - expect(customerSubObject).toBeDefined(); - expect(someClassSubObject).toBeDefined(); - expect(customerSubObject.someCustomerField).toEqual( - 'imCustomerOne' - ); - const formatedArrayField = customerSubObject.arrayField.map( - elem => elem.value - ); - expect(formatedArrayField).toEqual(arrayField); - expect(someClassSubObject.someClassField).toEqual( - 'imSomeClassTwo' - ); - } - ); + expect(customerSubObject).toBeDefined(); + expect(someClassSubObject).toBeDefined(); + expect(customerSubObject.someCustomerField).toEqual('imCustomerOne'); + const formatedArrayField = customerSubObject.arrayField.map(elem => elem.value); + expect(formatedArrayField).toEqual(arrayField); + expect(someClassSubObject.someClassField).toEqual('imSomeClassTwo'); + }); it_only_db('mongo')( 'should return many child objects in allow cyclic query', @@ -4412,8 +4136,7 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); async function getObject(className, id, headers) { - const alias = - className.charAt(0).toLowerCase() + className.slice(1); + const alias = className.charAt(0).toLowerCase() + className.slice(1); const specificQueryResult = await apolloClient.query({ query: gql` query GetSomeObject($id: ID!) { @@ -4439,15 +4162,14 @@ describe('ParseGraphQLServer', () => { objects .slice(0, 3) .map(obj => - expectAsync( - getObject(obj.className, obj.id) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')) + expectAsync(getObject(obj.className, obj.id)).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ) ) ); - expect( - (await getObject(object4.className, object4.id)).data.get - .someField - ).toEqual('someValue4'); + expect((await getObject(object4.className, object4.id)).data.get.someField).toEqual( + 'someValue4' + ); await Promise.all( objects.map(async obj => expect( @@ -4634,9 +4356,7 @@ describe('ParseGraphQLServer', () => { }); expect(result1.data.get.pointerToUser.username).toBeUndefined(); - expect( - result2.data.graphQLClass.pointerToUser.username - ).toBeDefined(); + expect(result2.data.graphQLClass.pointerToUser.username).toBeDefined(); }); it('should respect protectedFields', async done => { @@ -4724,12 +4444,8 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const databaseAdapter = - parseServer.config.databaseController.adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + const databaseAdapter = parseServer.config.databaseController.adapter; + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); await apolloClient.query({ query: gql` @@ -4753,25 +4469,15 @@ describe('ParseGraphQLServer', () => { let foundGraphQLClassReadPreference = false; let foundUserClassReadPreference = false; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if ( - call.args[0].ns.collection.indexOf('GraphQLClass') >= 0 - ) { - foundGraphQLClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.PRIMARY - ); - } else if ( - call.args[0].ns.collection.indexOf('_User') >= 0 - ) { - foundUserClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.PRIMARY - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { + foundGraphQLClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.PRIMARY); + } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { + foundUserClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.PRIMARY); + } + }); expect(foundGraphQLClassReadPreference).toBe(true); expect(foundUserClassReadPreference).toBe(true); @@ -4785,20 +4491,13 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const databaseAdapter = - parseServer.config.databaseController.adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + const databaseAdapter = parseServer.config.databaseController.adapter; + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); await apolloClient.query({ query: gql` query GetSomeObject($id: ID!) { - graphQLClass( - id: $id - options: { readPreference: SECONDARY } - ) { + graphQLClass(id: $id, options: { readPreference: SECONDARY }) { pointerToUser { username } @@ -4817,21 +4516,15 @@ describe('ParseGraphQLServer', () => { let foundGraphQLClassReadPreference = false; let foundUserClassReadPreference = false; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { - foundGraphQLClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.SECONDARY - ); - } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { - foundUserClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.SECONDARY - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { + foundGraphQLClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.SECONDARY); + } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { + foundUserClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.SECONDARY); + } + }); expect(foundGraphQLClassReadPreference).toBe(true); expect(foundUserClassReadPreference).toBe(true); @@ -4842,22 +4535,15 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const databaseAdapter = - parseServer.config.databaseController.adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + const databaseAdapter = parseServer.config.databaseController.adapter; + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); await apolloClient.query({ query: gql` query GetSomeObject($id: ID!) { graphQLClass( id: $id - options: { - readPreference: SECONDARY - includeReadPreference: NEAREST - } + options: { readPreference: SECONDARY, includeReadPreference: NEAREST } ) { pointerToUser { username @@ -4877,21 +4563,15 @@ describe('ParseGraphQLServer', () => { let foundGraphQLClassReadPreference = false; let foundUserClassReadPreference = false; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { - foundGraphQLClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.SECONDARY - ); - } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { - foundUserClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.NEAREST - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { + foundGraphQLClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.SECONDARY); + } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { + foundUserClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.NEAREST); + } + }); expect(foundGraphQLClassReadPreference).toBe(true); expect(foundUserClassReadPreference).toBe(true); @@ -5092,9 +4772,7 @@ describe('ParseGraphQLServer', () => { }); expect( - result.data.graphQLClasses.edges - .map(object => object.node.someField) - .sort() + result.data.graphQLClasses.edges.map(object => object.node.someField).sort() ).toEqual(['someValue1', 'someValue3']); }); @@ -5170,9 +4848,7 @@ describe('ParseGraphQLServer', () => { }); expect( - result.data.graphQLClasses.edges - .map(object => object.node.someField) - .sort() + result.data.graphQLClasses.edges.map(object => object.node.someField).sort() ).toEqual(['someValue1', 'someValue2']); }); @@ -5187,9 +4863,7 @@ describe('ParseGraphQLServer', () => { const result = await apolloClient.query({ query: gql` - query FullTextSearchTests( - $where: FullTextSearchTestWhereInput - ) { + query FullTextSearchTests($where: FullTextSearchTestWhereInput) { fullTextSearchTests(where: $where) { edges { node { @@ -5217,9 +4891,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect( - result.data.fullTextSearchTests.edges[0].node.objectId - ).toEqual(obj.id); + expect(result.data.fullTextSearchTests.edges[0].node.objectId).toEqual(obj.id); } catch (e) { handleError(e); } @@ -5311,12 +4983,7 @@ describe('ParseGraphQLServer', () => { $skip: Int $first: Int ) { - find: someClasses( - where: $where - order: $order - skip: $skip - first: $first - ) { + find: someClasses(where: $where, order: $order, skip: $skip, first: $first) { edges { node { someField @@ -5337,9 +5004,10 @@ describe('ParseGraphQLServer', () => { }, }); - expect( - result.data.find.edges.map(obj => obj.node.someField) - ).toEqual(['someValue14', 'someValue17']); + expect(result.data.find.edges.map(obj => obj.node.someField)).toEqual([ + 'someValue14', + 'someValue17', + ]); }); it('should support pagination', async () => { @@ -5408,13 +5076,11 @@ describe('ParseGraphQLServer', () => { }; let result = await find(); - expect( - result.data.someClasses.edges.map(edge => edge.node.numberField) - ).toEqual(numberArray(0, 99)); - expect(result.data.someClasses.count).toEqual(100); - expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual( - false + expect(result.data.someClasses.edges.map(edge => edge.node.numberField)).toEqual( + numberArray(0, 99) ); + expect(result.data.someClasses.count).toEqual(100); + expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual(false); expect(result.data.someClasses.pageInfo.startCursor).toEqual( result.data.someClasses.edges[0].cursor ); @@ -5424,13 +5090,11 @@ describe('ParseGraphQLServer', () => { expect(result.data.someClasses.pageInfo.hasNextPage).toEqual(false); result = await find({ first: 10 }); - expect( - result.data.someClasses.edges.map(edge => edge.node.numberField) - ).toEqual(numberArray(0, 9)); - expect(result.data.someClasses.count).toEqual(100); - expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual( - false + expect(result.data.someClasses.edges.map(edge => edge.node.numberField)).toEqual( + numberArray(0, 9) ); + expect(result.data.someClasses.count).toEqual(100); + expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual(false); expect(result.data.someClasses.pageInfo.startCursor).toEqual( result.data.someClasses.edges[0].cursor ); @@ -5443,13 +5107,11 @@ describe('ParseGraphQLServer', () => { first: 10, after: result.data.someClasses.pageInfo.endCursor, }); - expect( - result.data.someClasses.edges.map(edge => edge.node.numberField) - ).toEqual(numberArray(10, 19)); - expect(result.data.someClasses.count).toEqual(100); - expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual( - true + expect(result.data.someClasses.edges.map(edge => edge.node.numberField)).toEqual( + numberArray(10, 19) ); + expect(result.data.someClasses.count).toEqual(100); + expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual(true); expect(result.data.someClasses.pageInfo.startCursor).toEqual( result.data.someClasses.edges[0].cursor ); @@ -5459,13 +5121,11 @@ describe('ParseGraphQLServer', () => { expect(result.data.someClasses.pageInfo.hasNextPage).toEqual(true); result = await find({ last: 10 }); - expect( - result.data.someClasses.edges.map(edge => edge.node.numberField) - ).toEqual(numberArray(90, 99)); - expect(result.data.someClasses.count).toEqual(100); - expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual( - true + expect(result.data.someClasses.edges.map(edge => edge.node.numberField)).toEqual( + numberArray(90, 99) ); + expect(result.data.someClasses.count).toEqual(100); + expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual(true); expect(result.data.someClasses.pageInfo.startCursor).toEqual( result.data.someClasses.edges[0].cursor ); @@ -5478,13 +5138,11 @@ describe('ParseGraphQLServer', () => { last: 10, before: result.data.someClasses.pageInfo.startCursor, }); - expect( - result.data.someClasses.edges.map(edge => edge.node.numberField) - ).toEqual(numberArray(80, 89)); - expect(result.data.someClasses.count).toEqual(100); - expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual( - true + expect(result.data.someClasses.edges.map(edge => edge.node.numberField)).toEqual( + numberArray(80, 89) ); + expect(result.data.someClasses.count).toEqual(100); + expect(result.data.someClasses.pageInfo.hasPreviousPage).toEqual(true); expect(result.data.someClasses.pageInfo.startCursor).toEqual( result.data.someClasses.edges[0].cursor ); @@ -5523,10 +5181,7 @@ describe('ParseGraphQLServer', () => { const result = await apolloClient.query({ query: gql` - query FindSomeObjects( - $where: GraphQLClassWhereInput - $first: Int - ) { + query FindSomeObjects($where: GraphQLClassWhereInput, $first: Int) { find: graphQLClasses(where: $where, first: $first) { edges { node { @@ -5618,10 +5273,7 @@ describe('ParseGraphQLServer', () => { const result = await apolloClient.query({ query: gql` query FindSomeObjects($limit: Int) { - find: someClasses( - where: { id: { exists: true } } - first: $limit - ) { + find: someClasses(where: { id: { exists: true } }, first: $limit) { edges { node { id @@ -5702,9 +5354,7 @@ describe('ParseGraphQLServer', () => { }); expect(result1.data.find.edges[0].node.someField).toBeDefined(); - expect( - result1.data.find.edges[0].node.pointerToUser - ).toBeUndefined(); + expect(result1.data.find.edges[0].node.pointerToUser).toBeUndefined(); expect(result2.data.find.edges[0].node.someField).toBeDefined(); expect(result2.data.find.edges[0].node.pointerToUser).toBeDefined(); }); @@ -5767,12 +5417,8 @@ describe('ParseGraphQLServer', () => { }, }, }); - expect( - result1.data.find.edges[0].node.pointerToUser.username - ).toBeUndefined(); - expect( - result2.data.find.edges[0].node.pointerToUser.username - ).toBeDefined(); + expect(result1.data.find.edges[0].node.pointerToUser.username).toBeUndefined(); + expect(result2.data.find.edges[0].node.pointerToUser.username).toBeDefined(); }); describe_only_db('mongo')('read preferences', () => { @@ -5781,12 +5427,8 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const databaseAdapter = - parseServer.config.databaseController.adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + const databaseAdapter = parseServer.config.databaseController.adapter; + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); await apolloClient.query({ query: gql` @@ -5811,21 +5453,15 @@ describe('ParseGraphQLServer', () => { let foundGraphQLClassReadPreference = false; let foundUserClassReadPreference = false; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { - foundGraphQLClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.PRIMARY - ); - } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { - foundUserClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.PRIMARY - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { + foundGraphQLClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.PRIMARY); + } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { + foundUserClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.PRIMARY); + } + }); expect(foundGraphQLClassReadPreference).toBe(true); expect(foundUserClassReadPreference).toBe(true); @@ -5836,19 +5472,13 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const databaseAdapter = - parseServer.config.databaseController.adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + const databaseAdapter = parseServer.config.databaseController.adapter; + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); await apolloClient.query({ query: gql` query FindSomeObjects { - find: graphQLClasses( - options: { readPreference: SECONDARY } - ) { + find: graphQLClasses(options: { readPreference: SECONDARY }) { edges { node { pointerToUser { @@ -5868,21 +5498,15 @@ describe('ParseGraphQLServer', () => { let foundGraphQLClassReadPreference = false; let foundUserClassReadPreference = false; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { - foundGraphQLClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.SECONDARY - ); - } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { - foundUserClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.SECONDARY - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { + foundGraphQLClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.SECONDARY); + } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { + foundUserClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.SECONDARY); + } + }); expect(foundGraphQLClassReadPreference).toBe(true); expect(foundUserClassReadPreference).toBe(true); @@ -5893,21 +5517,14 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const databaseAdapter = - parseServer.config.databaseController.adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + const databaseAdapter = parseServer.config.databaseController.adapter; + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); await apolloClient.query({ query: gql` query FindSomeObjects { graphQLClasses( - options: { - readPreference: SECONDARY - includeReadPreference: NEAREST - } + options: { readPreference: SECONDARY, includeReadPreference: NEAREST } ) { edges { node { @@ -5928,21 +5545,15 @@ describe('ParseGraphQLServer', () => { let foundGraphQLClassReadPreference = false; let foundUserClassReadPreference = false; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { - foundGraphQLClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.SECONDARY - ); - } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { - foundUserClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.NEAREST - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { + foundGraphQLClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.SECONDARY); + } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { + foundUserClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.NEAREST); + } + }); expect(foundGraphQLClassReadPreference).toBe(true); expect(foundUserClassReadPreference).toBe(true); @@ -5954,22 +5565,15 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const databaseAdapter = - parseServer.config.databaseController.adapter; - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + const databaseAdapter = parseServer.config.databaseController.adapter; + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); await apolloClient.query({ query: gql` query FindSomeObjects($where: GraphQLClassWhereInput) { find: graphQLClasses( where: $where - options: { - readPreference: SECONDARY - subqueryReadPreference: NEAREST - } + options: { readPreference: SECONDARY, subqueryReadPreference: NEAREST } ) { edges { node { @@ -5999,25 +5603,15 @@ describe('ParseGraphQLServer', () => { let foundGraphQLClassReadPreference = false; let foundUserClassReadPreference = false; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if ( - call.args[0].ns.collection.indexOf('GraphQLClass') >= 0 - ) { - foundGraphQLClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.SECONDARY - ); - } else if ( - call.args[0].ns.collection.indexOf('_User') >= 0 - ) { - foundUserClassReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.NEAREST - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('GraphQLClass') >= 0) { + foundGraphQLClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.SECONDARY); + } else if (call.args[0].ns.collection.indexOf('_User') >= 0) { + foundUserClassReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.NEAREST); + } + }); expect(foundGraphQLClassReadPreference).toBe(true); expect(foundUserClassReadPreference).toBe(true); @@ -6059,65 +5653,59 @@ describe('ParseGraphQLServer', () => { handleError(e); } - expect( - result.data.graphQLClasses.edges.map(edge => edge.node.objectId) - ).toEqual([object3.id, object1.id, object2.id]); + expect(result.data.graphQLClasses.edges.map(edge => edge.node.objectId)).toEqual([ + object3.id, + object1.id, + object2.id, + ]); }); - it_only_db('mongo')( - 'should order by multiple fields on a relation field', - async () => { - await prepareData(); + it_only_db('mongo')('should order by multiple fields on a relation field', async () => { + await prepareData(); - const parentObject = new Parse.Object('ParentClass'); - const relation = parentObject.relation('graphQLClasses'); - relation.add(object1); - relation.add(object2); - relation.add(object3); - await parentObject.save(); + const parentObject = new Parse.Object('ParentClass'); + const relation = parentObject.relation('graphQLClasses'); + relation.add(object1); + relation.add(object2); + relation.add(object3); + await parentObject.save(); - await resetGraphQLCache(); + await resetGraphQLCache(); - let result; - try { - result = await apolloClient.query({ - query: gql` - query OrderByMultipleFieldsOnRelation( - $id: ID! - $order: [GraphQLClassOrder!] - ) { - parentClass(id: $id) { - graphQLClasses(order: $order) { - edges { - node { - objectId - } + let result; + try { + result = await apolloClient.query({ + query: gql` + query OrderByMultipleFieldsOnRelation($id: ID!, $order: [GraphQLClassOrder!]) { + parentClass(id: $id) { + graphQLClasses(order: $order) { + edges { + node { + objectId } } } } - `, - variables: { - id: parentObject.id, - order: ['someOtherField_DESC', 'someField_ASC'], + } + `, + variables: { + id: parentObject.id, + order: ['someOtherField_DESC', 'someField_ASC'], + }, + context: { + headers: { + 'X-Parse-Master-Key': 'test', }, - context: { - headers: { - 'X-Parse-Master-Key': 'test', - }, - }, - }); - } catch (e) { - handleError(e); - } - - expect( - result.data.parentClass.graphQLClasses.edges.map( - edge => edge.node.objectId - ) - ).toEqual([object3.id, object1.id, object2.id]); + }, + }); + } catch (e) { + handleError(e); } - ); + + expect( + result.data.parentClass.graphQLClasses.edges.map(edge => edge.node.objectId) + ).toEqual([object3.id, object1.id, object2.id]); + }); }); }); @@ -6155,13 +5743,9 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.createCustomer.clientMutationId).toEqual( - clientMutationId - ); + expect(result.data.createCustomer.clientMutationId).toEqual(clientMutationId); expect(result.data.createCustomer.customer.id).toBeDefined(); - expect(result.data.createCustomer.customer.someField).toEqual( - 'someValue' - ); + expect(result.data.createCustomer.customer.someField).toEqual('someValue'); const customer = await new Parse.Query('Customer').get( result.data.createCustomer.customer.objectId @@ -6179,8 +5763,7 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); async function createObject(className, headers) { - const getClassName = - className.charAt(0).toLowerCase() + className.slice(1); + const getClassName = className.charAt(0).toLowerCase() + className.slice(1); const result = await apolloClient.mutate({ mutation: gql` mutation CreateSomeObject { @@ -6197,8 +5780,7 @@ describe('ParseGraphQLServer', () => { }, }); - const specificCreate = - result.data[`create${className}`][getClassName]; + const specificCreate = result.data[`create${className}`][getClassName]; expect(specificCreate.id).toBeDefined(); expect(specificCreate.createdAt).toBeDefined(); @@ -6206,9 +5788,7 @@ describe('ParseGraphQLServer', () => { } await expectAsync(createObject('GraphQLClass')).toBeRejectedWith( - jasmine.stringMatching( - 'Permission denied for action create on class GraphQLClass' - ) + jasmine.stringMatching('Permission denied for action create on class GraphQLClass') ); await expectAsync(createObject('PublicClass')).toBeResolved(); await expectAsync( @@ -6242,9 +5822,7 @@ describe('ParseGraphQLServer', () => { 'X-Parse-Session-Token': user4.getSessionToken(), }) ).toBeRejectedWith( - jasmine.stringMatching( - 'Permission denied for action create on class GraphQLClass' - ) + jasmine.stringMatching('Permission denied for action create on class GraphQLClass') ); await expectAsync( createObject('PublicClass', { @@ -6288,16 +5866,10 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.updateCustomer.clientMutationId).toEqual( - clientMutationId - ); + expect(result.data.updateCustomer.clientMutationId).toEqual(clientMutationId); expect(result.data.updateCustomer.customer.updatedAt).toBeDefined(); - expect(result.data.updateCustomer.customer.someField1).toEqual( - 'someField1Value2' - ); - expect(result.data.updateCustomer.customer.someField2).toEqual( - 'someField2Value1' - ); + expect(result.data.updateCustomer.customer.someField1).toEqual('someField1Value2'); + expect(result.data.updateCustomer.customer.someField2).toEqual('someField2Value1'); await obj.fetch(); @@ -6315,10 +5887,7 @@ describe('ParseGraphQLServer', () => { const result = await apolloClient.mutate({ mutation: gql` - mutation UpdateCustomer( - $id: ID! - $fields: UpdateCustomerFieldsInput - ) { + mutation UpdateCustomer($id: ID!, $fields: UpdateCustomerFieldsInput) { updateCustomer(input: { id: $id, fields: $fields }) { customer { id @@ -6335,9 +5904,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.updateCustomer.customer.objectId).toEqual( - obj.id - ); + expect(result.data.updateCustomer.customer.objectId).toEqual(obj.id); await obj.fetch(); @@ -6546,8 +6113,7 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); function updateObject(className, id, fields, headers) { - const mutationName = - className.charAt(0).toLowerCase() + className.slice(1); + const mutationName = className.charAt(0).toLowerCase() + className.slice(1); return apolloClient.mutate({ mutation: gql` @@ -6593,8 +6159,7 @@ describe('ParseGraphQLServer', () => { someField: 'changedValue1', }) ).data[`update${object4.className}`][ - object4.className.charAt(0).toLowerCase() + - object4.className.slice(1) + object4.className.charAt(0).toLowerCase() + object4.className.slice(1) ].updatedAt ).toBeDefined(); await object4.fetch({ useMasterKey: true }); @@ -6610,8 +6175,7 @@ describe('ParseGraphQLServer', () => { { 'X-Parse-Master-Key': 'test' } ) ).data[`update${obj.className}`][ - obj.className.charAt(0).toLowerCase() + - obj.className.slice(1) + obj.className.charAt(0).toLowerCase() + obj.className.slice(1) ].updatedAt ).toBeDefined(); await obj.fetch({ useMasterKey: true }); @@ -6629,8 +6193,7 @@ describe('ParseGraphQLServer', () => { { 'X-Parse-Session-Token': user1.getSessionToken() } ) ).data[`update${obj.className}`][ - obj.className.charAt(0).toLowerCase() + - obj.className.slice(1) + obj.className.charAt(0).toLowerCase() + obj.className.slice(1) ].updatedAt ).toBeDefined(); await obj.fetch({ useMasterKey: true }); @@ -6648,8 +6211,7 @@ describe('ParseGraphQLServer', () => { { 'X-Parse-Session-Token': user2.getSessionToken() } ) ).data[`update${obj.className}`][ - obj.className.charAt(0).toLowerCase() + - obj.className.slice(1) + obj.className.charAt(0).toLowerCase() + obj.className.slice(1) ].updatedAt ).toBeDefined(); await obj.fetch({ useMasterKey: true }); @@ -6667,8 +6229,7 @@ describe('ParseGraphQLServer', () => { { 'X-Parse-Session-Token': user3.getSessionToken() } ) ).data[`update${obj.className}`][ - obj.className.charAt(0).toLowerCase() + - obj.className.slice(1) + obj.className.charAt(0).toLowerCase() + obj.className.slice(1) ].updatedAt ).toBeDefined(); await obj.fetch({ useMasterKey: true }); @@ -6710,8 +6271,7 @@ describe('ParseGraphQLServer', () => { { 'X-Parse-Session-Token': user4.getSessionToken() } ) ).data[`update${object4.className}`][ - object4.className.charAt(0).toLowerCase() + - object4.className.slice(1) + object4.className.charAt(0).toLowerCase() + object4.className.slice(1) ].updatedAt ).toBeDefined(); await object4.fetch({ useMasterKey: true }); @@ -6740,8 +6300,7 @@ describe('ParseGraphQLServer', () => { { 'X-Parse-Session-Token': user5.getSessionToken() } ) ).data[`update${object3.className}`][ - object3.className.charAt(0).toLowerCase() + - object3.className.slice(1) + object3.className.charAt(0).toLowerCase() + object3.className.slice(1) ].updatedAt ).toBeDefined(); await object3.fetch({ useMasterKey: true }); @@ -6755,8 +6314,7 @@ describe('ParseGraphQLServer', () => { { 'X-Parse-Session-Token': user5.getSessionToken() } ) ).data[`update${object4.className}`][ - object4.className.charAt(0).toLowerCase() + - object4.className.slice(1) + object4.className.charAt(0).toLowerCase() + object4.className.slice(1) ].updatedAt ).toBeDefined(); await object4.fetch({ useMasterKey: true }); @@ -6796,22 +6354,14 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.deleteCustomer.clientMutationId).toEqual( - clientMutationId - ); - expect(result.data.deleteCustomer.customer.objectId).toEqual( - obj.id - ); - expect(result.data.deleteCustomer.customer.someField1).toEqual( - 'someField1Value1' - ); - expect(result.data.deleteCustomer.customer.someField2).toEqual( - 'someField2Value1' - ); + expect(result.data.deleteCustomer.clientMutationId).toEqual(clientMutationId); + expect(result.data.deleteCustomer.customer.objectId).toEqual(obj.id); + expect(result.data.deleteCustomer.customer.someField1).toEqual('someField1Value1'); + expect(result.data.deleteCustomer.customer.someField2).toEqual('someField2Value1'); - await expectAsync( - obj.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(obj.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); }); it('should respect level permissions', async () => { @@ -6820,8 +6370,7 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); function deleteObject(className, id, headers) { - const mutationName = - className.charAt(0).toLowerCase() + className.slice(1); + const mutationName = className.charAt(0).toLowerCase() + className.slice(1); return apolloClient.mutate({ mutation: gql` mutation DeleteSomeObject( @@ -6846,9 +6395,9 @@ describe('ParseGraphQLServer', () => { await Promise.all( objects.slice(0, 3).map(async obj => { const originalFieldValue = obj.get('someField'); - await expectAsync( - deleteObject(obj.className, obj.id) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(deleteObject(obj.className, obj.id)).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); await obj.fetch({ useMasterKey: true }); expect(obj.get('someField')).toEqual(originalFieldValue); }) @@ -6867,52 +6416,42 @@ describe('ParseGraphQLServer', () => { ); expect( (await deleteObject(object4.className, object4.id)).data.delete[ - object4.className.charAt(0).toLowerCase() + - object4.className.slice(1) + object4.className.charAt(0).toLowerCase() + object4.className.slice(1) ] ).toEqual({ objectId: object4.id, __typename: 'PublicClass' }); - await expectAsync( - object4.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object4.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); expect( ( await deleteObject(object1.className, object1.id, { 'X-Parse-Master-Key': 'test', }) - ).data.delete[ - object1.className.charAt(0).toLowerCase() + - object1.className.slice(1) - ] + ).data.delete[object1.className.charAt(0).toLowerCase() + object1.className.slice(1)] ).toEqual({ objectId: object1.id, __typename: 'GraphQLClass' }); - await expectAsync( - object1.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object1.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); expect( ( await deleteObject(object2.className, object2.id, { 'X-Parse-Session-Token': user2.getSessionToken(), }) - ).data.delete[ - object2.className.charAt(0).toLowerCase() + - object2.className.slice(1) - ] + ).data.delete[object2.className.charAt(0).toLowerCase() + object2.className.slice(1)] ).toEqual({ objectId: object2.id, __typename: 'GraphQLClass' }); - await expectAsync( - object2.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object2.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); expect( ( await deleteObject(object3.className, object3.id, { 'X-Parse-Session-Token': user5.getSessionToken(), }) - ).data.delete[ - object3.className.charAt(0).toLowerCase() + - object3.className.slice(1) - ] + ).data.delete[object3.className.charAt(0).toLowerCase() + object3.className.slice(1)] ).toEqual({ objectId: object3.id, __typename: 'GraphQLClass' }); - await expectAsync( - object3.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object3.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); }); it('should respect level permissions with specific class mutation', async () => { @@ -6921,8 +6460,7 @@ describe('ParseGraphQLServer', () => { await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); function deleteObject(className, id, headers) { - const mutationName = - className.charAt(0).toLowerCase() + className.slice(1); + const mutationName = className.charAt(0).toLowerCase() + className.slice(1); return apolloClient.mutate({ mutation: gql` mutation DeleteSomeObject( @@ -6947,9 +6485,9 @@ describe('ParseGraphQLServer', () => { await Promise.all( objects.slice(0, 3).map(async obj => { const originalFieldValue = obj.get('someField'); - await expectAsync( - deleteObject(obj.className, obj.id) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(deleteObject(obj.className, obj.id)).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); await obj.fetch({ useMasterKey: true }); expect(obj.get('someField')).toEqual(originalFieldValue); }) @@ -6969,53 +6507,47 @@ describe('ParseGraphQLServer', () => { expect( (await deleteObject(object4.className, object4.id)).data[ `delete${object4.className}` - ][ - object4.className.charAt(0).toLowerCase() + - object4.className.slice(1) - ].objectId + ][object4.className.charAt(0).toLowerCase() + object4.className.slice(1)].objectId ).toEqual(object4.id); - await expectAsync( - object4.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object4.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); expect( ( await deleteObject(object1.className, object1.id, { 'X-Parse-Master-Key': 'test', }) ).data[`delete${object1.className}`][ - object1.className.charAt(0).toLowerCase() + - object1.className.slice(1) + object1.className.charAt(0).toLowerCase() + object1.className.slice(1) ].objectId ).toEqual(object1.id); - await expectAsync( - object1.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object1.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); expect( ( await deleteObject(object2.className, object2.id, { 'X-Parse-Session-Token': user2.getSessionToken(), }) ).data[`delete${object2.className}`][ - object2.className.charAt(0).toLowerCase() + - object2.className.slice(1) + object2.className.charAt(0).toLowerCase() + object2.className.slice(1) ].objectId ).toEqual(object2.id); - await expectAsync( - object2.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object2.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); expect( ( await deleteObject(object3.className, object3.id, { 'X-Parse-Session-Token': user5.getSessionToken(), }) ).data[`delete${object3.className}`][ - object3.className.charAt(0).toLowerCase() + - object3.className.slice(1) + object3.className.charAt(0).toLowerCase() + object3.className.slice(1) ].objectId ).toEqual(object3.id); - await expectAsync( - object3.fetch({ useMasterKey: true }) - ).toBeRejectedWith(jasmine.stringMatching('Object not found')); + await expectAsync(object3.fetch({ useMasterKey: true })).toBeRejectedWith( + jasmine.stringMatching('Object not found') + ); }); }); }); @@ -7052,10 +6584,7 @@ describe('ParseGraphQLServer', () => { }, }) ); - body.append( - 'map', - JSON.stringify({ 1: ['variables.input.upload'] }) - ); + body.append('map', JSON.stringify({ 1: ['variables.input.upload'] })); body.append('1', 'My File Content', { filename: 'myFileName.txt', contentType: 'text/plain', @@ -7071,9 +6600,7 @@ describe('ParseGraphQLServer', () => { const result = JSON.parse(await res.text()); - expect(result.data.createFile.clientMutationId).toEqual( - clientMutationId - ); + expect(result.data.createFile.clientMutationId).toEqual(clientMutationId); expect(result.data.createFile.fileInfo.name).toEqual( jasmine.stringMatching(/_myFileName.txt$/) ); @@ -7121,11 +6648,7 @@ describe('ParseGraphQLServer', () => { }, }); - const { - id, - username: resultUserName, - email: resultEmail, - } = result.data.viewer.user; + const { id, username: resultUserName, email: resultEmail } = result.data.viewer.user; expect(id).toBeDefined(); expect(resultUserName).toEqual(userName); expect(resultEmail).toEqual(email); @@ -7280,9 +6803,7 @@ describe('ParseGraphQLServer', () => { expect(result.data.signUp.viewer.sessionToken).toBeDefined(); expect(result.data.signUp.viewer.user.someField).toEqual('someValue'); expect(result.data.signUp.viewer.user.aPointer.id).toBeDefined(); - expect(result.data.signUp.viewer.user.aPointer.username).toEqual( - 'user2' - ); + expect(result.data.signUp.viewer.user.aPointer.username).toEqual('user2'); expect(typeof result.data.signUp.viewer.sessionToken).toBe('string'); }); @@ -7343,20 +6864,12 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.logInWith.clientMutationId).toEqual( - clientMutationId - ); + expect(result.data.logInWith.clientMutationId).toEqual(clientMutationId); expect(result.data.logInWith.viewer.sessionToken).toBeDefined(); - expect(result.data.logInWith.viewer.user.someField).toEqual( - 'someValue' - ); - expect(typeof result.data.logInWith.viewer.sessionToken).toBe( - 'string' - ); + expect(result.data.logInWith.viewer.user.someField).toEqual('someValue'); + expect(typeof result.data.logInWith.viewer.sessionToken).toBe('string'); expect(result.data.logInWith.viewer.user.aPointer.id).toBeDefined(); - expect(result.data.logInWith.viewer.user.aPointer.username).toEqual( - 'user2' - ); + expect(result.data.logInWith.viewer.user.aPointer.username).toEqual('user2'); }); it('should log the user in', async () => { @@ -7511,9 +7024,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.resetPassword.clientMutationId).toEqual( - clientMutationId - ); + expect(result.data.resetPassword.clientMutationId).toEqual(clientMutationId); expect(result.data.resetPassword.ok).toBeTruthy(); }); it('should send verification email again', async () => { @@ -7536,9 +7047,7 @@ describe('ParseGraphQLServer', () => { await Parse.User.logOut(); const result = await apolloClient.mutate({ mutation: gql` - mutation SendVerificationEmail( - $input: SendVerificationEmailInput! - ) { + mutation SendVerificationEmail($input: SendVerificationEmailInput!) { sendVerificationEmail(input: $input) { clientMutationId ok @@ -7553,9 +7062,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.sendVerificationEmail.clientMutationId).toEqual( - clientMutationId - ); + expect(result.data.sendVerificationEmail.clientMutationId).toEqual(clientMutationId); expect(result.data.sendVerificationEmail.ok).toBeTruthy(); }); }); @@ -7679,9 +7186,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect(result.data.callCloudCode.clientMutationId).toEqual( - clientMutationId - ); + expect(result.data.callCloudCode.clientMutationId).toEqual(clientMutationId); expect(result.data.callCloudCode.result).toEqual('Hello world!'); } catch (e) { handleError(e); @@ -7717,24 +7222,12 @@ describe('ParseGraphQLServer', () => { expect(req.params.date.getTime()).toBe(1463907600000); expect(req.params.dateList[0] instanceof Date).toBe(true); expect(req.params.dateList[0].getTime()).toBe(1463907600000); - expect(req.params.complexStructure.date[0] instanceof Date).toBe( - true - ); - expect(req.params.complexStructure.date[0].getTime()).toBe( - 1463907600000 - ); - expect( - req.params.complexStructure.deepDate.date[0] instanceof Date - ).toBe(true); - expect(req.params.complexStructure.deepDate.date[0].getTime()).toBe( - 1463907600000 - ); - expect( - req.params.complexStructure.deepDate2[0].date instanceof Date - ).toBe(true); - expect( - req.params.complexStructure.deepDate2[0].date.getTime() - ).toBe(1463907600000); + expect(req.params.complexStructure.date[0] instanceof Date).toBe(true); + expect(req.params.complexStructure.date[0].getTime()).toBe(1463907600000); + expect(req.params.complexStructure.deepDate.date[0] instanceof Date).toBe(true); + expect(req.params.complexStructure.deepDate.date[0].getTime()).toBe(1463907600000); + expect(req.params.complexStructure.deepDate2[0].date instanceof Date).toBe(true); + expect(req.params.complexStructure.deepDate2[0].date.getTime()).toBe(1463907600000); // Regression for #2294 expect(req.params.file instanceof Parse.File).toBe(true); expect(req.params.file.url()).toEqual('https://some.url'); @@ -7847,9 +7340,12 @@ describe('ParseGraphQLServer', () => { }) ).data['__type']; expect(functionEnum.kind).toEqual('ENUM'); - expect( - functionEnum.enumValues.map(value => value.name).sort() - ).toEqual(['_underscored', 'a', 'b', 'contains1Number']); + expect(functionEnum.enumValues.map(value => value.name).sort()).toEqual([ + '_underscored', + 'a', + 'b', + 'contains1Number', + ]); } catch (e) { handleError(e); } @@ -7857,10 +7353,7 @@ describe('ParseGraphQLServer', () => { it('should warn functions not matching GraphQL allowed names', async () => { try { - spyOn( - parseGraphQLServer.parseGraphQLSchema.log, - 'warn' - ).and.callThrough(); + spyOn(parseGraphQLServer.parseGraphQLSchema.log, 'warn').and.callThrough(); Parse.Cloud.define('a', async () => { return 'hello a'; @@ -7889,9 +7382,7 @@ describe('ParseGraphQLServer', () => { }) ).data['__type']; expect(functionEnum.kind).toEqual('ENUM'); - expect( - functionEnum.enumValues.map(value => value.name).sort() - ).toEqual(['a']); + expect(functionEnum.enumValues.map(value => value.name).sort()).toEqual(['a']); expect( parseGraphQLServer.parseGraphQLSchema.log.warn.calls .all() @@ -7915,9 +7406,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -7962,9 +7451,7 @@ describe('ParseGraphQLServer', () => { someClass(id: $id) { someField } - someClasses( - where: { someField: { equalTo: $someFieldValue } } - ) { + someClasses(where: { someField: { equalTo: $someFieldValue } }) { edges { node { someField @@ -7994,9 +7481,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -8041,9 +7526,7 @@ describe('ParseGraphQLServer', () => { someClass(id: $id) { someField } - someClasses( - where: { someField: { equalTo: $someFieldValue } } - ) { + someClasses(where: { someField: { equalTo: $someFieldValue } }) { edges { node { someField @@ -8073,9 +7556,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -8120,9 +7601,7 @@ describe('ParseGraphQLServer', () => { someClass(id: $id) { someField } - someClasses( - where: { someField: { equalTo: $someFieldValue } } - ) { + someClasses(where: { someField: { equalTo: $someFieldValue } }) { edges { node { someField @@ -8153,19 +7632,14 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } `, variables: { schemaFields: { - addBooleans: [ - { name: 'someFieldTrue' }, - { name: 'someFieldFalse' }, - ], + addBooleans: [{ name: 'someFieldTrue' }, { name: 'someFieldFalse' }], }, }, context: { @@ -8231,12 +7705,8 @@ describe('ParseGraphQLServer', () => { }, }); - expect(typeof getResult.data.someClass.someFieldTrue).toEqual( - 'boolean' - ); - expect(typeof getResult.data.someClass.someFieldFalse).toEqual( - 'boolean' - ); + expect(typeof getResult.data.someClass.someFieldTrue).toEqual('boolean'); + expect(typeof getResult.data.someClass.someFieldFalse).toEqual('boolean'); expect(getResult.data.someClass.someFieldTrue).toEqual(true); expect(getResult.data.someClass.someFieldFalse).toEqual(false); expect(getResult.data.someClasses.edges.length).toEqual(1); @@ -8252,9 +7722,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -8313,9 +7781,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect(new Date(getResult.data.someClass.someField)).toEqual( - someFieldValue - ); + expect(new Date(getResult.data.someClass.someField)).toEqual(someFieldValue); expect(getResult.data.someClasses.edges.length).toEqual(1); } catch (e) { handleError(e); @@ -8730,77 +8196,68 @@ describe('ParseGraphQLServer', () => { expect(result.company.name).toEqual('imACompany2'); }); - it_only_db('mongo')( - 'should support relation and nested relation on create', - async () => { - const company = new Parse.Object('Company'); - company.set('name', 'imACompany1'); - await company.save(); + it_only_db('mongo')('should support relation and nested relation on create', async () => { + const company = new Parse.Object('Company'); + company.set('name', 'imACompany1'); + await company.save(); - const country = new Parse.Object('Country'); - country.set('name', 'imACountry'); - country.relation('companies').add(company); - await country.save(); + const country = new Parse.Object('Country'); + country.set('name', 'imACountry'); + country.relation('companies').add(company); + await country.save(); - await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); + await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const { - data: { - createCountry: { country: result }, - }, - } = await apolloClient.mutate({ - mutation: gql` - mutation CreateCountry($fields: CreateCountryFieldsInput) { - createCountry(input: { fields: $fields }) { - country { - id - objectId - name - companies { - edges { - node { - id - objectId - name - } + const { + data: { + createCountry: { country: result }, + }, + } = await apolloClient.mutate({ + mutation: gql` + mutation CreateCountry($fields: CreateCountryFieldsInput) { + createCountry(input: { fields: $fields }) { + country { + id + objectId + name + companies { + edges { + node { + id + objectId + name } } } } } - `, - variables: { - fields: { - name: 'imACountry2', - companies: { - add: [company.id], - createAndAdd: [ - { - name: 'imACompany2', - }, - { - name: 'imACompany3', - }, - ], - }, + } + `, + variables: { + fields: { + name: 'imACountry2', + companies: { + add: [company.id], + createAndAdd: [ + { + name: 'imACompany2', + }, + { + name: 'imACompany3', + }, + ], }, }, - }); + }, + }); - expect(result.id).toBeDefined(); - expect(result.name).toEqual('imACountry2'); - expect(result.companies.edges.length).toEqual(3); - expect( - result.companies.edges.some(o => o.node.objectId === company.id) - ).toBeTruthy(); - expect( - result.companies.edges.some(o => o.node.name === 'imACompany2') - ).toBeTruthy(); - expect( - result.companies.edges.some(o => o.node.name === 'imACompany3') - ).toBeTruthy(); - } - ); + expect(result.id).toBeDefined(); + expect(result.name).toEqual('imACountry2'); + expect(result.companies.edges.length).toEqual(3); + expect(result.companies.edges.some(o => o.node.objectId === company.id)).toBeTruthy(); + expect(result.companies.edges.some(o => o.node.name === 'imACompany2')).toBeTruthy(); + expect(result.companies.edges.some(o => o.node.name === 'imACompany3')).toBeTruthy(); + }); it_only_db('mongo')('should support deep nested creation', async () => { const team = new Parse.Object('Team'); @@ -8896,152 +8353,132 @@ describe('ParseGraphQLServer', () => { ).toBeTruthy(); }); - it_only_db('mongo')( - 'should support relation and nested relation on update', - async () => { - const company1 = new Parse.Object('Company'); - company1.set('name', 'imACompany1'); - await company1.save(); + it_only_db('mongo')('should support relation and nested relation on update', async () => { + const company1 = new Parse.Object('Company'); + company1.set('name', 'imACompany1'); + await company1.save(); - const company2 = new Parse.Object('Company'); - company2.set('name', 'imACompany2'); - await company2.save(); + const company2 = new Parse.Object('Company'); + company2.set('name', 'imACompany2'); + await company2.save(); - const country = new Parse.Object('Country'); - country.set('name', 'imACountry'); - country.relation('companies').add(company1); - await country.save(); + const country = new Parse.Object('Country'); + country.set('name', 'imACountry'); + country.relation('companies').add(company1); + await country.save(); - await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); + await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const { - data: { - updateCountry: { country: result }, - }, - } = await apolloClient.mutate({ - mutation: gql` - mutation UpdateCountry( - $id: ID! - $fields: UpdateCountryFieldsInput - ) { - updateCountry(input: { id: $id, fields: $fields }) { - country { - id - objectId - companies { - edges { - node { - id - objectId - name - } + const { + data: { + updateCountry: { country: result }, + }, + } = await apolloClient.mutate({ + mutation: gql` + mutation UpdateCountry($id: ID!, $fields: UpdateCountryFieldsInput) { + updateCountry(input: { id: $id, fields: $fields }) { + country { + id + objectId + companies { + edges { + node { + id + objectId + name } } } } } - `, - variables: { - id: country.id, - fields: { - companies: { - add: [company2.id], - remove: [company1.id], - createAndAdd: [ - { - name: 'imACompany3', - }, - ], - }, + } + `, + variables: { + id: country.id, + fields: { + companies: { + add: [company2.id], + remove: [company1.id], + createAndAdd: [ + { + name: 'imACompany3', + }, + ], }, }, - }); + }, + }); - expect(result.objectId).toEqual(country.id); - expect(result.companies.edges.length).toEqual(2); - expect( - result.companies.edges.some(o => o.node.objectId === company2.id) - ).toBeTruthy(); - expect( - result.companies.edges.some(o => o.node.name === 'imACompany3') - ).toBeTruthy(); - expect( - result.companies.edges.some(o => o.node.objectId === company1.id) - ).toBeFalsy(); - } - ); + expect(result.objectId).toEqual(country.id); + expect(result.companies.edges.length).toEqual(2); + expect(result.companies.edges.some(o => o.node.objectId === company2.id)).toBeTruthy(); + expect(result.companies.edges.some(o => o.node.name === 'imACompany3')).toBeTruthy(); + expect(result.companies.edges.some(o => o.node.objectId === company1.id)).toBeFalsy(); + }); - it_only_db('mongo')( - 'should support nested relation on create with filter', - async () => { - const company = new Parse.Object('Company'); - company.set('name', 'imACompany1'); - await company.save(); + it_only_db('mongo')('should support nested relation on create with filter', async () => { + const company = new Parse.Object('Company'); + company.set('name', 'imACompany1'); + await company.save(); - const country = new Parse.Object('Country'); - country.set('name', 'imACountry'); - country.relation('companies').add(company); - await country.save(); + const country = new Parse.Object('Country'); + country.set('name', 'imACountry'); + country.relation('companies').add(company); + await country.save(); - await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); + await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - const { - data: { - createCountry: { country: result }, - }, - } = await apolloClient.mutate({ - mutation: gql` - mutation CreateCountry( - $fields: CreateCountryFieldsInput - $where: CompanyWhereInput - ) { - createCountry(input: { fields: $fields }) { - country { - id - name - companies(where: $where) { - edges { - node { - id - name - } + const { + data: { + createCountry: { country: result }, + }, + } = await apolloClient.mutate({ + mutation: gql` + mutation CreateCountry($fields: CreateCountryFieldsInput, $where: CompanyWhereInput) { + createCountry(input: { fields: $fields }) { + country { + id + name + companies(where: $where) { + edges { + node { + id + name } } } } } - `, - variables: { - where: { - name: { - equalTo: 'imACompany2', - }, - }, - fields: { - name: 'imACountry2', - companies: { - add: [company.id], - createAndAdd: [ - { - name: 'imACompany2', - }, - { - name: 'imACompany3', - }, - ], - }, + } + `, + variables: { + where: { + name: { + equalTo: 'imACompany2', }, }, - }); + fields: { + name: 'imACountry2', + companies: { + add: [company.id], + createAndAdd: [ + { + name: 'imACompany2', + }, + { + name: 'imACompany3', + }, + ], + }, + }, + }, + }); - expect(result.id).toBeDefined(); - expect(result.name).toEqual('imACountry2'); - expect(result.companies.edges.length).toEqual(1); - expect( - result.companies.edges.some(o => o.node.name === 'imACompany2') - ).toBeTruthy(); - } - ); + expect(result.id).toBeDefined(); + expect(result.name).toEqual('imACountry2'); + expect(result.companies.edges.length).toEqual(1); + expect(result.companies.edges.some(o => o.node.name === 'imACompany2')).toBeTruthy(); + }); it_only_db('mongo')('should support relation on query', async () => { const company1 = new Parse.Object('Company'); @@ -9088,12 +8525,8 @@ describe('ParseGraphQLServer', () => { expect(result1.objectId).toEqual(country.id); expect(result1.companies.edges.length).toEqual(2); - expect( - result1.companies.edges.some(o => o.node.objectId === company1.id) - ).toBeTruthy(); - expect( - result1.companies.edges.some(o => o.node.objectId === company2.id) - ).toBeTruthy(); + expect(result1.companies.edges.some(o => o.node.objectId === company1.id)).toBeTruthy(); + expect(result1.companies.edges.some(o => o.node.objectId === company2.id)).toBeTruthy(); // With where const { @@ -9128,235 +8561,232 @@ describe('ParseGraphQLServer', () => { expect(result2.companies.edges[0].node.objectId).toEqual(company1.id); }); - it_only_db('mongo')( - 'should support relational where query', - async () => { - const president = new Parse.Object('President'); - president.set('name', 'James'); - await president.save(); + it_only_db('mongo')('should support relational where query', async () => { + const president = new Parse.Object('President'); + president.set('name', 'James'); + await president.save(); - const employee = new Parse.Object('Employee'); - employee.set('name', 'John'); - await employee.save(); + const employee = new Parse.Object('Employee'); + employee.set('name', 'John'); + await employee.save(); - const company1 = new Parse.Object('Company'); - company1.set('name', 'imACompany1'); - await company1.save(); + const company1 = new Parse.Object('Company'); + company1.set('name', 'imACompany1'); + await company1.save(); - const company2 = new Parse.Object('Company'); - company2.set('name', 'imACompany2'); - company2.relation('employees').add([employee]); - await company2.save(); + const company2 = new Parse.Object('Company'); + company2.set('name', 'imACompany2'); + company2.relation('employees').add([employee]); + await company2.save(); - const country = new Parse.Object('Country'); - country.set('name', 'imACountry'); - country.relation('companies').add([company1, company2]); - await country.save(); + const country = new Parse.Object('Country'); + country.set('name', 'imACountry'); + country.relation('companies').add([company1, company2]); + await country.save(); - const country2 = new Parse.Object('Country'); - country2.set('name', 'imACountry2'); - country2.relation('companies').add([company1]); - await country2.save(); + const country2 = new Parse.Object('Country'); + country2.set('name', 'imACountry2'); + country2.relation('companies').add([company1]); + await country2.save(); - const country3 = new Parse.Object('Country'); - country3.set('name', 'imACountry3'); - country3.set('president', president); - await country3.save(); + const country3 = new Parse.Object('Country'); + country3.set('name', 'imACountry3'); + country3.set('president', president); + await country3.save(); - await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); + await parseGraphQLServer.parseGraphQLSchema.databaseController.schemaCache.clear(); - let { - data: { - countries: { edges: result }, - }, - } = await apolloClient.query({ - query: gql` - query findCountry($where: CountryWhereInput) { - countries(where: $where) { - edges { - node { - id - objectId - companies { - edges { - node { - id - objectId - name - } + let { + data: { + countries: { edges: result }, + }, + } = await apolloClient.query({ + query: gql` + query findCountry($where: CountryWhereInput) { + countries(where: $where) { + edges { + node { + id + objectId + companies { + edges { + node { + id + objectId + name } } } } } } - `, - variables: { - where: { - companies: { - have: { - employees: { have: { name: { equalTo: 'John' } } }, - }, + } + `, + variables: { + where: { + companies: { + have: { + employees: { have: { name: { equalTo: 'John' } } }, }, }, }, - }); - expect(result.length).toEqual(1); - result = result[0].node; - expect(result.objectId).toEqual(country.id); - expect(result.companies.edges.length).toEqual(2); + }, + }); + expect(result.length).toEqual(1); + result = result[0].node; + expect(result.objectId).toEqual(country.id); + expect(result.companies.edges.length).toEqual(2); - const { - data: { - countries: { edges: result2 }, - }, - } = await apolloClient.query({ - query: gql` - query findCountry($where: CountryWhereInput) { - countries(where: $where) { - edges { - node { - id - objectId - companies { - edges { - node { - id - objectId - name - } + const { + data: { + countries: { edges: result2 }, + }, + } = await apolloClient.query({ + query: gql` + query findCountry($where: CountryWhereInput) { + countries(where: $where) { + edges { + node { + id + objectId + companies { + edges { + node { + id + objectId + name } } } } } } - `, - variables: { - where: { - companies: { - have: { - OR: [ - { name: { equalTo: 'imACompany1' } }, - { name: { equalTo: 'imACompany2' } }, - ], - }, + } + `, + variables: { + where: { + companies: { + have: { + OR: [ + { name: { equalTo: 'imACompany1' } }, + { name: { equalTo: 'imACompany2' } }, + ], }, }, }, - }); - expect(result2.length).toEqual(2); + }, + }); + expect(result2.length).toEqual(2); - const { - data: { - countries: { edges: result3 }, - }, - } = await apolloClient.query({ - query: gql` - query findCountry($where: CountryWhereInput) { - countries(where: $where) { - edges { - node { - id - name - } + const { + data: { + countries: { edges: result3 }, + }, + } = await apolloClient.query({ + query: gql` + query findCountry($where: CountryWhereInput) { + countries(where: $where) { + edges { + node { + id + name } } } - `, - variables: { - where: { - companies: { exists: false }, - }, + } + `, + variables: { + where: { + companies: { exists: false }, }, - }); - expect(result3.length).toEqual(1); - expect(result3[0].node.name).toEqual('imACountry3'); + }, + }); + expect(result3.length).toEqual(1); + expect(result3[0].node.name).toEqual('imACountry3'); - const { - data: { - countries: { edges: result4 }, - }, - } = await apolloClient.query({ - query: gql` - query findCountry($where: CountryWhereInput) { - countries(where: $where) { - edges { - node { - id - name - } + const { + data: { + countries: { edges: result4 }, + }, + } = await apolloClient.query({ + query: gql` + query findCountry($where: CountryWhereInput) { + countries(where: $where) { + edges { + node { + id + name } } } - `, - variables: { - where: { - president: { exists: false }, - }, + } + `, + variables: { + where: { + president: { exists: false }, }, - }); - expect(result4.length).toEqual(2); - const { - data: { - countries: { edges: result5 }, - }, - } = await apolloClient.query({ - query: gql` - query findCountry($where: CountryWhereInput) { - countries(where: $where) { - edges { - node { - id - name - } + }, + }); + expect(result4.length).toEqual(2); + const { + data: { + countries: { edges: result5 }, + }, + } = await apolloClient.query({ + query: gql` + query findCountry($where: CountryWhereInput) { + countries(where: $where) { + edges { + node { + id + name } } } - `, - variables: { - where: { - president: { exists: true }, - }, + } + `, + variables: { + where: { + president: { exists: true }, }, - }); - expect(result5.length).toEqual(1); - const { - data: { - countries: { edges: result6 }, - }, - } = await apolloClient.query({ - query: gql` - query findCountry($where: CountryWhereInput) { - countries(where: $where) { - edges { - node { - id - objectId - name - } + }, + }); + expect(result5.length).toEqual(1); + const { + data: { + countries: { edges: result6 }, + }, + } = await apolloClient.query({ + query: gql` + query findCountry($where: CountryWhereInput) { + countries(where: $where) { + edges { + node { + id + objectId + name } } } - `, - variables: { - where: { - companies: { - haveNot: { - OR: [ - { name: { equalTo: 'imACompany1' } }, - { name: { equalTo: 'imACompany2' } }, - ], - }, + } + `, + variables: { + where: { + companies: { + haveNot: { + OR: [ + { name: { equalTo: 'imACompany1' } }, + { name: { equalTo: 'imACompany2' } }, + ], }, }, }, - }); - expect(result6.length).toEqual(1); - expect(result6.length).toEqual(1); - expect(result6[0].node.name).toEqual('imACountry3'); - } - ); + }, + }); + expect(result6.length).toEqual(1); + expect(result6.length).toEqual(1); + expect(result6[0].node.name).toEqual('imACountry3'); + }); it('should support files', async () => { try { @@ -9385,10 +8815,7 @@ describe('ParseGraphQLServer', () => { }, }) ); - body.append( - 'map', - JSON.stringify({ 1: ['variables.input.upload'] }) - ); + body.append('map', JSON.stringify({ 1: ['variables.input.upload'] })); body.append('1', 'My File Content', { filename: 'myFileName.txt', contentType: 'text/plain', @@ -9417,9 +8844,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -9502,10 +8927,7 @@ describe('ParseGraphQLServer', () => { }, }) ); - body2.append( - 'map', - JSON.stringify({ 1: ['variables.fields3.someField.upload'] }) - ); + body2.append('map', JSON.stringify({ 1: ['variables.fields3.someField.upload'] })); body2.append('1', 'My File Content', { filename: 'myFileName.txt', contentType: 'text/plain', @@ -9518,24 +8940,24 @@ describe('ParseGraphQLServer', () => { }); expect(res.status).toEqual(200); const result2 = JSON.parse(await res.text()); - expect( - result2.data.createSomeClass1.someClass.someField.name - ).toEqual(jasmine.stringMatching(/_myFileName.txt$/)); - expect( - result2.data.createSomeClass1.someClass.someField.url - ).toEqual(jasmine.stringMatching(/_myFileName.txt$/)); - expect( - result2.data.createSomeClass2.someClass.someField.name - ).toEqual(jasmine.stringMatching(/_myFileName.txt$/)); - expect( - result2.data.createSomeClass2.someClass.someField.url - ).toEqual(jasmine.stringMatching(/_myFileName.txt$/)); - expect( - result2.data.createSomeClass3.someClass.someField.name - ).toEqual(jasmine.stringMatching(/_myFileName.txt$/)); - expect( - result2.data.createSomeClass3.someClass.someField.url - ).toEqual(jasmine.stringMatching(/_myFileName.txt$/)); + expect(result2.data.createSomeClass1.someClass.someField.name).toEqual( + jasmine.stringMatching(/_myFileName.txt$/) + ); + expect(result2.data.createSomeClass1.someClass.someField.url).toEqual( + jasmine.stringMatching(/_myFileName.txt$/) + ); + expect(result2.data.createSomeClass2.someClass.someField.name).toEqual( + jasmine.stringMatching(/_myFileName.txt$/) + ); + expect(result2.data.createSomeClass2.someClass.someField.url).toEqual( + jasmine.stringMatching(/_myFileName.txt$/) + ); + expect(result2.data.createSomeClass3.someClass.someField.name).toEqual( + jasmine.stringMatching(/_myFileName.txt$/) + ); + expect(result2.data.createSomeClass3.someClass.someField.url).toEqual( + jasmine.stringMatching(/_myFileName.txt$/) + ); const schema = await new Parse.Schema('SomeClass').get(); expect(schema.fields.someField.type).toEqual('File'); @@ -9549,9 +8971,7 @@ describe('ParseGraphQLServer', () => { url } } - findSomeClass1: someClasses( - where: { someField: { exists: true } } - ) { + findSomeClass1: someClasses(where: { someField: { exists: true } }) { edges { node { someField { @@ -9561,9 +8981,7 @@ describe('ParseGraphQLServer', () => { } } } - findSomeClass2: someClasses( - where: { someField: { exists: true } } - ) { + findSomeClass2: someClasses(where: { someField: { exists: true } }) { edges { node { someField { @@ -9598,9 +9016,7 @@ describe('ParseGraphQLServer', () => { const mutationResult = await apolloClient.mutate({ mutation: gql` mutation UnlinkFile($id: ID!) { - updateSomeClass( - input: { id: $id, fields: { someField: { file: null } } } - ) { + updateSomeClass(input: { id: $id, fields: { someField: { file: null } } }) { someClass { someField { name @@ -9614,9 +9030,7 @@ describe('ParseGraphQLServer', () => { id: result2.data.createSomeClass3.someClass.id, }, }); - expect( - mutationResult.data.updateSomeClass.someClass.someField - ).toEqual(null); + expect(mutationResult.data.updateSomeClass.someClass.someField).toEqual(null); } catch (e) { handleError(e); } @@ -9632,9 +9046,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -9834,12 +9246,10 @@ describe('ParseGraphQLServer', () => { const { edges } = someClasses; expect(edges.length).toEqual(2); expect( - edges.find(result => result.node.id === create1.someClass.id).node - .someField + edges.find(result => result.node.id === create1.someClass.id).node.someField ).toEqual(someFieldValue); expect( - edges.find(result => result.node.id === create2.someClass.id).node - .someField + edges.find(result => result.node.id === create2.someClass.id).node.someField ).toEqual(someFieldValue2); } catch (e) { handleError(e); @@ -9848,20 +9258,12 @@ describe('ParseGraphQLServer', () => { it('should support array values', async () => { try { - const someFieldValue = [ - 1, - 'foo', - ['bar'], - { lorem: 'ipsum' }, - true, - ]; + const someFieldValue = [1, 'foo', ['bar'], { lorem: 'ipsum' }, true]; await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -9931,9 +9333,7 @@ describe('ParseGraphQLServer', () => { const { someField } = getResult.data.someClass; expect(Array.isArray(someField)).toBeTruthy(); - expect(someField.map(element => element.value)).toEqual( - someFieldValue - ); + expect(someField.map(element => element.value)).toEqual(someFieldValue); expect(getResult.data.someClasses.edges.length).toEqual(1); } catch (e) { handleError(e); @@ -9979,10 +9379,7 @@ describe('ParseGraphQLServer', () => { input: { name: "SomeClass" schemaFields: { - addStrings: [ - { name: "someStringField" } - { name: "someNullField" } - ] + addStrings: [{ name: "someStringField" }, { name: "someNullField" }] addNumbers: [{ name: "someNumberField" }] addBooleans: [{ name: "someBooleanField" }] addObjects: [{ name: "someObjectField" }] @@ -10025,10 +9422,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` - mutation UpdateSomeObject( - $id: ID! - $fields: UpdateSomeClassFieldsInput - ) { + mutation UpdateSomeObject($id: ID!, $fields: UpdateSomeClassFieldsInput) { updateSomeClass(input: { id: $id, fields: $fields }) { clientMutationId } @@ -10067,9 +9461,7 @@ describe('ParseGraphQLServer', () => { expect(getResult.data.someClass.someNumberField).toBeFalsy(); expect(getResult.data.someClass.someBooleanField).toBeFalsy(); expect(getResult.data.someClass.someObjectField).toBeFalsy(); - expect(getResult.data.someClass.someNullField).toEqual( - 'now it has a string' - ); + expect(getResult.data.someClass.someNullField).toEqual('now it has a string'); } catch (e) { handleError(e); } @@ -10082,9 +9474,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -10112,16 +9502,12 @@ describe('ParseGraphQLServer', () => { $fields1: CreateSomeClassFieldsInput $fields2: CreateSomeClassFieldsInput ) { - createSomeClass1: createSomeClass( - input: { fields: $fields1 } - ) { + createSomeClass1: createSomeClass(input: { fields: $fields1 }) { someClass { id } } - createSomeClass2: createSomeClass( - input: { fields: $fields2 } - ) { + createSomeClass2: createSomeClass(input: { fields: $fields2 }) { someClass { id } @@ -10144,9 +9530,7 @@ describe('ParseGraphQLServer', () => { someClass(id: $id) { someField } - someClasses( - where: { someField: { equalTo: $someFieldValue } } - ) { + someClasses(where: { someField: { equalTo: $someFieldValue } }) { edges { node { id @@ -10181,9 +9565,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -10261,12 +9643,7 @@ describe('ParseGraphQLServer', () => { query GeoQuery($latitude: Float!, $longitude: Float!) { nearSphere: someClasses( where: { - someField: { - nearSphere: { - latitude: $latitude - longitude: $longitude - } - } + someField: { nearSphere: { latitude: $latitude, longitude: $longitude } } } ) { edges { @@ -10281,10 +9658,7 @@ describe('ParseGraphQLServer', () => { geoWithin: { centerSphere: { distance: 10 - center: { - latitude: $latitude - longitude: $longitude - } + center: { latitude: $latitude, longitude: $longitude } } } } @@ -10301,14 +9675,8 @@ describe('ParseGraphQLServer', () => { someField: { within: { box: { - bottomLeft: { - latitude: $latitude - longitude: $longitude - } - upperRight: { - latitude: $latitude - longitude: $longitude - } + bottomLeft: { latitude: $latitude, longitude: $longitude } + upperRight: { latitude: $latitude, longitude: $longitude } } } } @@ -10356,9 +9724,7 @@ describe('ParseGraphQLServer', () => { await apolloClient.mutate({ mutation: gql` mutation CreateClass($schemaFields: SchemaFieldsInput) { - createClass( - input: { name: "SomeClass", schemaFields: $schemaFields } - ) { + createClass(input: { name: "SomeClass", schemaFields: $schemaFields }) { clientMutationId } } @@ -10424,9 +9790,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect(typeof getResult.data.someClass.somePolygonField).toEqual( - 'object' - ); + expect(typeof getResult.data.someClass.somePolygonField).toEqual('object'); expect(getResult.data.someClass.somePolygonField).toEqual( somePolygonFieldValue.map(geoPoint => ({ ...geoPoint, @@ -10437,11 +9801,7 @@ describe('ParseGraphQLServer', () => { const getIntersect = await apolloClient.query({ query: gql` query IntersectQuery($point: GeoPointInput!) { - someClasses( - where: { - somePolygonField: { geoIntersects: { point: $point } } - } - ) { + someClasses(where: { somePolygonField: { geoIntersects: { point: $point } } }) { edges { node { id @@ -10515,9 +9875,7 @@ describe('ParseGraphQLServer', () => { }, }); - expect(getResult.data.someClass.someField).toEqual( - someFieldValue.base64 - ); + expect(getResult.data.someClass.someField).toEqual(someFieldValue.base64); const updatedSomeFieldValue = { __type: 'Bytes', @@ -10526,10 +9884,7 @@ describe('ParseGraphQLServer', () => { const updatedResult = await apolloClient.mutate({ mutation: gql` - mutation UpdateSomeObject( - $id: ID! - $fields: UpdateSomeClassFieldsInput - ) { + mutation UpdateSomeObject($id: ID!, $fields: UpdateSomeClassFieldsInput) { updateSomeClass(input: { id: $id, fields: $fields }) { someClass { updatedAt @@ -10570,9 +9925,7 @@ describe('ParseGraphQLServer', () => { }); const findResults = findResult.data.someClasses.edges; expect(findResults.length).toBe(1); - expect(findResults[0].node.id).toBe( - createResult.data.createSomeClass.someClass.id - ); + expect(findResults[0].node.id).toBe(createResult.data.createSomeClass.someClass.id); }); }); @@ -10744,9 +10097,7 @@ describe('ParseGraphQLServer', () => { `, }); parseGraphQLServer.applyGraphQL(expressApp); - await new Promise(resolve => - httpServer.listen({ port: 13377 }, resolve) - ); + await new Promise(resolve => httpServer.listen({ port: 13377 }, resolve)); const httpLink = createUploadLink({ uri: 'http://localhost:13377/graphql', fetch, @@ -10930,9 +10281,7 @@ describe('ParseGraphQLServer', () => { }); parseGraphQLServer.applyGraphQL(expressApp); - await new Promise(resolve => - httpServer.listen({ port: 13377 }, resolve) - ); + await new Promise(resolve => httpServer.listen({ port: 13377 }, resolve)); const httpLink = createUploadLink({ uri: 'http://localhost:13377/graphql', fetch, @@ -10982,13 +10331,9 @@ describe('ParseGraphQLServer', () => { } `, }); - expect(result.data.customQueryWithAutoTypeReturn.objectId).toEqual( - obj.id - ); + expect(result.data.customQueryWithAutoTypeReturn.objectId).toEqual(obj.id); expect(result.data.customQueryWithAutoTypeReturn.name).toEqual('aname'); - expect(result.data.customQueryWithAutoTypeReturn.nameUpperCase).toEqual( - 'ANAME' - ); + expect(result.data.customQueryWithAutoTypeReturn.nameUpperCase).toEqual('ANAME'); expect(result.data.customQueryWithAutoTypeReturn.type).toEqual('robot'); }); @@ -11029,9 +10374,7 @@ describe('ParseGraphQLServer', () => { variables: { id: obj.id, name: 'anewname', type: 'human' }, mutation: gql` mutation someClass($id: ID!, $name: String!, $type: TypeEnum!) { - updateSomeClass( - input: { id: $id, fields: { name: $name, type: $type } } - ) { + updateSomeClass(input: { id: $id, fields: { name: $name, type: $type } }) { someClass { nameUpperCase type @@ -11040,9 +10383,7 @@ describe('ParseGraphQLServer', () => { } `, }); - expect(result3.data.updateSomeClass.someClass.nameUpperCase).toEqual( - 'ANEWNAME' - ); + expect(result3.data.updateSomeClass.someClass.nameUpperCase).toEqual('ANEWNAME'); expect(result3.data.updateSomeClass.someClass.type).toEqual('human'); }); }); @@ -11064,9 +10405,7 @@ describe('ParseGraphQLServer', () => { }); parseGraphQLServer.applyGraphQL(expressApp); - await new Promise(resolve => - httpServer.listen({ port: 13377 }, resolve) - ); + await new Promise(resolve => httpServer.listen({ port: 13377 }, resolve)); const httpLink = createUploadLink({ uri: 'http://localhost:13377/graphql', fetch, diff --git a/spec/ParseHooks.spec.js b/spec/ParseHooks.spec.js index b3f45fc1..de2918ba 100644 --- a/spec/ParseHooks.spec.js +++ b/spec/ParseHooks.spec.js @@ -63,10 +63,7 @@ describe('Hooks', () => { .then(response => { expect(response.objectId).toBeUndefined(); expect(response.url).toBe('http://someurl'); - return Parse.Hooks.updateFunction( - 'My-Test-Function', - 'http://anotherurl' - ); + return Parse.Hooks.updateFunction('My-Test-Function', 'http://anotherurl'); }) .then(res => { expect(res.objectId).toBeUndefined(); @@ -86,9 +83,7 @@ describe('Hooks', () => { }, err => { expect(err.code).toBe(143); - expect(err.message).toBe( - 'no function named: My-Test-Function is defined' - ); + expect(err.message).toBe('no function named: My-Test-Function is defined'); done(); return Promise.resolve(); } @@ -123,11 +118,7 @@ describe('Hooks', () => { expect(res.objectId).toBeUndefined(); expect(res.url).toBe('http://someurl'); // delete - return Parse.Hooks.updateTrigger( - 'MyClass', - 'beforeDelete', - 'http://anotherurl' - ); + return Parse.Hooks.updateTrigger('MyClass', 'beforeDelete', 'http://anotherurl'); }, err => { jfail(err); @@ -158,7 +149,7 @@ describe('Hooks', () => { } ) .then( - function() { + function () { fail('should not succeed'); done(); }, @@ -199,10 +190,7 @@ describe('Hooks', () => { .then(() => new Promise(resolve => setTimeout(resolve, 100))) .then( () => { - return Parse.Hooks.createFunction( - 'my_new_function', - 'http://url.com' - ); + return Parse.Hooks.createFunction('my_new_function', 'http://url.com'); }, () => { fail('should create a new function'); @@ -217,9 +205,7 @@ describe('Hooks', () => { expect(err).not.toBe(null); if (err) { expect(err.code).toBe(143); - expect(err.message).toBe( - 'function name: my_new_function already exits' - ); + expect(err.message).toBe('function name: my_new_function already exits'); } return Parse.Hooks.removeFunction('my_new_function'); } @@ -239,11 +225,7 @@ describe('Hooks', () => { Parse.Hooks.createTrigger('MyClass', 'beforeSave', 'http://url.com') .then( () => { - return Parse.Hooks.createTrigger( - 'MyClass', - 'beforeSave', - 'http://url.com' - ); + return Parse.Hooks.createTrigger('MyClass', 'beforeSave', 'http://url.com'); }, () => { fail('should create a new trigger'); @@ -258,9 +240,7 @@ describe('Hooks', () => { expect(err).not.toBe(null); if (err) { expect(err.code).toBe(143); - expect(err.message).toBe( - 'class MyClass already has trigger beforeSave' - ); + expect(err.message).toBe('class MyClass already has trigger beforeSave'); } return Parse.Hooks.removeTrigger('MyClass', 'beforeSave'); } @@ -287,9 +267,7 @@ describe('Hooks', () => { expect(err).not.toBe(null); if (err) { expect(err.code).toBe(143); - expect(err.message).toBe( - 'no function named: A_COOL_FUNCTION is defined' - ); + expect(err.message).toBe('no function named: A_COOL_FUNCTION is defined'); } return Parse.Hooks.getFunction('A_COOL_FUNCTION'); } @@ -304,9 +282,7 @@ describe('Hooks', () => { expect(err).not.toBe(null); if (err) { expect(err.code).toBe(143); - expect(err.message).toBe( - 'no function named: A_COOL_FUNCTION is defined' - ); + expect(err.message).toBe('no function named: A_COOL_FUNCTION is defined'); } done(); } @@ -384,41 +360,22 @@ describe('Hooks', () => { const promises = []; for (let i = 0; i < 5; i++) { promises.push( - Parse.Hooks.createTrigger( - 'MyClass' + i, - 'beforeSave', - 'http://url.com/beforeSave/' + i - ) - ); - promises.push( - Parse.Hooks.createFunction( - 'AFunction' + i, - 'http://url.com/function' + i - ) + Parse.Hooks.createTrigger('MyClass' + i, 'beforeSave', 'http://url.com/beforeSave/' + i) ); + promises.push(Parse.Hooks.createFunction('AFunction' + i, 'http://url.com/function' + i)); } Promise.all(promises) .then( - function() { + function () { for (let i = 0; i < 5; i++) { // Delete everything from memory, as the server just started - triggers.removeTrigger( - 'beforeSave', - 'MyClass' + i, - Parse.applicationId - ); + triggers.removeTrigger('beforeSave', 'MyClass' + i, Parse.applicationId); triggers.removeFunction('AFunction' + i, Parse.applicationId); expect( - triggers.getTrigger( - 'MyClass' + i, - 'beforeSave', - Parse.applicationId - ) - ).toBeUndefined(); - expect( - triggers.getFunction('AFunction' + i, Parse.applicationId) + triggers.getTrigger('MyClass' + i, 'beforeSave', Parse.applicationId) ).toBeUndefined(); + expect(triggers.getFunction('AFunction' + i, Parse.applicationId)).toBeUndefined(); } const hooksController = new HooksController( Parse.applicationId, @@ -433,18 +390,12 @@ describe('Hooks', () => { } ) .then( - function() { + function () { for (let i = 0; i < 5; i++) { expect( - triggers.getTrigger( - 'MyClass' + i, - 'beforeSave', - Parse.applicationId - ) - ).not.toBeUndefined(); - expect( - triggers.getFunction('AFunction' + i, Parse.applicationId) + triggers.getTrigger('MyClass' + i, 'beforeSave', Parse.applicationId) ).not.toBeUndefined(); + expect(triggers.getFunction('AFunction' + i, Parse.applicationId)).not.toBeUndefined(); } done(); }, @@ -457,16 +408,13 @@ describe('Hooks', () => { }); it('should run the function on the test server', done => { - app.post('/SomeFunction', function(req, res) { + app.post('/SomeFunction', function (req, res) { res.json({ success: 'OK!' }); }); - Parse.Hooks.createFunction( - 'SOME_TEST_FUNCTION', - hookServerURL + '/SomeFunction' - ) + Parse.Hooks.createFunction('SOME_TEST_FUNCTION', hookServerURL + '/SomeFunction') .then( - function() { + function () { return Parse.Cloud.run('SOME_TEST_FUNCTION'); }, err => { @@ -476,7 +424,7 @@ describe('Hooks', () => { } ) .then( - function(res) { + function (res) { expect(res).toBe('OK!'); done(); }, @@ -489,16 +437,13 @@ describe('Hooks', () => { }); it('should run the function on the test server (error handling)', done => { - app.post('/SomeFunctionError', function(req, res) { + app.post('/SomeFunctionError', function (req, res) { res.json({ error: { code: 1337, error: 'hacking that one!' } }); }); // The function is deleted as the DB is dropped between calls - Parse.Hooks.createFunction( - 'SOME_TEST_FUNCTION', - hookServerURL + '/SomeFunctionError' - ) + Parse.Hooks.createFunction('SOME_TEST_FUNCTION', hookServerURL + '/SomeFunctionError') .then( - function() { + function () { return Parse.Cloud.run('SOME_TEST_FUNCTION'); }, err => { @@ -508,7 +453,7 @@ describe('Hooks', () => { } ) .then( - function() { + function () { fail('Should not succeed calling that function'); done(); }, @@ -526,7 +471,7 @@ describe('Hooks', () => { }); it('should provide X-Parse-Webhook-Key when defined', done => { - app.post('/ExpectingKey', function(req, res) { + app.post('/ExpectingKey', function (req, res) { if (req.get('X-Parse-Webhook-Key') === 'hook') { res.json({ success: 'correct key provided' }); } else { @@ -534,12 +479,9 @@ describe('Hooks', () => { } }); - Parse.Hooks.createFunction( - 'SOME_TEST_FUNCTION', - hookServerURL + '/ExpectingKey' - ) + Parse.Hooks.createFunction('SOME_TEST_FUNCTION', hookServerURL + '/ExpectingKey') .then( - function() { + function () { return Parse.Cloud.run('SOME_TEST_FUNCTION'); }, err => { @@ -549,7 +491,7 @@ describe('Hooks', () => { } ) .then( - function(res) { + function (res) { expect(res).toBe('correct key provided'); done(); }, @@ -563,7 +505,7 @@ describe('Hooks', () => { it('should not pass X-Parse-Webhook-Key if not provided', done => { reconfigureServer({ webhookKey: undefined }).then(() => { - app.post('/ExpectingKeyAlso', function(req, res) { + app.post('/ExpectingKeyAlso', function (req, res) { if (req.get('X-Parse-Webhook-Key') === 'hook') { res.json({ success: 'correct key provided' }); } else { @@ -571,12 +513,9 @@ describe('Hooks', () => { } }); - Parse.Hooks.createFunction( - 'SOME_TEST_FUNCTION', - hookServerURL + '/ExpectingKeyAlso' - ) + Parse.Hooks.createFunction('SOME_TEST_FUNCTION', hookServerURL + '/ExpectingKeyAlso') .then( - function() { + function () { return Parse.Cloud.run('SOME_TEST_FUNCTION'); }, err => { @@ -586,7 +525,7 @@ describe('Hooks', () => { } ) .then( - function() { + function () { fail('Should not succeed calling that function'); done(); }, @@ -605,7 +544,7 @@ describe('Hooks', () => { it('should run the beforeSave hook on the test server', done => { let triggerCount = 0; - app.post('/BeforeSaveSome', function(req, res) { + app.post('/BeforeSaveSome', function (req, res) { triggerCount++; const object = req.body.object; object.hello = 'world'; @@ -614,20 +553,16 @@ describe('Hooks', () => { res.json({ success: object }); }); // The function is deleted as the DB is dropped between calls - Parse.Hooks.createTrigger( - 'SomeRandomObject', - 'beforeSave', - hookServerURL + '/BeforeSaveSome' - ) - .then(function() { + Parse.Hooks.createTrigger('SomeRandomObject', 'beforeSave', hookServerURL + '/BeforeSaveSome') + .then(function () { const obj = new Parse.Object('SomeRandomObject'); return obj.save(); }) - .then(function(res) { + .then(function (res) { expect(triggerCount).toBe(1); return res.fetch(); }) - .then(function(res) { + .then(function (res) { expect(res.get('hello')).toEqual('world'); done(); }) @@ -639,24 +574,20 @@ describe('Hooks', () => { }); it('beforeSave hooks should correctly handle responses containing entire object', done => { - app.post('/BeforeSaveSome2', function(req, res) { + app.post('/BeforeSaveSome2', function (req, res) { const object = Parse.Object.fromJSON(req.body.object); object.set('hello', 'world'); res.json({ success: object }); }); - Parse.Hooks.createTrigger( - 'SomeRandomObject2', - 'beforeSave', - hookServerURL + '/BeforeSaveSome2' - ) - .then(function() { + Parse.Hooks.createTrigger('SomeRandomObject2', 'beforeSave', hookServerURL + '/BeforeSaveSome2') + .then(function () { const obj = new Parse.Object('SomeRandomObject2'); return obj.save(); }) - .then(function(res) { + .then(function (res) { return res.save(); }) - .then(function(res) { + .then(function (res) { expect(res.get('hello')).toEqual('world'); done(); }) @@ -669,36 +600,30 @@ describe('Hooks', () => { it('should run the afterSave hook on the test server', done => { let triggerCount = 0; let newObjectId; - app.post('/AfterSaveSome', function(req, res) { + app.post('/AfterSaveSome', function (req, res) { triggerCount++; const obj = new Parse.Object('AnotherObject'); obj.set('foo', 'bar'); - obj.save().then(function(obj) { + obj.save().then(function (obj) { newObjectId = obj.id; res.json({ success: {} }); }); }); // The function is deleted as the DB is dropped between calls - Parse.Hooks.createTrigger( - 'SomeRandomObject', - 'afterSave', - hookServerURL + '/AfterSaveSome' - ) - .then(function() { + Parse.Hooks.createTrigger('SomeRandomObject', 'afterSave', hookServerURL + '/AfterSaveSome') + .then(function () { const obj = new Parse.Object('SomeRandomObject'); return obj.save(); }) - .then(function() { + .then(function () { return new Promise(resolve => { setTimeout(() => { expect(triggerCount).toBe(1); - new Parse.Query('AnotherObject') - .get(newObjectId) - .then(r => resolve(r)); + new Parse.Query('AnotherObject').get(newObjectId).then(r => resolve(r)); }, 500); }); }) - .then(function(res) { + .then(function (res) { expect(res.get('foo')).toEqual('bar'); done(); }) diff --git a/spec/ParseInstallation.spec.js b/spec/ParseInstallation.spec.js index 920a28bf..b11f1337 100644 --- a/spec/ParseInstallation.spec.js +++ b/spec/ParseInstallation.spec.js @@ -10,19 +10,14 @@ const request = require('../lib/request'); let config; let database; -const defaultColumns = require('../lib/Controllers/SchemaController') - .defaultColumns; +const defaultColumns = require('../lib/Controllers/SchemaController').defaultColumns; const delay = function delay(delay) { return new Promise(resolve => setTimeout(resolve, delay)); }; const installationSchema = { - fields: Object.assign( - {}, - defaultColumns._Default, - defaultColumns._Installation - ), + fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation), }; describe('Installations', () => { @@ -40,9 +35,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); const obj = results[0]; @@ -58,8 +51,7 @@ describe('Installations', () => { }); it('creates an ios installation with ids', done => { - const t = - '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const device = 'ios'; const input = { deviceToken: t, @@ -67,9 +59,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); const obj = results[0]; @@ -93,9 +83,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); const obj = results[0]; @@ -120,9 +108,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); const obj = results[0]; @@ -142,8 +128,7 @@ describe('Installations', () => { }); it('creates an ios installation with all fields', done => { - const t = - '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const device = 'ios'; const input = { deviceToken: t, @@ -152,9 +137,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); const obj = results[0]; @@ -261,8 +244,7 @@ describe('Installations', () => { }); it('creates an object with custom fields', done => { - const t = - '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const input = { deviceToken: t, deviceType: 'ios', @@ -271,9 +253,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); const obj = results[0]; @@ -289,8 +269,7 @@ describe('Installations', () => { it('merging when installationId already exists', done => { const installId1 = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; const input = { deviceToken: t, deviceType: 'ios', @@ -301,9 +280,7 @@ describe('Installations', () => { let secondObject; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); firstObject = results[0]; @@ -312,9 +289,7 @@ describe('Installations', () => { input['foo'] = 'bar'; return rest.create(config, auth.nobody(config), '_Installation', input); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); secondObject = results[0]; @@ -330,8 +305,7 @@ describe('Installations', () => { it('merging when two objects both only have one id', done => { const installId = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const input1 = { installationId: installId, deviceType: 'ios', @@ -349,22 +323,13 @@ describe('Installations', () => { let secondObject; rest .create(config, auth.nobody(config), '_Installation', input1) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); firstObject = results[0]; - return rest.create( - config, - auth.nobody(config), - '_Installation', - input2 - ); + return rest.create(config, auth.nobody(config), '_Installation', input2); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(2); if (results[0]['_id'] == firstObject._id) { @@ -372,16 +337,9 @@ describe('Installations', () => { } else { secondObject = results[0]; } - return rest.create( - config, - auth.nobody(config), - '_Installation', - input3 - ); + return rest.create(config, auth.nobody(config), '_Installation', input3); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0]['_id']).toEqual(secondObject._id); @@ -397,8 +355,7 @@ describe('Installations', () => { const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; const installId3 = '33333333-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const input = { installationId: installId1, deviceType: 'ios', @@ -457,26 +414,16 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); const objectId = results[0].objectId; const update = { channels: ['baz'], }; - return rest.update( - config, - auth.nobody(config), - '_Installation', - { objectId }, - update - ); + return rest.update(config, auth.nobody(config), '_Installation', { objectId }, update); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0].channels.length).toEqual(1); @@ -499,9 +446,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); input = { installationId: installId2 }; @@ -524,10 +469,8 @@ describe('Installations', () => { }); it('update ios fails with new deviceToken and no installationId', done => { - const a = - '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - const b = - '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const a = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const b = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; let input = { deviceToken: a, deviceType: 'ios', @@ -535,9 +478,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); input = { deviceToken: b }; @@ -560,10 +501,8 @@ describe('Installations', () => { it('update ios updates device token', done => { const installId = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; - const u = - '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const t = '11433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; + const u = '91433856eed2f1285fb3aa11136718c1198ed5647875096952c66bf8cb976306'; let input = { installationId: installId, deviceType: 'ios', @@ -572,9 +511,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); input = { @@ -590,9 +527,7 @@ describe('Installations', () => { input ); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0].deviceToken).toEqual(u); @@ -613,9 +548,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); input = { @@ -648,9 +581,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); input = { @@ -664,9 +595,7 @@ describe('Installations', () => { input ); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0]['custom']).toEqual('allowed'); @@ -677,8 +606,7 @@ describe('Installations', () => { it('update android device token with duplicate device token', async () => { const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; let input = { installationId: installId1, @@ -737,8 +665,7 @@ describe('Installations', () => { it('update ios device token with duplicate device token', done => { const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; let input = { installationId: installId1, deviceToken: t, @@ -816,8 +743,7 @@ describe('Installations', () => { xit('update ios device token with duplicate token different app', done => { const installId1 = '11111111-abcd-abcd-abcd-123456789abc'; const installId2 = '22222222-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const input = { installationId: installId1, deviceToken: t, @@ -831,9 +757,7 @@ describe('Installations', () => { input.appIdentifier = 'bar'; return rest.create(config, auth.nobody(config), '_Installation', input); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { // The first object should have been deleted during merge expect(results.length).toEqual(1); @@ -848,17 +772,14 @@ describe('Installations', () => { it('update ios token and channels', done => { const installId = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; let input = { installationId: installId, deviceType: 'ios', }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); input = { @@ -873,9 +794,7 @@ describe('Installations', () => { input ); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0].installationId).toEqual(installId); @@ -891,8 +810,7 @@ describe('Installations', () => { it('update ios linking two existing objects', done => { const installId = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; let input = { installationId: installId, deviceType: 'ios', @@ -907,12 +825,7 @@ describe('Installations', () => { return rest.create(config, auth.nobody(config), '_Installation', input); }) .then(() => - database.adapter.find( - '_Installation', - installationSchema, - { deviceToken: t }, - {} - ) + database.adapter.find('_Installation', installationSchema, { deviceToken: t }, {}) ) .then(results => { expect(results.length).toEqual(1); @@ -929,9 +842,7 @@ describe('Installations', () => { input ); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0].installationId).toEqual(installId); @@ -947,8 +858,7 @@ describe('Installations', () => { it('update is linking two existing objects w/ increment', done => { const installId = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; let input = { installationId: installId, deviceType: 'ios', @@ -963,12 +873,7 @@ describe('Installations', () => { return rest.create(config, auth.nobody(config), '_Installation', input); }) .then(() => - database.adapter.find( - '_Installation', - installationSchema, - { deviceToken: t }, - {} - ) + database.adapter.find('_Installation', installationSchema, { deviceToken: t }, {}) ) .then(results => { expect(results.length).toEqual(1); @@ -989,9 +894,7 @@ describe('Installations', () => { input ); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0].installationId).toEqual(installId); @@ -1008,8 +911,7 @@ describe('Installations', () => { it('update is linking two existing with installation id', done => { const installId = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; let input = { installationId: installId, deviceType: 'ios', @@ -1018,9 +920,7 @@ describe('Installations', () => { let tokenObj; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); installObj = results[0]; @@ -1031,12 +931,7 @@ describe('Installations', () => { return rest.create(config, auth.nobody(config), '_Installation', input); }) .then(() => - database.adapter.find( - '_Installation', - installationSchema, - { deviceToken: t }, - {} - ) + database.adapter.find('_Installation', installationSchema, { deviceToken: t }, {}) ) .then(results => { expect(results.length).toEqual(1); @@ -1076,8 +971,7 @@ describe('Installations', () => { it('update is linking two existing with installation id w/ op', done => { const installId = '12345678-abcd-abcd-abcd-123456789abc'; - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; let input = { installationId: installId, deviceType: 'ios', @@ -1086,9 +980,7 @@ describe('Installations', () => { let tokenObj; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); installObj = results[0]; @@ -1099,12 +991,7 @@ describe('Installations', () => { return rest.create(config, auth.nobody(config), '_Installation', input); }) .then(() => - database.adapter.find( - '_Installation', - installationSchema, - { deviceToken: t }, - {} - ) + database.adapter.find('_Installation', installationSchema, { deviceToken: t }, {}) ) .then(results => { expect(results.length).toEqual(1); @@ -1158,8 +1045,7 @@ describe('Installations', () => { // imported installation, then we should reuse the existing installation // object in case the developer already added additional fields via Data // Browser or REST API (e.g. channel targeting info). - const t = - '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const t = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; const installId = '12345678-abcd-abcd-abcd-123456789abc'; let input = { deviceToken: t, @@ -1167,9 +1053,7 @@ describe('Installations', () => { }; rest .create(config, auth.nobody(config), '_Installation', input) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); input = { @@ -1179,9 +1063,7 @@ describe('Installations', () => { }; return rest.create(config, auth.nobody(config), '_Installation', input); }) - .then(() => - database.adapter.find('_Installation', installationSchema, {}, {}) - ) + .then(() => database.adapter.find('_Installation', installationSchema, {}, {})) .then(results => { expect(results.length).toEqual(1); expect(results[0].deviceToken).toEqual(t); @@ -1211,9 +1093,7 @@ describe('Installations', () => { }; return request({ headers: headers, - url: - 'http://localhost:8378/1/installations/' + - createResult.response.objectId, + url: 'http://localhost:8378/1/installations/' + createResult.response.objectId, }).then(response => { const body = response.data; expect(body.objectId).toEqual(createResult.response.objectId); @@ -1299,31 +1179,29 @@ describe('Installations', () => { installationId: installId, deviceType: device, }; - rest - .create(config, auth.nobody(config), '_Installation', input) - .then(() => { - const query = new Parse.Query(Parse.Installation); - query.equalTo('installationId', installId); - query - .first({ useMasterKey: true }) - .then(installation => { - return installation.save( - { - key: 'value', - }, - { useMasterKey: true } - ); - }) - .then( - () => { - done(); + rest.create(config, auth.nobody(config), '_Installation', input).then(() => { + const query = new Parse.Query(Parse.Installation); + query.equalTo('installationId', installId); + query + .first({ useMasterKey: true }) + .then(installation => { + return installation.save( + { + key: 'value', }, - err => { - jfail(err); - done(); - } + { useMasterKey: true } ); - }); + }) + .then( + () => { + done(); + }, + err => { + jfail(err); + done(); + } + ); + }); }); it('should properly reject updating installationId', done => { @@ -1333,36 +1211,32 @@ describe('Installations', () => { installationId: installId, deviceType: device, }; - rest - .create(config, auth.nobody(config), '_Installation', input) - .then(() => { - const query = new Parse.Query(Parse.Installation); - query.equalTo('installationId', installId); - query - .first({ useMasterKey: true }) - .then(installation => { - return installation.save( - { - key: 'value', - installationId: '22222222-abcd-abcd-abcd-123456789abc', - }, - { useMasterKey: true } - ); - }) - .then( - () => { - fail('should not succeed'); - done(); + rest.create(config, auth.nobody(config), '_Installation', input).then(() => { + const query = new Parse.Query(Parse.Installation); + query.equalTo('installationId', installId); + query + .first({ useMasterKey: true }) + .then(installation => { + return installation.save( + { + key: 'value', + installationId: '22222222-abcd-abcd-abcd-123456789abc', }, - err => { - expect(err.code).toBe(136); - expect(err.message).toBe( - 'installationId may not be changed in this operation' - ); - done(); - } + { useMasterKey: true } ); - }); + }) + .then( + () => { + fail('should not succeed'); + done(); + }, + err => { + expect(err.code).toBe(136); + expect(err.message).toBe('installationId may not be changed in this operation'); + done(); + } + ); + }); }); // TODO: Look at additional tests from installation_collection_test.go:882 diff --git a/spec/ParseLiveQuery.spec.js b/spec/ParseLiveQuery.spec.js index cb43b32d..870e0552 100644 --- a/spec/ParseLiveQuery.spec.js +++ b/spec/ParseLiveQuery.spec.js @@ -1,6 +1,5 @@ 'use strict'; -const UserController = require('../lib/Controllers/UserController') - .UserController; +const UserController = require('../lib/Controllers/UserController').UserController; const Config = require('../lib/Config'); const validatorFail = () => { throw 'you are not authorized'; @@ -855,10 +854,7 @@ describe('ParseLiveQuery', function () { const userController = new UserController(emailAdapter, 'test', { verifyUserEmails: true, }); - userController.verifyEmail( - foundUser.username, - foundUser._email_verify_token - ); + userController.verifyEmail(foundUser.username, foundUser._email_verify_token); }); }); }); diff --git a/spec/ParseLiveQueryServer.spec.js b/spec/ParseLiveQueryServer.spec.js index 6c1b831a..66fae587 100644 --- a/spec/ParseLiveQueryServer.spec.js +++ b/spec/ParseLiveQueryServer.spec.js @@ -1,9 +1,7 @@ const Parse = require('parse/node'); -const ParseLiveQueryServer = require('../lib/LiveQuery/ParseLiveQueryServer') - .ParseLiveQueryServer; +const ParseLiveQueryServer = require('../lib/LiveQuery/ParseLiveQueryServer').ParseLiveQueryServer; const ParseServer = require('../lib/ParseServer').default; -const LiveQueryController = require('../lib/Controllers/LiveQueryController') - .LiveQueryController; +const LiveQueryController = require('../lib/Controllers/LiveQueryController').LiveQueryController; const auth = require('../lib/Auth'); // Global mock info @@ -40,33 +38,15 @@ describe('ParseLiveQueryServer', function () { // Mock Subscription const mockSubscriotion = function () { this.addClientSubscription = jasmine.createSpy('addClientSubscription'); - this.deleteClientSubscription = jasmine.createSpy( - 'deleteClientSubscription' - ); + this.deleteClientSubscription = jasmine.createSpy('deleteClientSubscription'); }; - jasmine.mockLibrary( - '../lib/LiveQuery/Subscription', - 'Subscription', - mockSubscriotion - ); + jasmine.mockLibrary('../lib/LiveQuery/Subscription', 'Subscription', mockSubscriotion); // Mock queryHash - const mockQueryHash = jasmine - .createSpy('matchesQuery') - .and.returnValue(queryHashValue); - jasmine.mockLibrary( - '../lib/LiveQuery/QueryTools', - 'queryHash', - mockQueryHash - ); + const mockQueryHash = jasmine.createSpy('matchesQuery').and.returnValue(queryHashValue); + jasmine.mockLibrary('../lib/LiveQuery/QueryTools', 'queryHash', mockQueryHash); // Mock matchesQuery - const mockMatchesQuery = jasmine - .createSpy('matchesQuery') - .and.returnValue(true); - jasmine.mockLibrary( - '../lib/LiveQuery/QueryTools', - 'matchesQuery', - mockMatchesQuery - ); + const mockMatchesQuery = jasmine.createSpy('matchesQuery').and.returnValue(true); + jasmine.mockLibrary('../lib/LiveQuery/QueryTools', 'matchesQuery', mockMatchesQuery); // Mock ParsePubSub const mockParsePubSub = { createPublisher: function () { @@ -82,35 +62,24 @@ describe('ParseLiveQueryServer', function () { }; }, }; - jasmine.mockLibrary( - '../lib/LiveQuery/ParsePubSub', - 'ParsePubSub', - mockParsePubSub - ); - spyOn(auth, 'getAuthForSessionToken').and.callFake( - ({ sessionToken, cacheController }) => { - if (typeof sessionToken === 'undefined') { - return Promise.reject(); - } - if (sessionToken === null) { - return Promise.reject(); - } - if (sessionToken === 'pleaseThrow') { - return Promise.reject(); - } - if (sessionToken === 'invalid') { - return Promise.reject( - new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'invalid session token' - ) - ); - } - return Promise.resolve( - new auth.Auth({ cacheController, user: { id: testUserId } }) + jasmine.mockLibrary('../lib/LiveQuery/ParsePubSub', 'ParsePubSub', mockParsePubSub); + spyOn(auth, 'getAuthForSessionToken').and.callFake(({ sessionToken, cacheController }) => { + if (typeof sessionToken === 'undefined') { + return Promise.reject(); + } + if (sessionToken === null) { + return Promise.reject(); + } + if (sessionToken === 'pleaseThrow') { + return Promise.reject(); + } + if (sessionToken === 'invalid') { + return Promise.reject( + new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token') ); } - ); + return Promise.resolve(new auth.Auth({ cacheController, user: { id: testUserId } })); + }); done(); }); @@ -125,10 +94,7 @@ describe('ParseLiveQueryServer', function () { it('can be initialized from ParseServer', function () { const httpServer = {}; - const parseLiveQueryServer = ParseServer.createLiveQueryServer( - httpServer, - {} - ); + const parseLiveQueryServer = ParseServer.createLiveQueryServer(httpServer, {}); expect(parseLiveQueryServer.clientId).toBeUndefined(); expect(parseLiveQueryServer.clients.size).toBe(0); @@ -181,9 +147,7 @@ describe('ParseLiveQueryServer', function () { }, serverStartComplete: () => { expect(parseServer.liveQueryServer).not.toBeUndefined(); - expect(parseServer.liveQueryServer.server).not.toBe( - parseServer.server - ); + expect(parseServer.liveQueryServer.server).not.toBe(parseServer.server); parseServer.liveQueryServer.server.close( parseServer.server.close.bind(parseServer.server, done) ); @@ -234,10 +198,7 @@ describe('ParseLiveQueryServer', function () { }) .then(parseServer => { saveSpy = spyOn(parseServer.config.liveQueryController, 'onAfterSave'); - deleteSpy = spyOn( - parseServer.config.liveQueryController, - 'onAfterDelete' - ); + deleteSpy = spyOn(parseServer.config.liveQueryController, 'onAfterDelete'); return setPermissionsOnClass('Yolo', { create: { '*': true }, delete: { '*': true }, @@ -290,9 +251,7 @@ describe('ParseLiveQueryServer', function () { const parseWebSocket = { clientId: -1, }; - parseLiveQueryServer._validateKeys = jasmine - .createSpy('validateKeys') - .and.returnValue(true); + parseLiveQueryServer._validateKeys = jasmine.createSpy('validateKeys').and.returnValue(true); await parseLiveQueryServer._handleConnect(parseWebSocket, { sessionToken: 'token', }); @@ -396,10 +355,7 @@ describe('ParseLiveQueryServer', function () { // TODO(check subscription constructor to verify we pass the right argument) // Make sure we add clientInfo to the subscription const subscription = classSubscriptions.get('hash'); - expect(subscription.addClientSubscription).toHaveBeenCalledWith( - clientId, - requestId - ); + expect(subscription.addClientSubscription).toHaveBeenCalledWith(clientId, requestId); // Make sure we add subscriptionInfo to the client const args = client.addSubscriptionInfo.calls.first().args; expect(args[0]).toBe(requestId); @@ -428,13 +384,7 @@ describe('ParseLiveQueryServer', function () { }, fields: ['test'], }; - await addMockSubscription( - parseLiveQueryServer, - clientId, - requestId, - parseWebSocket, - query - ); + await addMockSubscription(parseLiveQueryServer, clientId, requestId, parseWebSocket, query); // Add subscription for mock client 2 const parseWebSocketAgain = { clientId: clientIdAgain, @@ -525,8 +475,7 @@ describe('ParseLiveQueryServer', function () { parseWebSocket ); // Mock client.getSubscriptionInfo - const subscriptionInfo = client.addSubscriptionInfo.calls.mostRecent() - .args[1]; + const subscriptionInfo = client.addSubscriptionInfo.calls.mostRecent().args[1]; client.getSubscriptionInfo = function () { return subscriptionInfo; }; @@ -539,10 +488,7 @@ describe('ParseLiveQueryServer', function () { // Make sure we delete subscription from client expect(client.deleteSubscriptionInfo).toHaveBeenCalledWith(requestId); // Make sure we delete client from subscription - expect(subscription.deleteClientSubscription).toHaveBeenCalledWith( - clientId, - requestId - ); + expect(subscription.deleteClientSubscription).toHaveBeenCalledWith(clientId, requestId); // Make sure we clear subscription in the server const subscriptions = parseLiveQueryServer.subscriptions; expect(subscriptions.size).toBe(0); @@ -574,9 +520,7 @@ describe('ParseLiveQueryServer', function () { it('can set subscribe command message handler for a parseWebSocket', function () { const parseLiveQueryServer = new ParseLiveQueryServer({}); // Register mock connect/subscribe/unsubscribe handler for the server - parseLiveQueryServer._handleSubscribe = jasmine.createSpy( - '_handleSubscribe' - ); + parseLiveQueryServer._handleSubscribe = jasmine.createSpy('_handleSubscribe'); // Make mock parseWebsocket const EventEmitter = require('events'); const parseWebSocket = new EventEmitter(); @@ -600,9 +544,7 @@ describe('ParseLiveQueryServer', function () { it('can set unsubscribe command message handler for a parseWebSocket', function () { const parseLiveQueryServer = new ParseLiveQueryServer({}); // Register mock connect/subscribe/unsubscribe handler for the server - parseLiveQueryServer._handleUnsubscribe = jasmine.createSpy( - '_handleSubscribe' - ); + parseLiveQueryServer._handleUnsubscribe = jasmine.createSpy('_handleSubscribe'); // Make mock parseWebsocket const EventEmitter = require('events'); const parseWebSocket = new EventEmitter(); @@ -617,8 +559,7 @@ describe('ParseLiveQueryServer', function () { // Trigger message event parseWebSocket.emit('message', unsubscribeRequest); // Make sure _handleUnsubscribe is called - const args = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent() - .args; + const args = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args; expect(args[0]).toBe(parseWebSocket); expect(JSON.stringify(args[1])).toBe(unsubscribeRequest); }); @@ -646,13 +587,11 @@ describe('ParseLiveQueryServer', function () { // Trigger message event parseWebSocket.emit('message', updateRequest); // Make sure _handleUnsubscribe is called - const args = parseLiveQueryServer._handleUpdateSubscription.calls.mostRecent() - .args; + const args = parseLiveQueryServer._handleUpdateSubscription.calls.mostRecent().args; expect(args[0]).toBe(parseWebSocket); expect(JSON.stringify(args[1])).toBe(updateRequest); expect(parseLiveQueryServer._handleUnsubscribe).toHaveBeenCalled(); - const unsubArgs = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent() - .args; + const unsubArgs = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args; expect(unsubArgs.length).toBe(3); expect(unsubArgs[2]).toBe(false); expect(parseLiveQueryServer._handleSubscribe).toHaveBeenCalled(); @@ -976,12 +915,7 @@ describe('ParseLiveQueryServer', function () { // Add mock subscription const requestId = 2; - await addMockSubscription( - parseLiveQueryServer, - clientId, - requestId, - parseWebSocket - ); + await addMockSubscription(parseLiveQueryServer, clientId, requestId, parseWebSocket); // Mock _matchesSubscription to return matching parseLiveQueryServer._matchesSubscription = function (parseObject) { if (!parseObject) { @@ -1065,13 +999,7 @@ describe('ParseLiveQueryServer', function () { }, fields: ['test'], }; - await addMockSubscription( - parseLiveQueryServer, - clientId, - requestId, - parseWebSocket, - query - ); + await addMockSubscription(parseLiveQueryServer, clientId, requestId, parseWebSocket, query); // Mock _matchesSubscription to return matching parseLiveQueryServer._matchesSubscription = function (parseObject) { if (!parseObject) { @@ -1103,12 +1031,8 @@ describe('ParseLiveQueryServer', function () { match: jasmine.createSpy('match'), }; - expect(parseLiveQueryServer._matchesSubscription(null, subscription)).toBe( - false - ); - expect( - parseLiveQueryServer._matchesSubscription(undefined, subscription) - ).toBe(false); + expect(parseLiveQueryServer._matchesSubscription(null, subscription)).toBe(false); + expect(parseLiveQueryServer._matchesSubscription(undefined, subscription)).toBe(false); // Make sure subscription.match is not called expect(subscription.match).not.toHaveBeenCalled(); }); @@ -1120,9 +1044,7 @@ describe('ParseLiveQueryServer', function () { query: {}, }; const parseObject = {}; - expect( - parseLiveQueryServer._matchesSubscription(parseObject, subscription) - ).toBe(true); + expect(parseLiveQueryServer._matchesSubscription(parseObject, subscription)).toBe(true); // Make sure matchesQuery is called const matchesQuery = require('../lib/LiveQuery/QueryTools').matchesQuery; expect(matchesQuery).toHaveBeenCalledWith(parseObject, subscription.query); @@ -1228,30 +1150,24 @@ describe('ParseLiveQueryServer', function () { const client = {}; const requestId = 0; - parseLiveQueryServer - ._matchesACL(undefined, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(true); - done(); - }); + parseLiveQueryServer._matchesACL(undefined, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(true); + done(); + }); }); it('can match ACL with none exist requestId', function (done) { const parseLiveQueryServer = new ParseLiveQueryServer({}); const acl = new Parse.ACL(); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue(undefined), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue(undefined), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); }); it('can match ACL with public read access', function (done) { @@ -1259,20 +1175,16 @@ describe('ParseLiveQueryServer', function () { const acl = new Parse.ACL(); acl.setPublicReadAccess(true); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: 'sessionToken', - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: 'sessionToken', + }), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(true); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(true); + done(); + }); }); it('can match ACL with valid subscription sessionToken', function (done) { @@ -1280,20 +1192,16 @@ describe('ParseLiveQueryServer', function () { const acl = new Parse.ACL(); acl.setReadAccess(testUserId, true); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: 'sessionToken', - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: 'sessionToken', + }), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(true); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(true); + done(); + }); }); it('can match ACL with valid client sessionToken', function (done) { @@ -1303,20 +1211,16 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return false when sessionToken is undefined const client = { sessionToken: 'sessionToken', - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: undefined, - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: undefined, + }), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(true); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(true); + done(); + }); }); it('can match ACL with invalid subscription and client sessionToken', function (done) { @@ -1326,20 +1230,16 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return false when sessionToken is undefined const client = { sessionToken: undefined, - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: undefined, - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: undefined, + }), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); }); it('can match ACL with subscription sessionToken checking error', function (done) { @@ -1349,20 +1249,16 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return error when sessionToken is null, this is just // the behaviour of our mock sessionTokenCache, not real sessionTokenCache const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: null, - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: null, + }), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); }); it('can match ACL with client sessionToken checking error', function (done) { @@ -1372,20 +1268,16 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return error when sessionToken is null const client = { sessionToken: null, - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: null, - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: null, + }), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); }); it("won't match ACL that doesn't have public read or any roles", function (done) { @@ -1393,20 +1285,16 @@ describe('ParseLiveQueryServer', function () { const acl = new Parse.ACL(); acl.setPublicReadAccess(false); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: 'sessionToken', - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: 'sessionToken', + }), }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); }); it("won't match non-public ACL with role when there is no user", function (done) { @@ -1415,9 +1303,7 @@ describe('ParseLiveQueryServer', function () { acl.setPublicReadAccess(false); acl.setRoleReadAccess('livequery', true); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({}), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({}), }; const requestId = 0; @@ -1436,11 +1322,9 @@ describe('ParseLiveQueryServer', function () { acl.setPublicReadAccess(false); acl.setRoleReadAccess('otherLiveQueryRead', true); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: 'sessionToken', - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: 'sessionToken', + }), }; const requestId = 0; @@ -1461,29 +1345,22 @@ describe('ParseLiveQueryServer', function () { return Promise.resolve([]); } //Return a role with the name "liveQueryRead" as that is what was set on the ACL - const liveQueryRole = new Parse.Role( - 'liveQueryRead', - new Parse.ACL() - ); + const liveQueryRole = new Parse.Role('liveQueryRead', new Parse.ACL()); liveQueryRole.id = 'abcdef1234'; return Promise.resolve([liveQueryRole]); }, }; }); - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); }); it('will match ACL with role based read access set to true', function (done) { @@ -1492,11 +1369,9 @@ describe('ParseLiveQueryServer', function () { acl.setPublicReadAccess(false); acl.setRoleReadAccess('liveQueryRead', true); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: 'sessionToken', - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: 'sessionToken', + }), }; const requestId = 0; @@ -1517,19 +1392,13 @@ describe('ParseLiveQueryServer', function () { return Promise.resolve([]); } //Return a role with the name "liveQueryRead" as that is what was set on the ACL - const liveQueryRole = new Parse.Role( - 'liveQueryRead', - new Parse.ACL() - ); + const liveQueryRole = new Parse.Role('liveQueryRead', new Parse.ACL()); liveQueryRole.id = 'abcdef1234'; return Promise.resolve([liveQueryRole]); }, each(callback) { //Return a role with the name "liveQueryRead" as that is what was set on the ACL - const liveQueryRole = new Parse.Role( - 'liveQueryRead', - new Parse.ACL() - ); + const liveQueryRole = new Parse.Role('liveQueryRead', new Parse.ACL()); liveQueryRole.id = 'abcdef1234'; callback(liveQueryRole); return Promise.resolve(); @@ -1537,12 +1406,10 @@ describe('ParseLiveQueryServer', function () { }; }); - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(true); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(true); + done(); + }); }); describe('class level permissions', () => { @@ -1553,11 +1420,9 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return false when sessionToken is undefined const client = { sessionToken: 'sessionToken', - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: undefined, - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: undefined, + }), }; const requestId = 0; @@ -1584,11 +1449,9 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return false when sessionToken is undefined const client = { sessionToken: 'sessionToken', - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: undefined, - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: undefined, + }), }; const requestId = 0; @@ -1615,11 +1478,9 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return false when sessionToken is undefined const client = { sessionToken: 'sessionToken', - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: 'userId', - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: 'userId', + }), }; const requestId = 0; @@ -1646,11 +1507,9 @@ describe('ParseLiveQueryServer', function () { // Mock sessionTokenCache will return false when sessionToken is undefined const client = { sessionToken: 'sessionToken', - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({ - sessionToken: undefined, - }), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({ + sessionToken: undefined, + }), }; const requestId = 0; @@ -1684,9 +1543,7 @@ describe('ParseLiveQueryServer', function () { clientKey: 'test', }; - expect( - parseLiveQueryServer._validateKeys(request, parseLiveQueryServer.keyPairs) - ).toBeTruthy(); + expect(parseLiveQueryServer._validateKeys(request, parseLiveQueryServer.keyPairs)).toBeTruthy(); }); it('can validate key when invalid key is provided', function () { @@ -1727,9 +1584,7 @@ describe('ParseLiveQueryServer', function () { const parseLiveQueryServer = new ParseLiveQueryServer({}, {}); const request = {}; - expect( - parseLiveQueryServer._validateKeys(request, parseLiveQueryServer.keyPairs) - ).toBeTruthy(); + expect(parseLiveQueryServer._validateKeys(request, parseLiveQueryServer.keyPairs)).toBeTruthy(); }); it('can validate client has master key when valid', function () { @@ -1745,9 +1600,7 @@ describe('ParseLiveQueryServer', function () { masterKey: 'test', }; - expect( - parseLiveQueryServer._hasMasterKey(request, parseLiveQueryServer.keyPairs) - ).toBeTruthy(); + expect(parseLiveQueryServer._hasMasterKey(request, parseLiveQueryServer.keyPairs)).toBeTruthy(); }); it("can validate client doesn't have master key when invalid", function () { @@ -1778,9 +1631,7 @@ describe('ParseLiveQueryServer', function () { } ); - expect( - parseLiveQueryServer._hasMasterKey({}, parseLiveQueryServer.keyPairs) - ).not.toBeTruthy(); + expect(parseLiveQueryServer._hasMasterKey({}, parseLiveQueryServer.keyPairs)).not.toBeTruthy(); }); it("can validate client doesn't have master key when validKeyPairs is empty", function () { @@ -1799,19 +1650,15 @@ describe('ParseLiveQueryServer', function () { const acl = new Parse.ACL(); acl.setPublicReadAccess(false); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({}), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({}), hasMasterKey: true, }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(true); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(true); + done(); + }); }); it("won't match non-public ACL when client has no master key", function (done) { @@ -1819,27 +1666,21 @@ describe('ParseLiveQueryServer', function () { const acl = new Parse.ACL(); acl.setPublicReadAccess(false); const client = { - getSubscriptionInfo: jasmine - .createSpy('getSubscriptionInfo') - .and.returnValue({}), + getSubscriptionInfo: jasmine.createSpy('getSubscriptionInfo').and.returnValue({}), hasMasterKey: false, }; const requestId = 0; - parseLiveQueryServer - ._matchesACL(acl, client, requestId) - .then(function (isMatched) { - expect(isMatched).toBe(false); - done(); - }); + parseLiveQueryServer._matchesACL(acl, client, requestId).then(function (isMatched) { + expect(isMatched).toBe(false); + done(); + }); }); it('should properly pull auth from cache', () => { const parseLiveQueryServer = new ParseLiveQueryServer({}); const promise = parseLiveQueryServer.getAuthForSessionToken('sessionToken'); - const secondPromise = parseLiveQueryServer.getAuthForSessionToken( - 'sessionToken' - ); + const secondPromise = parseLiveQueryServer.getAuthForSessionToken('sessionToken'); // should be in the cache expect(parseLiveQueryServer.authCache.get('sessionToken')).toBe(promise); // should be the same promise returned @@ -1869,10 +1710,7 @@ describe('ParseLiveQueryServer', function () { }); afterEach(function () { - jasmine.restoreLibrary( - '../lib/LiveQuery/ParseWebSocketServer', - 'ParseWebSocketServer' - ); + jasmine.restoreLibrary('../lib/LiveQuery/ParseWebSocketServer', 'ParseWebSocketServer'); jasmine.restoreLibrary('../lib/LiveQuery/Client', 'Client'); jasmine.restoreLibrary('../lib/LiveQuery/Subscription', 'Subscription'); jasmine.restoreLibrary('../lib/LiveQuery/QueryTools', 'queryHash'); @@ -1927,10 +1765,7 @@ describe('ParseLiveQueryServer', function () { }; subscription.className = query.className; subscription.hash = queryHashValue; - if ( - subscription.clientRequestIds && - subscription.clientRequestIds.has(clientId) - ) { + if (subscription.clientRequestIds && subscription.clientRequestIds.has(clientId)) { subscription.clientRequestIds.get(clientId).push(requestId); } else { subscription.clientRequestIds = new Map([[clientId, [requestId]]]); @@ -2002,10 +1837,7 @@ describe('LiveQueryController', () => { }, }) .then(parseServer => { - saveSpy = spyOn( - parseServer.config.liveQueryController, - 'onAfterSave' - ).and.callThrough(); + saveSpy = spyOn(parseServer.config.liveQueryController, 'onAfterSave').and.callThrough(); deleteSpy = spyOn( parseServer.config.liveQueryController, 'onAfterDelete' diff --git a/spec/ParseObject.spec.js b/spec/ParseObject.spec.js index 78df95e5..235bdbd8 100644 --- a/spec/ParseObject.spec.js +++ b/spec/ParseObject.spec.js @@ -13,34 +13,34 @@ // single-instance mode. describe('Parse.Object testing', () => { - it('create', function(done) { - create({ test: 'test' }, function(model) { + it('create', function (done) { + create({ test: 'test' }, function (model) { ok(model.id, 'Should have an objectId set'); equal(model.get('test'), 'test', 'Should have the right attribute'); done(); }); }); - it('update', function(done) { - create({ test: 'test' }, function(model) { + it('update', function (done) { + create({ test: 'test' }, function (model) { const t2 = new TestObject({ objectId: model.id }); t2.set('test', 'changed'); - t2.save().then(function(model) { + t2.save().then(function (model) { equal(model.get('test'), 'changed', 'Update should have succeeded'); done(); }); }); }); - it('save without null', function(done) { + it('save without null', function (done) { const object = new TestObject(); object.set('favoritePony', 'Rainbow Dash'); object.save().then( - function(objectAgain) { + function (objectAgain) { equal(objectAgain, object); done(); }, - function(objectAgain, error) { + function (objectAgain, error) { ok(null, 'Error ' + error.code + ': ' + error.message); done(); } @@ -52,31 +52,31 @@ describe('Parse.Object testing', () => { const b = new Parse.Object('TestObject'); a.set('b', b); a.save() - .then(function() { + .then(function () { b.set('a', a); return b.save(); }) - .then(function() { + .then(function () { ok(a.id); ok(b.id); strictEqual(a.get('b'), b); strictEqual(b.get('a'), a); }) .then( - function() { + function () { done(); }, - function(error) { + function (error) { ok(false, error); done(); } ); }); - it('get', function(done) { - create({ test: 'test' }, function(model) { + it('get', function (done) { + create({ test: 'test' }, function (model) { const t2 = new TestObject({ objectId: model.id }); - t2.fetch().then(function(model2) { + t2.fetch().then(function (model2) { equal(model2.get('test'), 'test', 'Update should have succeeded'); ok(model2.id); equal(model2.id, model.id, 'Ids should match'); @@ -85,43 +85,43 @@ describe('Parse.Object testing', () => { }); }); - it('delete', function(done) { + it('delete', function (done) { const t = new TestObject(); t.set('test', 'test'); - t.save().then(function() { - t.destroy().then(function() { + t.save().then(function () { + t.destroy().then(function () { const t2 = new TestObject({ objectId: t.id }); t2.fetch().then(fail, () => done()); }); }); }); - it('find', function(done) { + it('find', function (done) { const t = new TestObject(); t.set('foo', 'bar'); - t.save().then(function() { + t.save().then(function () { const query = new Parse.Query(TestObject); query.equalTo('foo', 'bar'); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 1); done(); }); }); }); - it('relational fields', function(done) { + it('relational fields', function (done) { const item = new Item(); item.set('property', 'x'); const container = new Container(); container.set('item', item); - Parse.Object.saveAll([item, container]).then(function() { + Parse.Object.saveAll([item, container]).then(function () { const query = new Parse.Query(Container); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 1); const containerAgain = results[0]; const itemAgain = containerAgain.get('item'); - itemAgain.fetch().then(function() { + itemAgain.fetch().then(function () { equal(itemAgain.get('property'), 'x'); done(); }); @@ -129,28 +129,28 @@ describe('Parse.Object testing', () => { }); }); - it('save adds no data keys (other than createdAt and updatedAt)', function(done) { + it('save adds no data keys (other than createdAt and updatedAt)', function (done) { const object = new TestObject(); - object.save().then(function() { + object.save().then(function () { const keys = Object.keys(object.attributes).sort(); equal(keys.length, 2); done(); }); }); - it('recursive save', function(done) { + it('recursive save', function (done) { const item = new Item(); item.set('property', 'x'); const container = new Container(); container.set('item', item); - container.save().then(function() { + container.save().then(function () { const query = new Parse.Query(Container); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 1); const containerAgain = results[0]; const itemAgain = containerAgain.get('item'); - itemAgain.fetch().then(function() { + itemAgain.fetch().then(function () { equal(itemAgain.get('property'), 'x'); done(); }); @@ -158,14 +158,14 @@ describe('Parse.Object testing', () => { }); }); - it('fetch', function(done) { + it('fetch', function (done) { const item = new Item({ foo: 'bar' }); - item.save().then(function() { + item.save().then(function () { const itemAgain = new Item(); itemAgain.id = item.id; - itemAgain.fetch().then(function() { - itemAgain.save({ foo: 'baz' }).then(function() { - item.fetch().then(function() { + itemAgain.fetch().then(function () { + itemAgain.save({ foo: 'baz' }).then(function () { + item.fetch().then(function () { equal(item.get('foo'), itemAgain.get('foo')); done(); }); @@ -174,33 +174,33 @@ describe('Parse.Object testing', () => { }); }); - it("createdAt doesn't change", function(done) { + it("createdAt doesn't change", function (done) { const object = new TestObject({ foo: 'bar' }); - object.save().then(function() { + object.save().then(function () { const objectAgain = new TestObject(); objectAgain.id = object.id; - objectAgain.fetch().then(function() { + objectAgain.fetch().then(function () { equal(object.createdAt.getTime(), objectAgain.createdAt.getTime()); done(); }); }); }); - it('createdAt and updatedAt exposed', function(done) { + it('createdAt and updatedAt exposed', function (done) { const object = new TestObject({ foo: 'bar' }); - object.save().then(function() { + object.save().then(function () { notEqual(object.updatedAt, undefined); notEqual(object.createdAt, undefined); done(); }); }); - it('updatedAt gets updated', function(done) { + it('updatedAt gets updated', function (done) { const object = new TestObject({ foo: 'bar' }); - object.save().then(function() { + object.save().then(function () { ok(object.updatedAt, 'initial save should cause updatedAt to exist'); const firstUpdatedAt = object.updatedAt; - object.save({ foo: 'baz' }).then(function() { + object.save({ foo: 'baz' }).then(function () { ok(object.updatedAt, 'two saves should cause updatedAt to exist'); notEqual(firstUpdatedAt, object.updatedAt); done(); @@ -208,14 +208,12 @@ describe('Parse.Object testing', () => { }); }); - it('createdAt is reasonable', function(done) { + it('createdAt is reasonable', function (done) { const startTime = new Date(); const object = new TestObject({ foo: 'bar' }); - object.save().then(function() { + object.save().then(function () { const endTime = new Date(); - const startDiff = Math.abs( - startTime.getTime() - object.createdAt.getTime() - ); + const startDiff = Math.abs(startTime.getTime() - object.createdAt.getTime()); ok(startDiff < 5000); const endDiff = Math.abs(endTime.getTime() - object.createdAt.getTime()); @@ -225,11 +223,11 @@ describe('Parse.Object testing', () => { }); }); - it_exclude_dbs(['postgres'])('can set null', function(done) { + it_exclude_dbs(['postgres'])('can set null', function (done) { const obj = new Parse.Object('TestObject'); obj.set('foo', null); obj.save().then( - function(obj) { + function (obj) { on_db('mongo', () => { equal(obj.get('foo'), null); }); @@ -238,31 +236,31 @@ describe('Parse.Object testing', () => { }); done(); }, - function() { + function () { fail('should not fail'); done(); } ); }); - it('can set boolean', function(done) { + it('can set boolean', function (done) { const obj = new Parse.Object('TestObject'); obj.set('yes', true); obj.set('no', false); obj.save().then( - function(obj) { + function (obj) { equal(obj.get('yes'), true); equal(obj.get('no'), false); done(); }, - function(obj, error) { + function (obj, error) { ok(false, error.message); done(); } ); }); - it('cannot set invalid date', async function(done) { + it('cannot set invalid date', async function (done) { const obj = new Parse.Object('TestObject'); obj.set('when', new Date(Date.parse(null))); try { @@ -286,14 +284,14 @@ describe('Parse.Object testing', () => { expect(object.get('authData')).toBe('random'); }); - it('invalid class name', function(done) { + it('invalid class name', function (done) { const item = new Parse.Object('Foo^bar'); item.save().then( - function() { + function () { ok(false, 'The name should have been invalid.'); done(); }, - function() { + function () { // Because the class name is invalid, the router will not be able to route // it, so it will actually return a -1 error code. // equal(error.code, Parse.Error.INVALID_CLASS_NAME); @@ -302,26 +300,15 @@ describe('Parse.Object testing', () => { ); }); - it('invalid key name', function(done) { + it('invalid key name', function (done) { const item = new Parse.Object('Item'); - ok( - !item.set({ 'foo^bar': 'baz' }), - 'Item should not be updated with invalid key.' - ); + ok(!item.set({ 'foo^bar': 'baz' }), 'Item should not be updated with invalid key.'); item.save({ 'foo^bar': 'baz' }).then(fail, () => done()); }); - it('invalid __type', function(done) { + it('invalid __type', function (done) { const item = new Parse.Object('Item'); - const types = [ - 'Pointer', - 'File', - 'Date', - 'GeoPoint', - 'Bytes', - 'Polygon', - 'Relation', - ]; + const types = ['Pointer', 'File', 'Date', 'GeoPoint', 'Bytes', 'Polygon', 'Relation']; const tests = types.map(type => { const test = new Parse.Object('Item'); test.set('foo', { @@ -329,7 +316,7 @@ describe('Parse.Object testing', () => { }); return test; }); - const next = function(index) { + const next = function (index) { if (index < tests.length) { tests[index].save().then(fail, error => { expect(error.code).toEqual(Parse.Error.INCORRECT_TYPE); @@ -348,50 +335,50 @@ describe('Parse.Object testing', () => { .then(fail, () => next(0)); }); - it('simple field deletion', function(done) { + it('simple field deletion', function (done) { const simple = new Parse.Object('SimpleObject'); simple .save({ foo: 'bar', }) .then( - function(simple) { + function (simple) { simple.unset('foo'); ok(!simple.has('foo'), 'foo should have been unset.'); ok(simple.dirty('foo'), 'foo should be dirty.'); ok(simple.dirty(), 'the whole object should be dirty.'); simple.save().then( - function(simple) { + function (simple) { ok(!simple.has('foo'), 'foo should have been unset.'); ok(!simple.dirty('foo'), 'the whole object was just saved.'); ok(!simple.dirty(), 'the whole object was just saved.'); const query = new Parse.Query('SimpleObject'); query.get(simple.id).then( - function(simpleAgain) { + function (simpleAgain) { ok(!simpleAgain.has('foo'), 'foo should have been removed.'); done(); }, - function(simpleAgain, error) { + function (simpleAgain, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }, - function(simple, error) { + function (simple, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }, - function(simple, error) { + function (simple, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }); - it('field deletion before first save', function(done) { + it('field deletion before first save', function (done) { const simple = new Parse.Object('SimpleObject'); simple.set('foo', 'bar'); simple.unset('foo'); @@ -400,31 +387,31 @@ describe('Parse.Object testing', () => { ok(simple.dirty('foo'), 'foo should be dirty.'); ok(simple.dirty(), 'the whole object should be dirty.'); simple.save().then( - function(simple) { + function (simple) { ok(!simple.has('foo'), 'foo should have been unset.'); ok(!simple.dirty('foo'), 'the whole object was just saved.'); ok(!simple.dirty(), 'the whole object was just saved.'); const query = new Parse.Query('SimpleObject'); query.get(simple.id).then( - function(simpleAgain) { + function (simpleAgain) { ok(!simpleAgain.has('foo'), 'foo should have been removed.'); done(); }, - function(simpleAgain, error) { + function (simpleAgain, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }, - function(simple, error) { + function (simple, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }); - it('relation deletion', function(done) { + it('relation deletion', function (done) { const simple = new Parse.Object('SimpleObject'); const child = new Parse.Object('Child'); simple @@ -432,54 +419,51 @@ describe('Parse.Object testing', () => { child: child, }) .then( - function(simple) { + function (simple) { simple.unset('child'); ok(!simple.has('child'), 'child should have been unset.'); ok(simple.dirty('child'), 'child should be dirty.'); ok(simple.dirty(), 'the whole object should be dirty.'); simple.save().then( - function(simple) { + function (simple) { ok(!simple.has('child'), 'child should have been unset.'); ok(!simple.dirty('child'), 'the whole object was just saved.'); ok(!simple.dirty(), 'the whole object was just saved.'); const query = new Parse.Query('SimpleObject'); query.get(simple.id).then( - function(simpleAgain) { - ok( - !simpleAgain.has('child'), - 'child should have been removed.' - ); + function (simpleAgain) { + ok(!simpleAgain.has('child'), 'child should have been removed.'); done(); }, - function(simpleAgain, error) { + function (simpleAgain, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }, - function(simple, error) { + function (simple, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }, - function(simple, error) { + function (simple, error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }); - it('deleted keys get cleared', function(done) { + it('deleted keys get cleared', function (done) { const simpleObject = new Parse.Object('SimpleObject'); simpleObject.set('foo', 'bar'); simpleObject.unset('foo'); - simpleObject.save().then(function(simpleObject) { + simpleObject.save().then(function (simpleObject) { simpleObject.set('foo', 'baz'); - simpleObject.save().then(function(simpleObject) { + simpleObject.save().then(function (simpleObject) { const query = new Parse.Query('SimpleObject'); - query.get(simpleObject.id).then(function(simpleObjectAgain) { + query.get(simpleObject.id).then(function (simpleObjectAgain) { equal(simpleObjectAgain.get('foo'), 'baz'); done(); }, done.fail); @@ -487,58 +471,58 @@ describe('Parse.Object testing', () => { }, done.fail); }); - it('setting after deleting', function(done) { + it('setting after deleting', function (done) { const simpleObject = new Parse.Object('SimpleObject'); simpleObject.set('foo', 'bar'); simpleObject.save().then( - function(simpleObject) { + function (simpleObject) { simpleObject.unset('foo'); simpleObject.set('foo', 'baz'); simpleObject.save().then( - function(simpleObject) { + function (simpleObject) { const query = new Parse.Query('SimpleObject'); query.get(simpleObject.id).then( - function(simpleObjectAgain) { + function (simpleObjectAgain) { equal(simpleObjectAgain.get('foo'), 'baz'); done(); }, - function(error) { + function (error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }, - function(error) { + function (error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }, - function(error) { + function (error) { ok(false, 'Error ' + error.code + ': ' + error.message); done(); } ); }); - it('increment', function(done) { + it('increment', function (done) { const simple = new Parse.Object('SimpleObject'); simple .save({ foo: 5, }) - .then(function(simple) { + .then(function (simple) { simple.increment('foo'); equal(simple.get('foo'), 6); ok(simple.dirty('foo'), 'foo should be dirty.'); ok(simple.dirty(), 'the whole object should be dirty.'); - simple.save().then(function(simple) { + simple.save().then(function (simple) { equal(simple.get('foo'), 6); ok(!simple.dirty('foo'), 'the whole object was just saved.'); ok(!simple.dirty(), 'the whole object was just saved.'); const query = new Parse.Query('SimpleObject'); - query.get(simple.id).then(function(simpleAgain) { + query.get(simple.id).then(function (simpleAgain) { equal(simpleAgain.get('foo'), 6); done(); }); @@ -546,7 +530,7 @@ describe('Parse.Object testing', () => { }); }); - it('addUnique', function(done) { + it('addUnique', function (done) { const x1 = new Parse.Object('X'); x1.set('stuff', [1, 2]); x1.save() @@ -577,16 +561,14 @@ describe('Parse.Object testing', () => { jfail(error); }); on_db('postgres', () => { - expect(error.message).toEqual( - 'Postgres does not support AddUnique operator.' - ); + expect(error.message).toEqual('Postgres does not support AddUnique operator.'); }); done(); } ); }); - it('addUnique with object', function(done) { + it('addUnique with object', function (done) { const x1 = new Parse.Object('X'); x1.set('stuff', [1, { hello: 'world' }, { foo: 'bar' }]); x1.save() @@ -605,12 +587,7 @@ describe('Parse.Object testing', () => { .then( x3 => { const stuff = x3.get('stuff'); - const target = [ - 1, - { hello: 'world' }, - { foo: 'bar' }, - { bar: 'baz' }, - ]; + const target = [1, { hello: 'world' }, { foo: 'bar' }, { bar: 'baz' }]; expect(stuff.length).toEqual(target.length); let found = 0; for (const thing in target) { @@ -630,7 +607,7 @@ describe('Parse.Object testing', () => { ); }); - it('removes with object', function(done) { + it('removes with object', function (done) { const x1 = new Parse.Object('X'); x1.set('stuff', [1, { hello: 'world' }, { foo: 'bar' }]); x1.save() @@ -657,12 +634,12 @@ describe('Parse.Object testing', () => { ); }); - it('dirty attributes', function(done) { + it('dirty attributes', function (done) { const object = new Parse.Object('TestObject'); object.set('cat', 'good'); object.set('dog', 'bad'); object.save().then( - function(object) { + function (object) { ok(!object.dirty()); ok(!object.dirty('cat')); ok(!object.dirty('dog')); @@ -675,14 +652,14 @@ describe('Parse.Object testing', () => { done(); }, - function() { + function () { ok(false, 'This should have saved.'); done(); } ); }); - it('dirty keys', function(done) { + it('dirty keys', function (done) { const object = new Parse.Object('TestObject'); object.set('gogo', 'good'); object.set('sito', 'sexy'); @@ -694,7 +671,7 @@ describe('Parse.Object testing', () => { object .save() - .then(function(obj) { + .then(function (obj) { ok(!obj.dirty()); dirtyKeys = obj.dirtyKeys(); equal(dirtyKeys.length, 0); @@ -711,7 +688,7 @@ describe('Parse.Object testing', () => { return obj.save(); }) - .then(function(obj) { + .then(function (obj) { ok(!obj.dirty()); equal(obj.get('gogo'), 'good'); equal(obj.get('sito'), undefined); @@ -724,8 +701,8 @@ describe('Parse.Object testing', () => { }); }); - it('length attribute', function(done) { - Parse.User.signUp('bob', 'password').then(function(user) { + it('length attribute', function (done) { + Parse.User.signUp('bob', 'password').then(function (user) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject({ length: 5, @@ -734,17 +711,17 @@ describe('Parse.Object testing', () => { equal(obj.get('length'), 5); ok(obj.get('ACL') instanceof Parse.ACL); - obj.save().then(function(obj) { + obj.save().then(function (obj) { equal(obj.get('length'), 5); ok(obj.get('ACL') instanceof Parse.ACL); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(obj) { + query.get(obj.id).then(function (obj) { equal(obj.get('length'), 5); ok(obj.get('ACL') instanceof Parse.ACL); const query = new Parse.Query(TestObject); - query.find().then(function(results) { + query.find().then(function (results) { obj = results[0]; equal(obj.get('length'), 5); ok(obj.get('ACL') instanceof Parse.ACL); @@ -756,18 +733,18 @@ describe('Parse.Object testing', () => { }); }); - it('old attribute unset then unset', function(done) { + it('old attribute unset then unset', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 3); - obj.save().then(function() { + obj.save().then(function () { obj.unset('x'); obj.unset('x'); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -776,17 +753,17 @@ describe('Parse.Object testing', () => { }); }); - it('new attribute unset then unset', function(done) { + it('new attribute unset then unset', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 5); obj.unset('x'); obj.unset('x'); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -794,16 +771,16 @@ describe('Parse.Object testing', () => { }); }); - it('unknown attribute unset then unset', function(done) { + it('unknown attribute unset then unset', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.unset('x'); obj.unset('x'); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -811,18 +788,18 @@ describe('Parse.Object testing', () => { }); }); - it('old attribute unset then clear', function(done) { + it('old attribute unset then clear', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 3); - obj.save().then(function() { + obj.save().then(function () { obj.unset('x'); obj.clear(); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -831,17 +808,17 @@ describe('Parse.Object testing', () => { }); }); - it('new attribute unset then clear', function(done) { + it('new attribute unset then clear', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 5); obj.unset('x'); obj.clear(); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -849,16 +826,16 @@ describe('Parse.Object testing', () => { }); }); - it('unknown attribute unset then clear', function(done) { + it('unknown attribute unset then clear', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.unset('x'); obj.clear(); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -866,18 +843,18 @@ describe('Parse.Object testing', () => { }); }); - it('old attribute clear then unset', function(done) { + it('old attribute clear then unset', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 3); - obj.save().then(function() { + obj.save().then(function () { obj.clear(); obj.unset('x'); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -886,17 +863,17 @@ describe('Parse.Object testing', () => { }); }); - it('new attribute clear then unset', function(done) { + it('new attribute clear then unset', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 5); obj.clear(); obj.unset('x'); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -904,16 +881,16 @@ describe('Parse.Object testing', () => { }); }); - it('unknown attribute clear then unset', function(done) { + it('unknown attribute clear then unset', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.clear(); obj.unset('x'); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -921,18 +898,18 @@ describe('Parse.Object testing', () => { }); }); - it('old attribute clear then clear', function(done) { + it('old attribute clear then clear', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 3); - obj.save().then(function() { + obj.save().then(function () { obj.clear(); obj.clear(); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -941,17 +918,17 @@ describe('Parse.Object testing', () => { }); }); - it('new attribute clear then clear', function(done) { + it('new attribute clear then clear', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.set('x', 5); obj.clear(); obj.clear(); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -959,16 +936,16 @@ describe('Parse.Object testing', () => { }); }); - it('unknown attribute clear then clear', function(done) { + it('unknown attribute clear then clear', function (done) { const TestObject = Parse.Object.extend('TestObject'); const obj = new TestObject(); obj.clear(); obj.clear(); - obj.save().then(function() { + obj.save().then(function () { equal(obj.has('x'), false); equal(obj.get('x'), undefined); const query = new Parse.Query(TestObject); - query.get(obj.id).then(function(objAgain) { + query.get(obj.id).then(function (objAgain) { equal(objAgain.has('x'), false); equal(objAgain.get('x'), undefined); done(); @@ -976,7 +953,7 @@ describe('Parse.Object testing', () => { }); }); - it('saving children in an array', function(done) { + it('saving children in an array', function (done) { const Parent = Parse.Object.extend('Parent'); const Child = Parse.Object.extend('Child'); @@ -988,10 +965,10 @@ describe('Parse.Object testing', () => { child2.set('name', 'cersei'); parent.set('children', [child1, child2]); - parent.save().then(function() { + parent.save().then(function () { const query = new Parse.Query(Child); query.ascending('name'); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 2); equal(results[0].get('name'), 'cersei'); equal(results[1].get('name'), 'jamie'); @@ -1000,18 +977,18 @@ describe('Parse.Object testing', () => { }, done.fail); }); - it('two saves at the same time', function(done) { + it('two saves at the same time', function (done) { const object = new Parse.Object('TestObject'); let firstSave = true; - const success = function() { + const success = function () { if (firstSave) { firstSave = false; return; } const query = new Parse.Query('TestObject'); - query.find().then(function(results) { + query.find().then(function (results) { equal(results.length, 1); equal(results[0].get('cat'), 'meow'); equal(results[0].get('dog'), 'bark'); @@ -1028,7 +1005,7 @@ describe('Parse.Object testing', () => { // typed field and saved okay, since that appears to be borked in // the client. // If this fails, it's probably a schema issue. - it('many saves after a failure', function(done) { + it('many saves after a failure', function (done) { // Make a class with a number in the schema. const o1 = new Parse.Object('TestObject'); o1.set('number', 1); @@ -1058,49 +1035,49 @@ describe('Parse.Object testing', () => { }); }); - it('is not dirty after save', function(done) { + it('is not dirty after save', function (done) { const obj = new Parse.Object('TestObject'); - obj.save().then(function() { + obj.save().then(function () { obj.set({ content: 'x' }); - obj.fetch().then(function() { + obj.fetch().then(function () { equal(false, obj.dirty('content')); done(); }); }); }); - it('add with an object', function(done) { + it('add with an object', function (done) { const child = new Parse.Object('Person'); const parent = new Parse.Object('Person'); Promise.resolve() - .then(function() { + .then(function () { return child.save(); }) - .then(function() { + .then(function () { parent.add('children', child); return parent.save(); }) - .then(function() { + .then(function () { const query = new Parse.Query('Person'); return query.get(parent.id); }) - .then(function(parentAgain) { + .then(function (parentAgain) { equal(parentAgain.get('children')[0].id, child.id); }) .then( - function() { + function () { done(); }, - function(error) { + function (error) { ok(false, error); done(); } ); }); - it('toJSON saved object', function(done) { - create({ foo: 'bar' }, function(model) { + it('toJSON saved object', function (done) { + create({ foo: 'bar' }, function (model) { const objJSON = model.toJSON(); ok(objJSON.foo, "expected json to contain key 'foo'"); ok(objJSON.objectId, "expected json to contain key 'objectId'"); @@ -1110,13 +1087,13 @@ describe('Parse.Object testing', () => { }); }); - it('remove object from array', function(done) { + it('remove object from array', function (done) { const obj = new TestObject(); - obj.save().then(function() { + obj.save().then(function () { const container = new TestObject(); container.add('array', obj); equal(container.get('array').length, 1); - container.save(null).then(function() { + container.save(null).then(function () { const objAgain = new TestObject(); objAgain.id = obj.id; container.remove('array', objAgain); @@ -1126,37 +1103,37 @@ describe('Parse.Object testing', () => { }); }); - it('async methods', function(done) { + it('async methods', function (done) { const obj = new TestObject(); obj.set('time', 'adventure'); obj .save() - .then(function(obj) { + .then(function (obj) { ok(obj.id, 'objectId should not be null.'); const objAgain = new TestObject(); objAgain.id = obj.id; return objAgain.fetch(); }) - .then(function(objAgain) { + .then(function (objAgain) { equal(objAgain.get('time'), 'adventure'); return objAgain.destroy(); }) - .then(function() { + .then(function () { const query = new Parse.Query(TestObject); return query.find(); }) - .then(function(results) { + .then(function (results) { equal(results.length, 0); }) - .then(function() { + .then(function () { done(); }); }); - it('fail validation with promise', function(done) { + it('fail validation with promise', function (done) { const PickyEater = Parse.Object.extend('PickyEater', { - validate: function(attrs) { + validate: function (attrs) { if (attrs.meal === 'tomatoes') { return 'Ew. Tomatoes are gross.'; } @@ -1170,31 +1147,31 @@ describe('Parse.Object testing', () => { meal: 'burrito', }) .then( - function() { + function () { return bryan.save({ meal: 'tomatoes', }); }, - function() { + function () { ok(false, 'Save should have succeeded.'); } ) .then( - function() { + function () { ok(false, 'Save should have failed.'); }, - function(error) { + function (error) { equal(error, 'Ew. Tomatoes are gross.'); done(); } ); }); - it("beforeSave doesn't make object dirty with new field", function(done) { + it("beforeSave doesn't make object dirty with new field", function (done) { const restController = Parse.CoreManager.getRESTController(); const r = restController.request; - restController.request = function() { - return r.apply(this, arguments).then(function(result) { + restController.request = function () { + return r.apply(this, arguments).then(function (result) { result.aDate = { __type: 'Date', iso: '2014-06-24T06:06:06.452Z' }; return result; }); @@ -1203,21 +1180,21 @@ describe('Parse.Object testing', () => { const obj = new Parse.Object('Thing'); obj .save() - .then(function() { + .then(function () { ok(!obj.dirty(), 'The object should not be dirty'); ok(obj.get('aDate')); }) - .then(function() { + .then(function () { restController.request = r; done(); }); }); - xit("beforeSave doesn't make object dirty with existing field", function(done) { + xit("beforeSave doesn't make object dirty with existing field", function (done) { const restController = Parse.CoreManager.getRESTController(); const r = restController.request; - restController.request = function() { - return r.apply(restController, arguments).then(function(result) { + restController.request = function () { + return r.apply(restController, arguments).then(function (result) { result.aDate = { __type: 'Date', iso: '2014-06-24T06:06:06.452Z' }; return result; }); @@ -1230,60 +1207,60 @@ describe('Parse.Object testing', () => { obj.set('aDate', now); promise - .then(function() { + .then(function () { ok(obj.dirty(), 'The object should be dirty'); equal(now, obj.get('aDate')); }) - .then(function() { + .then(function () { restController.request = r; done(); }); }); - it('bytes work', function(done) { + it('bytes work', function (done) { Promise.resolve() - .then(function() { + .then(function () { const obj = new TestObject(); obj.set('bytes', { __type: 'Bytes', base64: 'ZnJveW8=' }); return obj.save(); }) - .then(function(obj) { + .then(function (obj) { const query = new Parse.Query(TestObject); return query.get(obj.id); }) .then( - function(obj) { + function (obj) { equal(obj.get('bytes').__type, 'Bytes'); equal(obj.get('bytes').base64, 'ZnJveW8='); done(); }, - function(error) { + function (error) { ok(false, JSON.stringify(error)); done(); } ); }); - it('destroyAll no objects', function(done) { + it('destroyAll no objects', function (done) { Parse.Object.destroyAll([]) - .then(function(success) { + .then(function (success) { ok(success, 'Should be able to destroy no objects'); done(); }) .catch(done.fail); }); - it('destroyAll new objects only', function(done) { + it('destroyAll new objects only', function (done) { const objects = [new TestObject(), new TestObject()]; Parse.Object.destroyAll(objects) - .then(function(success) { + .then(function (success) { ok(success, 'Should be able to destroy only new objects'); done(); }) .catch(done.fail); }); - it('fetchAll', function(done) { + it('fetchAll', function (done) { const numItems = 11; const container = new Container(); const items = []; @@ -1293,15 +1270,15 @@ describe('Parse.Object testing', () => { items.push(item); } Parse.Object.saveAll(items) - .then(function() { + .then(function () { container.set('items', items); return container.save(); }) - .then(function() { + .then(function () { const query = new Parse.Query(Container); return query.get(container.id); }) - .then(function(containerAgain) { + .then(function (containerAgain) { const itemsAgain = containerAgain.get('items'); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); @@ -1309,63 +1286,59 @@ describe('Parse.Object testing', () => { return; } equal(itemsAgain.length, numItems, 'Should get the array back'); - itemsAgain.forEach(function(item, i) { + itemsAgain.forEach(function (item, i) { const newValue = i * 2; item.set('x', newValue); }); return Parse.Object.saveAll(itemsAgain); }) - .then(function() { + .then(function () { return Parse.Object.fetchAll(items); }) - .then(function(fetchedItemsAgain) { - equal( - fetchedItemsAgain.length, - numItems, - 'Number of items fetched should not change' - ); - fetchedItemsAgain.forEach(function(item, i) { + .then(function (fetchedItemsAgain) { + equal(fetchedItemsAgain.length, numItems, 'Number of items fetched should not change'); + fetchedItemsAgain.forEach(function (item, i) { equal(item.get('x'), i * 2); }); done(); }); }); - it('fetchAll no objects', function(done) { + it('fetchAll no objects', function (done) { Parse.Object.fetchAll([]) - .then(function(success) { + .then(function (success) { ok(Array.isArray(success), 'Should be able to fetchAll no objects'); done(); }) .catch(done.fail); }); - it('fetchAll updates dates', function(done) { + it('fetchAll updates dates', function (done) { let updatedObject; const object = new TestObject(); object.set('x', 7); object .save() - .then(function() { + .then(function () { const query = new Parse.Query(TestObject); return query.find(object.id); }) - .then(function(results) { + .then(function (results) { updatedObject = results[0]; updatedObject.set('x', 11); return updatedObject.save(); }) - .then(function() { + .then(function () { return Parse.Object.fetchAll([object]); }) - .then(function() { + .then(function () { equal(object.createdAt.getTime(), updatedObject.createdAt.getTime()); equal(object.updatedAt.getTime(), updatedObject.updatedAt.getTime()); done(); }); }); - xit('fetchAll backbone-style callbacks', function(done) { + xit('fetchAll backbone-style callbacks', function (done) { const numItems = 11; const container = new Container(); const items = []; @@ -1375,15 +1348,15 @@ describe('Parse.Object testing', () => { items.push(item); } Parse.Object.saveAll(items) - .then(function() { + .then(function () { container.set('items', items); return container.save(); }) - .then(function() { + .then(function () { const query = new Parse.Query(Container); return query.get(container.id); }) - .then(function(containerAgain) { + .then(function (containerAgain) { const itemsAgain = containerAgain.get('items'); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); @@ -1391,26 +1364,22 @@ describe('Parse.Object testing', () => { return; } equal(itemsAgain.length, numItems, 'Should get the array back'); - itemsAgain.forEach(function(item, i) { + itemsAgain.forEach(function (item, i) { const newValue = i * 2; item.set('x', newValue); }); return Parse.Object.saveAll(itemsAgain); }) - .then(function() { + .then(function () { return Parse.Object.fetchAll(items).then( - function(fetchedItemsAgain) { - equal( - fetchedItemsAgain.length, - numItems, - 'Number of items fetched should not change' - ); - fetchedItemsAgain.forEach(function(item, i) { + function (fetchedItemsAgain) { + equal(fetchedItemsAgain.length, numItems, 'Number of items fetched should not change'); + fetchedItemsAgain.forEach(function (item, i) { equal(item.get('x'), i * 2); }); done(); }, - function() { + function () { ok(false, 'Failed to fetchAll'); done(); } @@ -1418,17 +1387,17 @@ describe('Parse.Object testing', () => { }); }); - it('fetchAll error on multiple classes', function(done) { + it('fetchAll error on multiple classes', function (done) { const container = new Container(); container.set('item', new Item()); container.set('subcontainer', new Container()); return container .save() - .then(function() { + .then(function () { const query = new Parse.Query(Container); return query.get(container.id); }) - .then(function(containerAgain) { + .then(function (containerAgain) { const subContainerAgain = containerAgain.get('subcontainer'); const itemAgain = containerAgain.get('item'); const multiClassArray = [subContainerAgain, itemAgain]; @@ -1439,7 +1408,7 @@ describe('Parse.Object testing', () => { }); }); - it('fetchAll error on unsaved object', async function(done) { + it('fetchAll error on unsaved object', async function (done) { const unsavedObjectArray = [new TestObject()]; await Parse.Object.fetchAll(unsavedObjectArray).catch(e => { expect(e.code).toBe(Parse.Error.MISSING_OBJECT_ID); @@ -1447,7 +1416,7 @@ describe('Parse.Object testing', () => { }); }); - it('fetchAll error on deleted object', function(done) { + it('fetchAll error on deleted object', function (done) { const numItems = 11; const items = []; for (let i = 0; i < numItems; i++) { @@ -1456,14 +1425,14 @@ describe('Parse.Object testing', () => { items.push(item); } Parse.Object.saveAll(items) - .then(function() { + .then(function () { const query = new Parse.Query(Item); return query.get(items[0].id); }) - .then(function(objectToDelete) { + .then(function (objectToDelete) { return objectToDelete.destroy(); }) - .then(function(deletedObject) { + .then(function (deletedObject) { const nonExistentObject = new Item({ objectId: deletedObject.id }); const nonExistentObjectArray = [nonExistentObject, items[1]]; return Parse.Object.fetchAll(nonExistentObjectArray).catch(e => { @@ -1475,7 +1444,7 @@ describe('Parse.Object testing', () => { // TODO: Verify that with Sessions, this test is wrong... A fetch on // user should not bring down a session token. - xit('fetchAll User attributes get merged', function(done) { + xit('fetchAll User attributes get merged', function (done) { let sameUser; let user = new Parse.User(); user.set('username', 'asdf'); @@ -1483,28 +1452,28 @@ describe('Parse.Object testing', () => { user.set('foo', 'bar'); user .signUp() - .then(function() { + .then(function () { Parse.User.logOut(); const query = new Parse.Query(Parse.User); return query.get(user.id); }) - .then(function(userAgain) { + .then(function (userAgain) { user = userAgain; sameUser = new Parse.User(); sameUser.set('username', 'asdf'); sameUser.set('password', 'zxcv'); return sameUser.logIn(); }) - .then(function() { + .then(function () { ok(!user.getSessionToken(), 'user should not have a sessionToken'); ok(sameUser.getSessionToken(), 'sameUser should have a sessionToken'); sameUser.set('baz', 'qux'); return sameUser.save(); }) - .then(function() { + .then(function () { return Parse.Object.fetchAll([user]); }) - .then(function() { + .then(function () { equal(user.getSessionToken(), sameUser.getSessionToken()); equal(user.createdAt.getTime(), sameUser.createdAt.getTime()); equal(user.updatedAt.getTime(), sameUser.updatedAt.getTime()); @@ -1513,7 +1482,7 @@ describe('Parse.Object testing', () => { }); }); - it('fetchAllIfNeeded', function(done) { + it('fetchAllIfNeeded', function (done) { const numItems = 11; const container = new Container(); const items = []; @@ -1523,43 +1492,39 @@ describe('Parse.Object testing', () => { items.push(item); } Parse.Object.saveAll(items) - .then(function() { + .then(function () { container.set('items', items); return container.save(); }) - .then(function() { + .then(function () { const query = new Parse.Query(Container); return query.get(container.id); }) - .then(function(containerAgain) { + .then(function (containerAgain) { const itemsAgain = containerAgain.get('items'); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); done(); return; } - itemsAgain.forEach(function(item, i) { + itemsAgain.forEach(function (item, i) { item.set('x', i * 2); }); return Parse.Object.saveAll(itemsAgain); }) - .then(function() { + .then(function () { return Parse.Object.fetchAllIfNeeded(items); }) - .then(function(fetchedItems) { - equal( - fetchedItems.length, - numItems, - 'Number of items should not change' - ); - fetchedItems.forEach(function(item, i) { + .then(function (fetchedItems) { + equal(fetchedItems.length, numItems, 'Number of items should not change'); + fetchedItems.forEach(function (item, i) { equal(item.get('x'), i); }); done(); }); }); - xit('fetchAllIfNeeded backbone-style callbacks', function(done) { + xit('fetchAllIfNeeded backbone-style callbacks', function (done) { const numItems = 11; const container = new Container(); const items = []; @@ -1569,41 +1534,37 @@ describe('Parse.Object testing', () => { items.push(item); } Parse.Object.saveAll(items) - .then(function() { + .then(function () { container.set('items', items); return container.save(); }) - .then(function() { + .then(function () { const query = new Parse.Query(Container); return query.get(container.id); }) - .then(function(containerAgain) { + .then(function (containerAgain) { const itemsAgain = containerAgain.get('items'); if (!itemsAgain || !itemsAgain.forEach) { fail('no itemsAgain retrieved', itemsAgain); done(); return; } - itemsAgain.forEach(function(item, i) { + itemsAgain.forEach(function (item, i) { item.set('x', i * 2); }); return Parse.Object.saveAll(itemsAgain); }) - .then(function() { + .then(function () { const items = container.get('items'); return Parse.Object.fetchAllIfNeeded(items).then( - function(fetchedItems) { - equal( - fetchedItems.length, - numItems, - 'Number of items should not change' - ); - fetchedItems.forEach(function(item, j) { + function (fetchedItems) { + equal(fetchedItems.length, numItems, 'Number of items should not change'); + fetchedItems.forEach(function (item, j) { equal(item.get('x'), j); }); done(); }, - function() { + function () { ok(false, 'Failed to fetchAll'); done(); } @@ -1611,16 +1572,16 @@ describe('Parse.Object testing', () => { }); }); - it('fetchAllIfNeeded no objects', function(done) { + it('fetchAllIfNeeded no objects', function (done) { Parse.Object.fetchAllIfNeeded([]) - .then(function(success) { + .then(function (success) { ok(Array.isArray(success), 'Should be able to fetchAll no objects'); done(); }) .catch(done.fail); }); - it('fetchAllIfNeeded unsaved object', async function(done) { + it('fetchAllIfNeeded unsaved object', async function (done) { const unsavedObjectArray = [new TestObject()]; await Parse.Object.fetchAllIfNeeded(unsavedObjectArray).catch(e => { expect(e.code).toBe(Parse.Error.MISSING_OBJECT_ID); @@ -1628,17 +1589,17 @@ describe('Parse.Object testing', () => { }); }); - it('fetchAllIfNeeded error on multiple classes', function(done) { + it('fetchAllIfNeeded error on multiple classes', function (done) { const container = new Container(); container.set('item', new Item()); container.set('subcontainer', new Container()); return container .save() - .then(function() { + .then(function () { const query = new Parse.Query(Container); return query.get(container.id); }) - .then(function(containerAgain) { + .then(function (containerAgain) { const subContainerAgain = containerAgain.get('subcontainer'); const itemAgain = containerAgain.get('item'); const multiClassArray = [subContainerAgain, itemAgain]; @@ -1649,7 +1610,7 @@ describe('Parse.Object testing', () => { }); }); - it('Objects with className User', function(done) { + it('Objects with className User', function (done) { equal(Parse.CoreManager.get('PERFORM_USER_REWRITE'), true); const User1 = Parse.Object.extend({ className: 'User', @@ -1663,28 +1624,20 @@ describe('Parse.Object testing', () => { className: 'User', }); - equal( - User2.className, - 'User', - 'className is not rewritten when allowCustomUserClass(true)' - ); + equal(User2.className, 'User', 'className is not rewritten when allowCustomUserClass(true)'); // Set back to default so as not to break other tests. Parse.User.allowCustomUserClass(false); - equal( - Parse.CoreManager.get('PERFORM_USER_REWRITE'), - true, - 'PERFORM_USER_REWRITE is reset' - ); + equal(Parse.CoreManager.get('PERFORM_USER_REWRITE'), true, 'PERFORM_USER_REWRITE is reset'); const user = new User2(); user.set('name', 'Me'); - user.save({ height: 181 }).then(function(user) { + user.save({ height: 181 }).then(function (user) { equal(user.get('name'), 'Me'); equal(user.get('height'), 181); const query = new Parse.Query(User2); - query.get(user.id).then(function(user) { + query.get(user.id).then(function (user) { equal(user.className, 'User'); equal(user.get('name'), 'Me'); equal(user.get('height'), 181); @@ -1693,33 +1646,25 @@ describe('Parse.Object testing', () => { }); }); - it('create without data', function(done) { + it('create without data', function (done) { const t1 = new TestObject({ test: 'test' }); t1.save() - .then(function(t1) { + .then(function (t1) { const t2 = TestObject.createWithoutData(t1.id); return t2.fetch(); }) - .then(function(t2) { - equal( - t2.get('test'), - 'test', - 'Fetch should have grabbed ' + "'test' property." - ); + .then(function (t2) { + equal(t2.get('test'), 'test', 'Fetch should have grabbed ' + "'test' property."); const t3 = TestObject.createWithoutData(t2.id); t3.set('test', 'not test'); return t3.fetch(); }) .then( - function(t3) { - equal( - t3.get('test'), - 'test', - "Fetch should have grabbed server 'test' property." - ); + function (t3) { + equal(t3.get('test'), 'test', "Fetch should have grabbed server 'test' property."); done(); }, - function(error) { + function (error) { ok(false, error); done(); } diff --git a/spec/ParsePolygon.spec.js b/spec/ParsePolygon.spec.js index cc04c095..84675267 100644 --- a/spec/ParsePolygon.spec.js +++ b/spec/ParsePolygon.spec.js @@ -1,8 +1,6 @@ const TestObject = Parse.Object.extend('TestObject'); -const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter') - .default; -const mongoURI = - 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; +const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; +const mongoURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; const request = require('../lib/request'); const defaultHeaders = { 'X-Parse-Application-Id': 'test', @@ -14,8 +12,19 @@ describe('Parse.Polygon testing', () => { beforeAll(() => require('../lib/TestUtils').destroyAllDataPermanently()); it('polygon save open path', done => { - const coords = [[0, 0], [0, 1], [1, 1], [1, 0]]; - const closed = [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]; + const coords = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + ]; + const closed = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + [0, 0], + ]; const obj = new TestObject(); obj.set('polygon', new Parse.Polygon(coords)); return obj @@ -33,7 +42,13 @@ describe('Parse.Polygon testing', () => { }); it('polygon save closed path', done => { - const coords = [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]; + const coords = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + [0, 0], + ]; const obj = new TestObject(); obj.set('polygon', new Parse.Polygon(coords)); return obj @@ -51,8 +66,19 @@ describe('Parse.Polygon testing', () => { }); it('polygon equalTo (open/closed) path', done => { - const openPoints = [[0, 0], [0, 1], [1, 1], [1, 0]]; - const closedPoints = [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]; + const openPoints = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + ]; + const closedPoints = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + [0, 0], + ]; const openPolygon = new Parse.Polygon(openPoints); const closedPolygon = new Parse.Polygon(closedPoints); const obj = new TestObject(); @@ -81,9 +107,19 @@ describe('Parse.Polygon testing', () => { }); it('polygon update', done => { - const oldCoords = [[0, 0], [0, 1], [1, 1], [1, 0]]; + const oldCoords = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + ]; const oldPolygon = new Parse.Polygon(oldCoords); - const newCoords = [[2, 2], [2, 3], [3, 3], [3, 2]]; + const newCoords = [ + [2, 2], + [2, 3], + [3, 3], + [3, 2], + ]; const newPolygon = new Parse.Polygon(newCoords); const obj = new TestObject(); obj.set('polygon', oldPolygon); @@ -107,7 +143,13 @@ describe('Parse.Polygon testing', () => { }); it('polygon invalid value', done => { - const coords = [['foo', 'bar'], [0, 1], [1, 0], [1, 1], [0, 0]]; + const coords = [ + ['foo', 'bar'], + [0, 1], + [1, 0], + [1, 1], + [0, 0], + ]; const obj = new TestObject(); obj.set('polygon', { __type: 'Polygon', coordinates: coords }); return obj @@ -128,15 +170,30 @@ describe('Parse.Polygon testing', () => { }); it('polygon three different points minimum', done => { - const coords = [[0, 0], [0, 1], [0, 0]]; + const coords = [ + [0, 0], + [0, 1], + [0, 0], + ]; const obj = new TestObject(); obj.set('polygon', new Parse.Polygon(coords)); obj.save().then(done.fail, () => done()); }); it('polygon counterclockwise', done => { - const coords = [[1, 1], [0, 1], [0, 0], [1, 0]]; - const closed = [[1, 1], [0, 1], [0, 0], [1, 0], [1, 1]]; + const coords = [ + [1, 1], + [0, 1], + [0, 0], + [1, 0], + ]; + const closed = [ + [1, 1], + [0, 1], + [0, 0], + [1, 0], + [1, 1], + ]; const obj = new TestObject(); obj.set('polygon', new Parse.Polygon(coords)); obj @@ -157,9 +214,25 @@ describe('Parse.Polygon testing', () => { beforeAll(() => require('../lib/TestUtils').destroyAllDataPermanently()); it('polygonContain query', done => { - const points1 = [[0, 0], [0, 1], [1, 1], [1, 0]]; - const points2 = [[0, 0], [0, 2], [2, 2], [2, 0]]; - const points3 = [[10, 10], [10, 15], [15, 15], [15, 10], [10, 10]]; + const points1 = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + ]; + const points2 = [ + [0, 0], + [0, 2], + [2, 2], + [2, 0], + ]; + const points3 = [ + [10, 10], + [10, 15], + [15, 15], + [15, 10], + [10, 10], + ]; const polygon1 = new Parse.Polygon(points1); const polygon2 = new Parse.Polygon(points2); const polygon3 = new Parse.Polygon(points3); @@ -193,9 +266,25 @@ describe('Parse.Polygon testing', () => { }); it('polygonContain query no reverse input (Regression test for #4608)', done => { - const points1 = [[0.25, 0], [0.25, 1.25], [0.75, 1.25], [0.75, 0]]; - const points2 = [[0, 0], [0, 2], [2, 2], [2, 0]]; - const points3 = [[10, 10], [10, 15], [15, 15], [15, 10], [10, 10]]; + const points1 = [ + [0.25, 0], + [0.25, 1.25], + [0.75, 1.25], + [0.75, 0], + ]; + const points2 = [ + [0, 0], + [0, 2], + [2, 2], + [2, 0], + ]; + const points3 = [ + [10, 10], + [10, 15], + [15, 15], + [15, 10], + [10, 10], + ]; const polygon1 = new Parse.Polygon(points1); const polygon2 = new Parse.Polygon(points2); const polygon3 = new Parse.Polygon(points3); @@ -270,7 +359,12 @@ describe('Parse.Polygon testing', () => { }); it('polygonContain invalid input', done => { - const points = [[0, 0], [0, 1], [1, 1], [1, 0]]; + const points = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + ]; const polygon = new Parse.Polygon(points); const obj = new TestObject({ location: polygon }); obj @@ -297,7 +391,12 @@ describe('Parse.Polygon testing', () => { }); it('polygonContain invalid geoPoint', done => { - const points = [[0, 0], [0, 1], [1, 1], [1, 0]]; + const points = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + ]; const polygon = new Parse.Polygon(points); const obj = new TestObject({ location: polygon }); obj @@ -328,7 +427,13 @@ describe('Parse.Polygon testing', () => { describe_only_db('mongo')('Parse.Polygon testing', () => { beforeEach(() => require('../lib/TestUtils').destroyAllDataPermanently()); it('support 2d and 2dsphere', done => { - const coords = [[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]; + const coords = [ + [0, 0], + [0, 1], + [1, 1], + [1, 0], + [0, 0], + ]; // testings against REST API, use raw formats const polygon = { __type: 'Polygon', coordinates: coords }; const location = { __type: 'GeoPoint', latitude: 10, longitude: 10 }; @@ -363,9 +468,7 @@ describe_only_db('mongo')('Parse.Polygon testing', () => { .then(resp => { return request({ method: 'POST', - url: `http://localhost:8378/1/classes/TestObject/${ - resp.data.objectId - }`, + url: `http://localhost:8378/1/classes/TestObject/${resp.data.objectId}`, body: { _method: 'GET' }, headers: defaultHeaders, }); @@ -391,8 +494,21 @@ describe_only_db('mongo')('Parse.Polygon testing', () => { const config = Config.get('test'); // When stored the first point should be the last point - const input = [[12, 11], [14, 13], [16, 15], [18, 17]]; - const output = [[[11, 12], [13, 14], [15, 16], [17, 18], [11, 12]]]; + const input = [ + [12, 11], + [14, 13], + [16, 15], + [18, 17], + ]; + const output = [ + [ + [11, 12], + [13, 14], + [15, 16], + [17, 18], + [11, 12], + ], + ]; const obj = new TestObject(); obj.set('polygon', new Parse.Polygon(input)); obj @@ -408,7 +524,12 @@ describe_only_db('mongo')('Parse.Polygon testing', () => { }); it('polygon loop is not valid', done => { - const coords = [[0, 0], [0, 1], [1, 0], [1, 1]]; + const coords = [ + [0, 0], + [0, 1], + [1, 0], + [1, 1], + ]; const obj = new TestObject(); obj.set('polygon', new Parse.Polygon(coords)); obj.save().then(done.fail, () => done()); diff --git a/spec/ParsePubSub.spec.js b/spec/ParsePubSub.spec.js index 3159fc7f..53bdd0b6 100644 --- a/spec/ParsePubSub.spec.js +++ b/spec/ParsePubSub.spec.js @@ -1,17 +1,13 @@ const ParsePubSub = require('../lib/LiveQuery/ParsePubSub').ParsePubSub; -describe('ParsePubSub', function() { - beforeEach(function(done) { +describe('ParsePubSub', function () { + beforeEach(function (done) { // Mock RedisPubSub const mockRedisPubSub = { createPublisher: jasmine.createSpy('createPublisherRedis'), createSubscriber: jasmine.createSpy('createSubscriberRedis'), }; - jasmine.mockLibrary( - '../lib/Adapters/PubSub/RedisPubSub', - 'RedisPubSub', - mockRedisPubSub - ); + jasmine.mockLibrary('../lib/Adapters/PubSub/RedisPubSub', 'RedisPubSub', mockRedisPubSub); // Mock EventEmitterPubSub const mockEventEmitterPubSub = { createPublisher: jasmine.createSpy('createPublisherEventEmitter'), @@ -25,14 +21,13 @@ describe('ParsePubSub', function() { done(); }); - it('can create redis publisher', function() { + it('can create redis publisher', function () { ParsePubSub.createPublisher({ redisURL: 'redisURL', redisOptions: { socket_keepalive: true }, }); - const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub') - .RedisPubSub; + const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub').RedisPubSub; const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub') .EventEmitterPubSub; expect(RedisPubSub.createPublisher).toHaveBeenCalledWith({ @@ -42,25 +37,23 @@ describe('ParsePubSub', function() { expect(EventEmitterPubSub.createPublisher).not.toHaveBeenCalled(); }); - it('can create event emitter publisher', function() { + it('can create event emitter publisher', function () { ParsePubSub.createPublisher({}); - const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub') - .RedisPubSub; + const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub').RedisPubSub; const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub') .EventEmitterPubSub; expect(RedisPubSub.createPublisher).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createPublisher).toHaveBeenCalled(); }); - it('can create redis subscriber', function() { + it('can create redis subscriber', function () { ParsePubSub.createSubscriber({ redisURL: 'redisURL', redisOptions: { socket_keepalive: true }, }); - const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub') - .RedisPubSub; + const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub').RedisPubSub; const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub') .EventEmitterPubSub; expect(RedisPubSub.createSubscriber).toHaveBeenCalledWith({ @@ -70,18 +63,17 @@ describe('ParsePubSub', function() { expect(EventEmitterPubSub.createSubscriber).not.toHaveBeenCalled(); }); - it('can create event emitter subscriber', function() { + it('can create event emitter subscriber', function () { ParsePubSub.createSubscriber({}); - const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub') - .RedisPubSub; + const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub').RedisPubSub; const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub') .EventEmitterPubSub; expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); expect(EventEmitterPubSub.createSubscriber).toHaveBeenCalled(); }); - it('can create publisher/sub with custom adapter', function() { + it('can create publisher/sub with custom adapter', function () { const adapter = { createPublisher: jasmine.createSpy('createPublisher'), createSubscriber: jasmine.createSpy('createSubscriber'), @@ -96,8 +88,7 @@ describe('ParsePubSub', function() { }); expect(adapter.createSubscriber).toHaveBeenCalled(); - const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub') - .RedisPubSub; + const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub').RedisPubSub; const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub') .EventEmitterPubSub; expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); @@ -106,27 +97,26 @@ describe('ParsePubSub', function() { expect(EventEmitterPubSub.createPublisher).not.toHaveBeenCalled(); }); - it('can create publisher/sub with custom function adapter', function() { + it('can create publisher/sub with custom function adapter', function () { const adapter = { createPublisher: jasmine.createSpy('createPublisher'), createSubscriber: jasmine.createSpy('createSubscriber'), }; ParsePubSub.createPublisher({ - pubSubAdapter: function() { + pubSubAdapter: function () { return adapter; }, }); expect(adapter.createPublisher).toHaveBeenCalled(); ParsePubSub.createSubscriber({ - pubSubAdapter: function() { + pubSubAdapter: function () { return adapter; }, }); expect(adapter.createSubscriber).toHaveBeenCalled(); - const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub') - .RedisPubSub; + const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub').RedisPubSub; const EventEmitterPubSub = require('../lib/Adapters/PubSub/EventEmitterPubSub') .EventEmitterPubSub; expect(RedisPubSub.createSubscriber).not.toHaveBeenCalled(); @@ -135,11 +125,8 @@ describe('ParsePubSub', function() { expect(EventEmitterPubSub.createPublisher).not.toHaveBeenCalled(); }); - afterEach(function() { + afterEach(function () { jasmine.restoreLibrary('../lib/Adapters/PubSub/RedisPubSub', 'RedisPubSub'); - jasmine.restoreLibrary( - '../lib/Adapters/PubSub/EventEmitterPubSub', - 'EventEmitterPubSub' - ); + jasmine.restoreLibrary('../lib/Adapters/PubSub/EventEmitterPubSub', 'EventEmitterPubSub'); }); }); diff --git a/spec/ParseQuery.Aggregate.spec.js b/spec/ParseQuery.Aggregate.spec.js index 8c9cd2a6..598ed51a 100644 --- a/spec/ParseQuery.Aggregate.spec.js +++ b/spec/ParseQuery.Aggregate.spec.js @@ -128,15 +128,9 @@ describe('Parse.Query Aggregate testing', () => { get(Parse.serverURL + '/aggregate/TestObject', options) .then(resp => { expect(resp.results.length).toBe(3); - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); - expect( - Object.prototype.hasOwnProperty.call(resp.results[1], 'objectId') - ).toBe(true); - expect( - Object.prototype.hasOwnProperty.call(resp.results[2], 'objectId') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[1], 'objectId')).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[2], 'objectId')).toBe(true); expect(resp.results[0].objectId).not.toBe(undefined); expect(resp.results[1].objectId).not.toBe(undefined); expect(resp.results[2].objectId).not.toBe(undefined); @@ -155,15 +149,9 @@ describe('Parse.Query Aggregate testing', () => { }); const resp = await get(Parse.serverURL + '/aggregate/TestObject', options); expect(resp.results.length).toBe(3); - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); - expect( - Object.prototype.hasOwnProperty.call(resp.results[1], 'objectId') - ).toBe(true); - expect( - Object.prototype.hasOwnProperty.call(resp.results[2], 'objectId') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[1], 'objectId')).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[2], 'objectId')).toBe(true); expect(resp.results[0].objectId).not.toBe(undefined); expect(resp.results[1].objectId).not.toBe(undefined); expect(resp.results[2].objectId).not.toBe(undefined); @@ -321,15 +309,12 @@ describe('Parse.Query Aggregate testing', () => { get(Parse.serverURL + '/aggregate/TestObject', options) .then(resp => { expect(resp.results.length).toBe(2); - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); - expect( - Object.prototype.hasOwnProperty.call(resp.results[1], 'objectId') - ).toBe(true); - expect( - resp.results.sort((a, b) => (a.objectId > b.objectId ? 1 : -1)) - ).toEqual([{ objectId: 10 }, { objectId: 20 }]); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[1], 'objectId')).toBe(true); + expect(resp.results.sort((a, b) => (a.objectId > b.objectId ? 1 : -1))).toEqual([ + { objectId: 10 }, + { objectId: 20 }, + ]); done(); }) .catch(done.fail); @@ -433,12 +418,8 @@ describe('Parse.Query Aggregate testing', () => { expect(results.length).toEqual(4); for (let i = 0; i < results.length; i++) { const item = results[i]; - expect(Object.prototype.hasOwnProperty.call(item, 'updatedAt')).toEqual( - true - ); - expect(Object.prototype.hasOwnProperty.call(item, 'objectId')).toEqual( - false - ); + expect(Object.prototype.hasOwnProperty.call(item, 'updatedAt')).toEqual(true); + expect(Object.prototype.hasOwnProperty.call(item, 'objectId')).toEqual(false); } done(); }); @@ -529,12 +510,8 @@ describe('Parse.Query Aggregate testing', () => { }) .then(results => { expect(results.length).toEqual(3); - expect(results.some(result => result.objectId === pointer1.id)).toEqual( - true - ); - expect(results.some(result => result.objectId === pointer2.id)).toEqual( - true - ); + expect(results.some(result => result.objectId === pointer1.id)).toEqual(true); + expect(results.some(result => result.objectId === pointer2.id)).toEqual(true); expect(results.some(result => result.objectId === null)).toEqual(true); done(); }); @@ -548,9 +525,7 @@ describe('Parse.Query Aggregate testing', () => { }); get(Parse.serverURL + '/aggregate/TestObject', options) .then(resp => { - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); expect(resp.results[0].objectId).toBe(null); expect(resp.results[0].total).toBe(50); done(); @@ -566,9 +541,7 @@ describe('Parse.Query Aggregate testing', () => { }); get(Parse.serverURL + '/aggregate/TestObject', options) .then(resp => { - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); expect(resp.results[0].objectId).toBe(null); expect(resp.results[0].total).toBe(4); done(); @@ -584,9 +557,7 @@ describe('Parse.Query Aggregate testing', () => { }); get(Parse.serverURL + '/aggregate/TestObject', options) .then(resp => { - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); expect(resp.results[0].objectId).toBe(null); expect(resp.results[0].minScore).toBe(10); done(); @@ -602,9 +573,7 @@ describe('Parse.Query Aggregate testing', () => { }); get(Parse.serverURL + '/aggregate/TestObject', options) .then(resp => { - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); expect(resp.results[0].objectId).toBe(null); expect(resp.results[0].maxScore).toBe(20); done(); @@ -620,9 +589,7 @@ describe('Parse.Query Aggregate testing', () => { }); get(Parse.serverURL + '/aggregate/TestObject', options) .then(resp => { - expect( - Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(resp.results[0], 'objectId')).toBe(true); expect(resp.results[0].objectId).toBe(null); expect(resp.results[0].avgScore).toBe(12.5); done(); @@ -783,10 +750,7 @@ describe('Parse.Query Aggregate testing', () => { const options = Object.assign({}, masterKeyOptions, { body: { match: { - $or: [ - { score: { $gt: 15, $lt: 25 } }, - { views: { $gt: 750, $lt: 850 } }, - ], + $or: [{ score: { $gt: 15, $lt: 25 } }, { views: { $gt: 750, $lt: 850 } }], }, }, }); @@ -854,12 +818,8 @@ describe('Parse.Query Aggregate testing', () => { expect(results.length).toEqual(2); expect(results[0].pointer.objectId).toEqual(pointer1.id); expect(results[1].pointer.objectId).toEqual(pointer1.id); - expect(results.some(result => result.objectId === obj1.id)).toEqual( - true - ); - expect(results.some(result => result.objectId === obj3.id)).toEqual( - true - ); + expect(results.some(result => result.objectId === obj1.id)).toEqual(true); + expect(results.some(result => result.objectId === obj3.id)).toEqual(true); done(); }); }); @@ -880,11 +840,7 @@ describe('Parse.Query Aggregate testing', () => { Parse.Object.saveAll([obj1, obj2]) .then(() => { const now = new Date(); - const today = new Date( - now.getFullYear(), - now.getMonth(), - now.getDate() - ); + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const pipeline = [{ match: { createdAt: { $gte: today } } }]; const query = new Parse.Query(TestObject); return query.aggregate(pipeline); @@ -903,11 +859,7 @@ describe('Parse.Query Aggregate testing', () => { Parse.Object.saveAll([obj1, obj2]) .then(() => { const now = new Date(); - const today = new Date( - now.getFullYear(), - now.getMonth(), - now.getDate() - ); + const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const pipeline = [{ match: { updatedAt: { $gte: today } } }]; const query = new Parse.Query(TestObject); return query.aggregate(pipeline); @@ -926,11 +878,7 @@ describe('Parse.Query Aggregate testing', () => { Parse.Object.saveAll([obj1, obj2]) .then(() => { const now = new Date(); - const future = new Date( - now.getFullYear(), - now.getMonth() + 1, - now.getDate() - ); + const future = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate()); const pipeline = [{ match: { createdAt: future } }]; const query = new Parse.Query(TestObject); return query.aggregate(pipeline); @@ -958,12 +906,8 @@ describe('Parse.Query Aggregate testing', () => { expect(results.length).toEqual(2); expect(results[0].pointer.objectId).toEqual(pointer.id); expect(results[1].pointer.objectId).toEqual(pointer.id); - expect(results.some(result => result.objectId === obj1.id)).toEqual( - true - ); - expect(results.some(result => result.objectId === obj2.id)).toEqual( - true - ); + expect(results.some(result => result.objectId === obj1.id)).toEqual(true); + expect(results.some(result => result.objectId === obj2.id)).toEqual(true); done(); }); }); @@ -1092,9 +1036,7 @@ describe('Parse.Query Aggregate testing', () => { .then(resp => { expect(resp.results.length).toBe(2); resp.results.forEach(result => { - expect(Object.prototype.hasOwnProperty.call(result, 'objectId')).toBe( - true - ); + expect(Object.prototype.hasOwnProperty.call(result, 'objectId')).toBe(true); expect(result.name).toBe(undefined); expect(result.sender).toBe(undefined); expect(result.size).toBe(undefined); @@ -1212,12 +1154,8 @@ describe('Parse.Query Aggregate testing', () => { }) .then(results => { expect(results.length).toEqual(2); - expect(results.some(result => result.objectId === pointer1.id)).toEqual( - true - ); - expect(results.some(result => result.objectId === pointer2.id)).toEqual( - true - ); + expect(results.some(result => result.objectId === pointer1.id)).toEqual(true); + expect(results.some(result => result.objectId === pointer2.id)).toEqual(true); done(); }); }); @@ -1374,74 +1312,66 @@ describe('Parse.Query Aggregate testing', () => { }); }); - it_exclude_dbs(['postgres'])( - 'aggregate allow multiple of same stage', - done => { - const pointer1 = new TestObject({ value: 1 }); - const pointer2 = new TestObject({ value: 2 }); - const pointer3 = new TestObject({ value: 3 }); + it_exclude_dbs(['postgres'])('aggregate allow multiple of same stage', done => { + const pointer1 = new TestObject({ value: 1 }); + const pointer2 = new TestObject({ value: 2 }); + const pointer3 = new TestObject({ value: 3 }); - const obj1 = new TestObject({ pointer: pointer1, name: 'Hello' }); - const obj2 = new TestObject({ pointer: pointer2, name: 'Hello' }); - const obj3 = new TestObject({ pointer: pointer3, name: 'World' }); + const obj1 = new TestObject({ pointer: pointer1, name: 'Hello' }); + const obj2 = new TestObject({ pointer: pointer2, name: 'Hello' }); + const obj3 = new TestObject({ pointer: pointer3, name: 'World' }); - const options = Object.assign({}, masterKeyOptions, { - body: { - pipeline: [ - { - match: { name: 'Hello' }, + const options = Object.assign({}, masterKeyOptions, { + body: { + pipeline: [ + { + match: { name: 'Hello' }, + }, + { + // Transform className$objectId to objectId and store in new field tempPointer + project: { + tempPointer: { $substr: ['$_p_pointer', 11, -1] }, // Remove TestObject$ }, - { - // Transform className$objectId to objectId and store in new field tempPointer - project: { - tempPointer: { $substr: ['$_p_pointer', 11, -1] }, // Remove TestObject$ - }, + }, + { + // Left Join, replace objectId stored in tempPointer with an actual object + lookup: { + from: 'test_TestObject', + localField: 'tempPointer', + foreignField: '_id', + as: 'tempPointer', }, - { - // Left Join, replace objectId stored in tempPointer with an actual object - lookup: { - from: 'test_TestObject', - localField: 'tempPointer', - foreignField: '_id', - as: 'tempPointer', - }, + }, + { + // lookup returns an array, Deconstructs an array field to objects + unwind: { + path: '$tempPointer', }, - { - // lookup returns an array, Deconstructs an array field to objects - unwind: { - path: '$tempPointer', - }, - }, - { - match: { 'tempPointer.value': 2 }, - }, - ], - }, + }, + { + match: { 'tempPointer.value': 2 }, + }, + ], + }, + }); + Parse.Object.saveAll([pointer1, pointer2, pointer3, obj1, obj2, obj3]) + .then(() => { + return get(Parse.serverURL + '/aggregate/TestObject', options); + }) + .then(resp => { + expect(resp.results.length).toEqual(1); + expect(resp.results[0].tempPointer.value).toEqual(2); + done(); }); - Parse.Object.saveAll([pointer1, pointer2, pointer3, obj1, obj2, obj3]) - .then(() => { - return get(Parse.serverURL + '/aggregate/TestObject', options); - }) - .then(resp => { - expect(resp.results.length).toEqual(1); - expect(resp.results[0].tempPointer.value).toEqual(2); - done(); - }); - } - ); + }); it_only_db('mongo')('aggregate geoNear with location query', async () => { // Create geo index which is required for `geoNear` query const database = Config.get(Parse.applicationId).database; const schema = await new Parse.Schema('GeoObject').save(); - await database.adapter.ensureIndex( - 'GeoObject', - schema, - ['location'], - undefined, - false, - { indexType: '2dsphere' } - ); + await database.adapter.ensureIndex('GeoObject', schema, ['location'], undefined, false, { + indexType: '2dsphere', + }); // Create objects const GeoObject = Parse.Object.extend('GeoObject'); const obj1 = new GeoObject({ @@ -1537,53 +1467,50 @@ describe('Parse.Query Aggregate testing', () => { expect(results.length).toEqual(3); }); - it_only_db('mongo')( - 'aggregate geoNear with near legacy coordinate pair', - async () => { - // Create geo index which is required for `geoNear` query - const database = Config.get(Parse.applicationId).database; - const schema = await new Parse.Schema('GeoObject').save(); - await database.adapter.ensureIndex( - 'GeoObject', - schema, - ['location'], - undefined, - false, - '2dsphere' - ); - // Create objects - const GeoObject = Parse.Object.extend('GeoObject'); - const obj1 = new GeoObject({ - value: 1, - location: new Parse.GeoPoint(1, 1), - date: new Date(1), - }); - const obj2 = new GeoObject({ - value: 2, - location: new Parse.GeoPoint(2, 1), - date: new Date(2), - }); - const obj3 = new GeoObject({ - value: 3, - location: new Parse.GeoPoint(3, 1), - date: new Date(3), - }); - await Parse.Object.saveAll([obj1, obj2, obj3]); - // Create query - const pipeline = [ - { - geoNear: { - near: [1, 1], - key: 'location', - spherical: true, - distanceField: 'dist', - }, + it_only_db('mongo')('aggregate geoNear with near legacy coordinate pair', async () => { + // Create geo index which is required for `geoNear` query + const database = Config.get(Parse.applicationId).database; + const schema = await new Parse.Schema('GeoObject').save(); + await database.adapter.ensureIndex( + 'GeoObject', + schema, + ['location'], + undefined, + false, + '2dsphere' + ); + // Create objects + const GeoObject = Parse.Object.extend('GeoObject'); + const obj1 = new GeoObject({ + value: 1, + location: new Parse.GeoPoint(1, 1), + date: new Date(1), + }); + const obj2 = new GeoObject({ + value: 2, + location: new Parse.GeoPoint(2, 1), + date: new Date(2), + }); + const obj3 = new GeoObject({ + value: 3, + location: new Parse.GeoPoint(3, 1), + date: new Date(3), + }); + await Parse.Object.saveAll([obj1, obj2, obj3]); + // Create query + const pipeline = [ + { + geoNear: { + near: [1, 1], + key: 'location', + spherical: true, + distanceField: 'dist', }, - ]; - const query = new Parse.Query(GeoObject); - const results = await query.aggregate(pipeline); - // Check results - expect(results.length).toEqual(3); - } - ); + }, + ]; + const query = new Parse.Query(GeoObject); + const results = await query.aggregate(pipeline); + // Check results + expect(results.length).toEqual(3); + }); }); diff --git a/spec/ParseQuery.FullTextSearch.spec.js b/spec/ParseQuery.FullTextSearch.spec.js index 21d1c2a2..99118d10 100644 --- a/spec/ParseQuery.FullTextSearch.spec.js +++ b/spec/ParseQuery.FullTextSearch.spec.js @@ -314,291 +314,277 @@ describe('Parse.Query Full Text Search testing', () => { }); }); -describe_only_db('mongo')( - '[mongodb] Parse.Query Full Text Search testing', - () => { - it('fullTextSearch: does not create text index if compound index exist', done => { - fullTextHelper() - .then(() => { - return databaseAdapter.dropAllIndexes('TestObject'); - }) - .then(() => { - return databaseAdapter.getIndexes('TestObject'); - }) - .then(indexes => { - expect(indexes.length).toEqual(1); - return databaseAdapter.createIndex('TestObject', { - subject: 'text', - comment: 'text', - }); - }) - .then(() => { - return databaseAdapter.getIndexes('TestObject'); - }) - .then(indexes => { - expect(indexes.length).toEqual(2); - const where = { - subject: { - $text: { - $search: { - $term: 'coffee', - }, +describe_only_db('mongo')('[mongodb] Parse.Query Full Text Search testing', () => { + it('fullTextSearch: does not create text index if compound index exist', done => { + fullTextHelper() + .then(() => { + return databaseAdapter.dropAllIndexes('TestObject'); + }) + .then(() => { + return databaseAdapter.getIndexes('TestObject'); + }) + .then(indexes => { + expect(indexes.length).toEqual(1); + return databaseAdapter.createIndex('TestObject', { + subject: 'text', + comment: 'text', + }); + }) + .then(() => { + return databaseAdapter.getIndexes('TestObject'); + }) + .then(indexes => { + expect(indexes.length).toEqual(2); + const where = { + subject: { + $text: { + $search: { + $term: 'coffee', }, }, - }; - return request({ - method: 'POST', - url: 'http://localhost:8378/1/classes/TestObject', - body: { where, _method: 'GET' }, - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-REST-API-Key': 'test', - 'Content-Type': 'application/json', - }, - }); - }) - .then(resp => { - expect(resp.data.results.length).toEqual(3); - return databaseAdapter.getIndexes('TestObject'); - }) - .then(indexes => { - expect(indexes.length).toEqual(2); - request({ - url: 'http://localhost:8378/1/schemas/TestObject', - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-Master-Key': 'test', - 'Content-Type': 'application/json', - }, - }).then(response => { - const body = response.data; - expect(body.indexes._id_).toBeDefined(); - expect(body.indexes._id_._id).toEqual(1); - expect(body.indexes.subject_text_comment_text).toBeDefined(); - expect(body.indexes.subject_text_comment_text.subject).toEqual( - 'text' - ); - expect(body.indexes.subject_text_comment_text.comment).toEqual( - 'text' - ); - done(); - }); - }) - .catch(done.fail); - }); - - it('fullTextSearch: does not create text index if schema compound index exist', done => { - fullTextHelper() - .then(() => { - return databaseAdapter.dropAllIndexes('TestObject'); - }) - .then(() => { - return databaseAdapter.getIndexes('TestObject'); - }) - .then(indexes => { - expect(indexes.length).toEqual(1); - return request({ - method: 'PUT', - url: 'http://localhost:8378/1/schemas/TestObject', - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-REST-API-Key': 'test', - 'X-Parse-Master-Key': 'test', - 'Content-Type': 'application/json', - }, - body: { - indexes: { - text_test: { subject: 'text', comment: 'text' }, - }, - }, - }); - }) - .then(() => { - return databaseAdapter.getIndexes('TestObject'); - }) - .then(indexes => { - expect(indexes.length).toEqual(2); - const where = { - subject: { - $text: { - $search: { - $term: 'coffee', - }, - }, - }, - }; - return request({ - method: 'POST', - url: 'http://localhost:8378/1/classes/TestObject', - body: { where, _method: 'GET' }, - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-REST-API-Key': 'test', - 'Content-Type': 'application/json', - }, - }); - }) - .then(resp => { - expect(resp.data.results.length).toEqual(3); - return databaseAdapter.getIndexes('TestObject'); - }) - .then(indexes => { - expect(indexes.length).toEqual(2); - request({ - url: 'http://localhost:8378/1/schemas/TestObject', - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-Master-Key': 'test', - 'Content-Type': 'application/json', - }, - }).then(response => { - const body = response.data; - expect(body.indexes._id_).toBeDefined(); - expect(body.indexes._id_._id).toEqual(1); - expect(body.indexes.text_test).toBeDefined(); - expect(body.indexes.text_test.subject).toEqual('text'); - expect(body.indexes.text_test.comment).toEqual('text'); - done(); - }); - }) - .catch(done.fail); - }); - - it('fullTextSearch: $diacriticSensitive - false', done => { - fullTextHelper() - .then(() => { - const where = { - subject: { - $text: { - $search: { - $term: 'CAFÉ', - $diacriticSensitive: false, - }, - }, - }, - }; - return request({ - method: 'POST', - url: 'http://localhost:8378/1/classes/TestObject', - body: { where, _method: 'GET' }, - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-REST-API-Key': 'test', - 'Content-Type': 'application/json', - }, - }); - }) - .then(resp => { - expect(resp.data.results.length).toBe(2); - done(); - }, done.fail); - }); - - it('fullTextSearch: $caseSensitive', done => { - fullTextHelper() - .then(() => { - const where = { - subject: { - $text: { - $search: { - $term: 'Coffee', - $caseSensitive: true, - }, - }, - }, - }; - return request({ - method: 'POST', - url: 'http://localhost:8378/1/classes/TestObject', - body: { where, _method: 'GET' }, - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-REST-API-Key': 'test', - 'Content-Type': 'application/json', - }, - }); - }) - .then(resp => { - expect(resp.data.results.length).toBe(1); - done(); - }, done.fail); - }); - } -); - -describe_only_db('postgres')( - '[postgres] Parse.Query Full Text Search testing', - () => { - it('fullTextSearch: $diacriticSensitive - false', done => { - fullTextHelper() - .then(() => { - const where = { - subject: { - $text: { - $search: { - $term: 'CAFÉ', - $diacriticSensitive: false, - }, - }, - }, - }; - return request({ - method: 'POST', - url: 'http://localhost:8378/1/classes/TestObject', - body: { where, _method: 'GET' }, - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-REST-API-Key': 'test', - 'Content-Type': 'application/json', - }, - }); - }) - .then(resp => { - fail( - `$diacriticSensitive - false should not supported: ${JSON.stringify( - resp - )}` - ); - done(); - }) - .catch(err => { - expect(err.data.code).toEqual(Parse.Error.INVALID_JSON); + }, + }; + return request({ + method: 'POST', + url: 'http://localhost:8378/1/classes/TestObject', + body: { where, _method: 'GET' }, + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-REST-API-Key': 'test', + 'Content-Type': 'application/json', + }, + }); + }) + .then(resp => { + expect(resp.data.results.length).toEqual(3); + return databaseAdapter.getIndexes('TestObject'); + }) + .then(indexes => { + expect(indexes.length).toEqual(2); + request({ + url: 'http://localhost:8378/1/schemas/TestObject', + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-Master-Key': 'test', + 'Content-Type': 'application/json', + }, + }).then(response => { + const body = response.data; + expect(body.indexes._id_).toBeDefined(); + expect(body.indexes._id_._id).toEqual(1); + expect(body.indexes.subject_text_comment_text).toBeDefined(); + expect(body.indexes.subject_text_comment_text.subject).toEqual('text'); + expect(body.indexes.subject_text_comment_text.comment).toEqual('text'); done(); }); - }); + }) + .catch(done.fail); + }); - it('fullTextSearch: $caseSensitive', done => { - fullTextHelper() - .then(() => { - const where = { - subject: { - $text: { - $search: { - $term: 'Coffee', - $caseSensitive: true, - }, + it('fullTextSearch: does not create text index if schema compound index exist', done => { + fullTextHelper() + .then(() => { + return databaseAdapter.dropAllIndexes('TestObject'); + }) + .then(() => { + return databaseAdapter.getIndexes('TestObject'); + }) + .then(indexes => { + expect(indexes.length).toEqual(1); + return request({ + method: 'PUT', + url: 'http://localhost:8378/1/schemas/TestObject', + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-REST-API-Key': 'test', + 'X-Parse-Master-Key': 'test', + 'Content-Type': 'application/json', + }, + body: { + indexes: { + text_test: { subject: 'text', comment: 'text' }, + }, + }, + }); + }) + .then(() => { + return databaseAdapter.getIndexes('TestObject'); + }) + .then(indexes => { + expect(indexes.length).toEqual(2); + const where = { + subject: { + $text: { + $search: { + $term: 'coffee', }, }, - }; - return request({ - method: 'POST', - url: 'http://localhost:8378/1/classes/TestObject', - body: { where, _method: 'GET' }, - headers: { - 'X-Parse-Application-Id': 'test', - 'X-Parse-REST-API-Key': 'test', - 'Content-Type': 'application/json', - }, - }); - }) - .then(resp => { - fail(`$caseSensitive should not supported: ${JSON.stringify(resp)}`); - done(); - }) - .catch(err => { - expect(err.data.code).toEqual(Parse.Error.INVALID_JSON); + }, + }; + return request({ + method: 'POST', + url: 'http://localhost:8378/1/classes/TestObject', + body: { where, _method: 'GET' }, + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-REST-API-Key': 'test', + 'Content-Type': 'application/json', + }, + }); + }) + .then(resp => { + expect(resp.data.results.length).toEqual(3); + return databaseAdapter.getIndexes('TestObject'); + }) + .then(indexes => { + expect(indexes.length).toEqual(2); + request({ + url: 'http://localhost:8378/1/schemas/TestObject', + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-Master-Key': 'test', + 'Content-Type': 'application/json', + }, + }).then(response => { + const body = response.data; + expect(body.indexes._id_).toBeDefined(); + expect(body.indexes._id_._id).toEqual(1); + expect(body.indexes.text_test).toBeDefined(); + expect(body.indexes.text_test.subject).toEqual('text'); + expect(body.indexes.text_test.comment).toEqual('text'); done(); }); - }); - } -); + }) + .catch(done.fail); + }); + + it('fullTextSearch: $diacriticSensitive - false', done => { + fullTextHelper() + .then(() => { + const where = { + subject: { + $text: { + $search: { + $term: 'CAFÉ', + $diacriticSensitive: false, + }, + }, + }, + }; + return request({ + method: 'POST', + url: 'http://localhost:8378/1/classes/TestObject', + body: { where, _method: 'GET' }, + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-REST-API-Key': 'test', + 'Content-Type': 'application/json', + }, + }); + }) + .then(resp => { + expect(resp.data.results.length).toBe(2); + done(); + }, done.fail); + }); + + it('fullTextSearch: $caseSensitive', done => { + fullTextHelper() + .then(() => { + const where = { + subject: { + $text: { + $search: { + $term: 'Coffee', + $caseSensitive: true, + }, + }, + }, + }; + return request({ + method: 'POST', + url: 'http://localhost:8378/1/classes/TestObject', + body: { where, _method: 'GET' }, + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-REST-API-Key': 'test', + 'Content-Type': 'application/json', + }, + }); + }) + .then(resp => { + expect(resp.data.results.length).toBe(1); + done(); + }, done.fail); + }); +}); + +describe_only_db('postgres')('[postgres] Parse.Query Full Text Search testing', () => { + it('fullTextSearch: $diacriticSensitive - false', done => { + fullTextHelper() + .then(() => { + const where = { + subject: { + $text: { + $search: { + $term: 'CAFÉ', + $diacriticSensitive: false, + }, + }, + }, + }; + return request({ + method: 'POST', + url: 'http://localhost:8378/1/classes/TestObject', + body: { where, _method: 'GET' }, + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-REST-API-Key': 'test', + 'Content-Type': 'application/json', + }, + }); + }) + .then(resp => { + fail(`$diacriticSensitive - false should not supported: ${JSON.stringify(resp)}`); + done(); + }) + .catch(err => { + expect(err.data.code).toEqual(Parse.Error.INVALID_JSON); + done(); + }); + }); + + it('fullTextSearch: $caseSensitive', done => { + fullTextHelper() + .then(() => { + const where = { + subject: { + $text: { + $search: { + $term: 'Coffee', + $caseSensitive: true, + }, + }, + }, + }; + return request({ + method: 'POST', + url: 'http://localhost:8378/1/classes/TestObject', + body: { where, _method: 'GET' }, + headers: { + 'X-Parse-Application-Id': 'test', + 'X-Parse-REST-API-Key': 'test', + 'Content-Type': 'application/json', + }, + }); + }) + .then(resp => { + fail(`$caseSensitive should not supported: ${JSON.stringify(resp)}`); + done(); + }) + .catch(err => { + expect(err.data.code).toEqual(Parse.Error.INVALID_JSON); + done(); + }); + }); +}); diff --git a/spec/ParseQuery.hint.spec.js b/spec/ParseQuery.hint.spec.js index 43f1c4e9..156c7325 100644 --- a/spec/ParseQuery.hint.spec.js +++ b/spec/ParseQuery.hint.spec.js @@ -32,18 +32,10 @@ describe_only_db('mongo')('Parse.Query hint', () => { const object = new TestObject(); await object.save(); - const collection = await config.database.adapter._adaptiveCollection( - 'TestObject' - ); - let explain = await collection._rawFind( - { _id: object.id }, - { explain: true } - ); + const collection = await config.database.adapter._adaptiveCollection('TestObject'); + let explain = await collection._rawFind({ _id: object.id }, { explain: true }); expect(explain.queryPlanner.winningPlan.stage).toBe('IDHACK'); - explain = await collection._rawFind( - { _id: object.id }, - { hint: '_id_', explain: true } - ); + explain = await collection._rawFind({ _id: object.id }, { hint: '_id_', explain: true }); expect(explain.queryPlanner.winningPlan.stage).toBe('FETCH'); expect(explain.queryPlanner.winningPlan.inputStage.indexName).toBe('_id_'); }); @@ -52,18 +44,10 @@ describe_only_db('mongo')('Parse.Query hint', () => { const object = new TestObject(); await object.save(); - const collection = await config.database.adapter._adaptiveCollection( - 'TestObject' - ); - let explain = await collection._rawFind( - { _id: object.id }, - { explain: true } - ); + const collection = await config.database.adapter._adaptiveCollection('TestObject'); + let explain = await collection._rawFind({ _id: object.id }, { explain: true }); expect(explain.queryPlanner.winningPlan.stage).toBe('IDHACK'); - explain = await collection._rawFind( - { _id: object.id }, - { hint: { _id: 1 }, explain: true } - ); + explain = await collection._rawFind({ _id: object.id }, { hint: { _id: 1 }, explain: true }); expect(explain.queryPlanner.winningPlan.stage).toBe('FETCH'); expect(explain.queryPlanner.winningPlan.inputStage.keyPattern).toEqual({ _id: 1, @@ -74,9 +58,7 @@ describe_only_db('mongo')('Parse.Query hint', () => { const object = new TestObject({ foo: 'bar' }); await object.save(); - const collection = await config.database.adapter._adaptiveCollection( - 'TestObject' - ); + const collection = await config.database.adapter._adaptiveCollection('TestObject'); let result = await collection.aggregate([{ $group: { _id: '$foo' } }], { explain: true, }); @@ -96,9 +78,7 @@ describe_only_db('mongo')('Parse.Query hint', () => { const object = new TestObject({ foo: 'bar' }); await object.save(); - const collection = await config.database.adapter._adaptiveCollection( - 'TestObject' - ); + const collection = await config.database.adapter._adaptiveCollection('TestObject'); let result = await collection.aggregate([{ $group: { _id: '$foo' } }], { explain: true, }); @@ -136,9 +116,7 @@ describe_only_db('mongo')('Parse.Query hint', () => { }); response = await request(options); explain = response.data.results; - expect( - explain.queryPlanner.winningPlan.inputStage.inputStage.indexName - ).toBe('_id_'); + expect(explain.queryPlanner.winningPlan.inputStage.inputStage.indexName).toBe('_id_'); }); it('query aggregate with hint (rest)', async () => { diff --git a/spec/ParseQuery.spec.js b/spec/ParseQuery.spec.js index 7dec9893..5b8581dc 100644 --- a/spec/ParseQuery.spec.js +++ b/spec/ParseQuery.spec.js @@ -232,7 +232,7 @@ describe('Parse.Query testing', () => { .then(function () { done(); }) - .catch((err) => { + .catch(err => { jfail(err); done(); }); @@ -334,14 +334,14 @@ describe('Parse.Query testing', () => { } ); }, - (e) => { + e => { jfail(e); done(); } ); }); - it('containedIn null array', (done) => { + it('containedIn null array', done => { const emails = ['contact@xyz.com', 'contact@zyx.com', null]; const user = new Parse.User(); user.setUsername(emails[0]); @@ -353,7 +353,7 @@ describe('Parse.Query testing', () => { query.containedIn('username', emails); return query.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { equal(results.length, 1); done(); }, done.fail); @@ -377,7 +377,7 @@ describe('Parse.Query testing', () => { equal(result.get('nested').foo[0], "single'quote"); }); - it('nested containedIn string', (done) => { + it('nested containedIn string', done => { const sender1 = { group: ['A', 'B'] }; const sender2 = { group: ['A', 'C'] }; const sender3 = { group: ['B', 'C'] }; @@ -390,13 +390,13 @@ describe('Parse.Query testing', () => { query.containedIn('sender.group', ['A']); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 2); done(); }, done.fail); }); - it('nested containedIn number', (done) => { + it('nested containedIn number', done => { const sender1 = { group: [1, 2] }; const sender2 = { group: [1, 3] }; const sender3 = { group: [2, 3] }; @@ -409,7 +409,7 @@ describe('Parse.Query testing', () => { query.containedIn('sender.group', [1]); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 2); done(); }, done.fail); @@ -437,7 +437,7 @@ describe('Parse.Query testing', () => { } ); }) - .catch((err) => { + .catch(err => { jfail(err); done(); }); @@ -459,7 +459,7 @@ describe('Parse.Query testing', () => { done(); }); }) - .catch((err) => { + .catch(err => { jfail(err); done(); }); @@ -501,12 +501,7 @@ describe('Parse.Query testing', () => { const objectsList = []; objectsList.push( new DateSet({ - dates: makeDates([ - '2013-02-01', - '2013-02-02', - '2013-02-03', - '2013-02-04', - ]), + dates: makeDates(['2013-02-01', '2013-02-02', '2013-02-03', '2013-02-04']), }) ); objectsList.push( @@ -517,10 +512,7 @@ describe('Parse.Query testing', () => { Parse.Object.saveAll(objectsList).then(function () { const query = new Parse.Query(DateSet); - query.containsAll( - 'dates', - makeDates(['2013-02-01', '2013-02-02', '2013-02-03']) - ); + query.containsAll('dates', makeDates(['2013-02-01', '2013-02-02', '2013-02-03'])); query.find().then( function (results) { equal(results.length, 1); @@ -569,7 +561,7 @@ describe('Parse.Query testing', () => { }); }); - it('containsAllStartingWith should match all strings that starts with string', (done) => { + it('containsAllStartingWith should match all strings that starts with string', done => { const object = new Parse.Object('Object'); object.set('strings', ['the', 'brown', 'lazy', 'fox', 'jumps']); const object2 = new Parse.Object('Object'); @@ -579,7 +571,7 @@ describe('Parse.Query testing', () => { const objectList = [object, object2, object3]; - Parse.Object.saveAll(objectList).then((results) => { + Parse.Object.saveAll(objectList).then(results => { equal(objectList.length, results.length); return request({ @@ -587,11 +579,7 @@ describe('Parse.Query testing', () => { qs: { where: JSON.stringify({ strings: { - $all: [ - { $regex: '^\\Qthe\\E' }, - { $regex: '^\\Qfox\\E' }, - { $regex: '^\\Qlazy\\E' }, - ], + $all: [{ $regex: '^\\Qthe\\E' }, { $regex: '^\\Qfox\\E' }, { $regex: '^\\Qlazy\\E' }], }, }), }, @@ -653,7 +641,7 @@ describe('Parse.Query testing', () => { }); }); - it('containsAllStartingWith values must be all of type starting with regex', (done) => { + it('containsAllStartingWith values must be all of type starting with regex', done => { const object = new Parse.Object('Object'); object.set('strings', ['the', 'brown', 'lazy', 'fox', 'jumps']); @@ -688,7 +676,7 @@ describe('Parse.Query testing', () => { }); }); - it('containsAllStartingWith empty array values should return empty results', (done) => { + it('containsAllStartingWith empty array values should return empty results', done => { const object = new Parse.Object('Object'); object.set('strings', ['the', 'brown', 'lazy', 'fox', 'jumps']); @@ -723,7 +711,7 @@ describe('Parse.Query testing', () => { ); }); - it('containsAllStartingWith single empty value returns empty results', (done) => { + it('containsAllStartingWith single empty value returns empty results', done => { const object = new Parse.Object('Object'); object.set('strings', ['the', 'brown', 'lazy', 'fox', 'jumps']); @@ -758,7 +746,7 @@ describe('Parse.Query testing', () => { ); }); - it('containsAllStartingWith single regex value should return corresponding matching results', (done) => { + it('containsAllStartingWith single regex value should return corresponding matching results', done => { const object = new Parse.Object('Object'); object.set('strings', ['the', 'brown', 'lazy', 'fox', 'jumps']); const object2 = new Parse.Object('Object'); @@ -769,7 +757,7 @@ describe('Parse.Query testing', () => { const objectList = [object, object2, object3]; Parse.Object.saveAll(objectList) - .then((results) => { + .then(results => { equal(objectList.length, results.length); return request({ @@ -798,7 +786,7 @@ describe('Parse.Query testing', () => { ); }); - it('containsAllStartingWith single invalid regex returns empty results', (done) => { + it('containsAllStartingWith single invalid regex returns empty results', done => { const object = new Parse.Object('Object'); object.set('strings', ['the', 'brown', 'lazy', 'fox', 'jumps']); @@ -832,8 +820,8 @@ describe('Parse.Query testing', () => { ); }); - it('containedBy pointer array', (done) => { - const objects = Array.from(Array(10).keys()).map((idx) => { + it('containedBy pointer array', done => { + const objects = Array.from(Array(10).keys()).map(idx => { const obj = new Parse.Object('Object'); obj.set('key', idx); return obj; @@ -859,7 +847,7 @@ describe('Parse.Query testing', () => { }) .then(() => { // [1, 2, 3, 4, 5, 6, 7, 8, 9] - const pointers = objects.map((object) => object.toPointer()); + const pointers = objects.map(object => object.toPointer()); // Return all Parent where all parent.objects are contained in objects return request({ @@ -878,7 +866,7 @@ describe('Parse.Query testing', () => { }, }); }) - .then((response) => { + .then(response => { const results = response.data; expect(results.results[0].objectId).not.toBeUndefined(); expect(results.results[0].objectId).toBe(parent3.id); @@ -887,7 +875,7 @@ describe('Parse.Query testing', () => { }); }); - it('containedBy number array', (done) => { + it('containedBy number array', done => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ @@ -900,14 +888,9 @@ describe('Parse.Query testing', () => { const obj3 = new TestObject({ numbers: [1, 2, 3, 4] }); Parse.Object.saveAll([obj1, obj2, obj3]) .then(() => { - return request( - Object.assign( - { url: Parse.serverURL + '/classes/TestObject' }, - options - ) - ); + return request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)); }) - .then((response) => { + .then(response => { const results = response.data; expect(results.results[0].objectId).not.toBeUndefined(); expect(results.results[0].objectId).toBe(obj3.id); @@ -916,7 +899,7 @@ describe('Parse.Query testing', () => { }); }); - it('containedBy empty array', (done) => { + it('containedBy empty array', done => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ numbers: { $containedBy: [] } }), @@ -927,21 +910,16 @@ describe('Parse.Query testing', () => { const obj3 = new TestObject({ numbers: [1, 2, 3, 4] }); Parse.Object.saveAll([obj1, obj2, obj3]) .then(() => { - return request( - Object.assign( - { url: Parse.serverURL + '/classes/TestObject' }, - options - ) - ); + return request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)); }) - .then((response) => { + .then(response => { const results = response.data; expect(results.results.length).toBe(0); done(); }); }); - it('containedBy invalid query', (done) => { + it('containedBy invalid query', done => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ objects: { $containedBy: 1234 } }), @@ -951,15 +929,10 @@ describe('Parse.Query testing', () => { obj .save() .then(() => { - return request( - Object.assign( - { url: Parse.serverURL + '/classes/TestObject' }, - options - ) - ); + return request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)); }) .then(done.fail) - .catch((response) => { + .catch(response => { equal(response.data.code, Parse.Error.INVALID_JSON); equal(response.data.error, 'bad $containedBy: should be an array'); done(); @@ -974,9 +947,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.equalTo('number', 3); query.find().then(function (results) { @@ -990,9 +961,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.equalTo('number', undefined); query.find().then(function (results) { @@ -1006,9 +975,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.lessThan('number', 7); query.find().then(function (results) { @@ -1022,9 +989,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.lessThanOrEqualTo('number', 7); query.find().then(function (results) { @@ -1034,8 +999,8 @@ describe('Parse.Query testing', () => { }); }); - it('lessThan zero queries', (done) => { - const makeBoxedNumber = (i) => { + it('lessThan zero queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1046,14 +1011,14 @@ describe('Parse.Query testing', () => { query.lessThan('number', 0); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 3); done(); }); }); - it('lessThanOrEqualTo zero queries', (done) => { - const makeBoxedNumber = (i) => { + it('lessThanOrEqualTo zero queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1064,7 +1029,7 @@ describe('Parse.Query testing', () => { query.lessThanOrEqualTo('number', 0); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 4); done(); }); @@ -1074,9 +1039,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.greaterThan('number', 7); query.find().then(function (results) { @@ -1090,9 +1053,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.greaterThanOrEqualTo('number', 7); query.find().then(function (results) { @@ -1102,8 +1063,8 @@ describe('Parse.Query testing', () => { }); }); - it('greaterThan zero queries', (done) => { - const makeBoxedNumber = (i) => { + it('greaterThan zero queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1114,14 +1075,14 @@ describe('Parse.Query testing', () => { query.greaterThan('number', 0); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 1); done(); }); }); - it('greaterThanOrEqualTo zero queries', (done) => { - const makeBoxedNumber = (i) => { + it('greaterThanOrEqualTo zero queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1132,7 +1093,7 @@ describe('Parse.Query testing', () => { query.greaterThanOrEqualTo('number', 0); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 2); done(); }); @@ -1142,9 +1103,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.lessThanOrEqualTo('number', 7); query.greaterThanOrEqualTo('number', 7); @@ -1159,9 +1118,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.lessThan('number', 9); query.greaterThan('number', 3); @@ -1176,9 +1133,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.notEqualTo('number', 5); query.find().then(function (results) { @@ -1188,8 +1143,8 @@ describe('Parse.Query testing', () => { }); }); - it('notEqualTo zero queries', (done) => { - const makeBoxedNumber = (i) => { + it('notEqualTo zero queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1200,14 +1155,14 @@ describe('Parse.Query testing', () => { query.notEqualTo('number', 0); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 4); done(); }); }); - it('equalTo zero queries', (done) => { - const makeBoxedNumber = (i) => { + it('equalTo zero queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1218,14 +1173,14 @@ describe('Parse.Query testing', () => { query.equalTo('number', 0); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 1); done(); }); }); - it('number equalTo boolean queries', (done) => { - const makeBoxedNumber = (i) => { + it('number equalTo boolean queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1236,13 +1191,13 @@ describe('Parse.Query testing', () => { query.equalTo('number', false); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 0); done(); }); }); - it('equalTo false queries', (done) => { + it('equalTo false queries', done => { const obj1 = new TestObject({ field: false }); const obj2 = new TestObject({ field: true }); Parse.Object.saveAll([obj1, obj2]) @@ -1251,13 +1206,13 @@ describe('Parse.Query testing', () => { query.equalTo('field', false); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 1); done(); }); }); - it('where $eq false queries (rest)', (done) => { + it('where $eq false queries (rest)', done => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ field: { $eq: false } }), @@ -1266,16 +1221,16 @@ describe('Parse.Query testing', () => { const obj1 = new TestObject({ field: false }); const obj2 = new TestObject({ field: true }); Parse.Object.saveAll([obj1, obj2]).then(() => { - request( - Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options) - ).then((resp) => { - equal(resp.data.results.length, 1); - done(); - }); + request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)).then( + resp => { + equal(resp.data.results.length, 1); + done(); + } + ); }); }); - it('where $eq null queries (rest)', (done) => { + it('where $eq null queries (rest)', done => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ field: { $eq: null } }), @@ -1284,12 +1239,12 @@ describe('Parse.Query testing', () => { const obj1 = new TestObject({ field: false }); const obj2 = new TestObject({ field: null }); Parse.Object.saveAll([obj1, obj2]).then(() => { - return request( - Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options) - ).then((resp) => { - equal(resp.data.results.length, 1); - done(); - }); + return request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)).then( + resp => { + equal(resp.data.results.length, 1); + done(); + } + ); }); }); @@ -1297,9 +1252,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.containedIn('number', [3, 5, 7, 9, 11]); query.find().then(function (results) { @@ -1309,8 +1262,8 @@ describe('Parse.Query testing', () => { }); }); - it('containedIn false queries', (done) => { - const makeBoxedNumber = (i) => { + it('containedIn false queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1322,15 +1275,15 @@ describe('Parse.Query testing', () => { return query.find(); }) .then(done.fail) - .catch((error) => { + .catch(error => { equal(error.code, Parse.Error.INVALID_JSON); equal(error.message, 'bad $in value'); done(); }); }); - it('notContainedIn false queries', (done) => { - const makeBoxedNumber = (i) => { + it('notContainedIn false queries', done => { + const makeBoxedNumber = i => { return new BoxedNumber({ number: i }); }; const numbers = [-3, -2, -1, 0, 1]; @@ -1342,7 +1295,7 @@ describe('Parse.Query testing', () => { return query.find(); }) .then(done.fail) - .catch((error) => { + .catch(error => { equal(error.code, Parse.Error.INVALID_JSON); equal(error.message, 'bad $nin value'); done(); @@ -1353,9 +1306,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.notContainedIn('number', [3, 5, 7, 9, 11]); query.find().then(function (results) { @@ -1369,16 +1320,9 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function (list) { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function (list) { const query = new Parse.Query(BoxedNumber); - query.containedIn('objectId', [ - list[2].id, - list[3].id, - list[0].id, - 'NONSENSE', - ]); + query.containedIn('objectId', [list[2].id, list[3].id, list[0].id, 'NONSENSE']); query.ascending('number'); query.find().then(function (results) { if (results.length != 3) { @@ -1397,9 +1341,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function (list) { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function (list) { const query = new Parse.Query(BoxedNumber); query.equalTo('objectId', list[4].id); query.find().then(function (results) { @@ -1418,9 +1360,7 @@ describe('Parse.Query testing', () => { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.equalTo('number', 17); query.find().then(function (results) { @@ -1436,14 +1376,12 @@ describe('Parse.Query testing', () => { query .find() .then(done.fail) - .catch((error) => expect(error.code).toBe(Parse.Error.INVALID_KEY_NAME)) + .catch(error => expect(error.code).toBe(Parse.Error.INVALID_KEY_NAME)) .then(done); }); it('get', function (done) { - Parse.Object.saveAll([new TestObject({ foo: 'bar' })]).then(function ( - items - ) { + Parse.Object.saveAll([new TestObject({ foo: 'bar' })]).then(function (items) { ok(items[0]); const objectId = items[0].id; const query = new Parse.Query(TestObject); @@ -1459,9 +1397,7 @@ describe('Parse.Query testing', () => { }); it('get undefined', function (done) { - Parse.Object.saveAll([new TestObject({ foo: 'bar' })]).then(function ( - items - ) { + Parse.Object.saveAll([new TestObject({ foo: 'bar' })]).then(function (items) { ok(items[0]); const query = new Parse.Query(TestObject); query.get(undefined).then(fail, () => done()); @@ -1469,9 +1405,7 @@ describe('Parse.Query testing', () => { }); it('get error', function (done) { - Parse.Object.saveAll([new TestObject({ foo: 'bar' })]).then(function ( - items - ) { + Parse.Object.saveAll([new TestObject({ foo: 'bar' })]).then(function (items) { ok(items[0]); const query = new Parse.Query(TestObject); query.get('InvalidObjectID').then( @@ -1510,17 +1444,16 @@ describe('Parse.Query testing', () => { }); it('first with two results', function (done) { - Parse.Object.saveAll([ - new TestObject({ foo: 'bar' }), - new TestObject({ foo: 'bar' }), - ]).then(function () { - const query = new Parse.Query(TestObject); - query.equalTo('foo', 'bar'); - query.first().then(function (result) { - equal(result.get('foo'), 'bar'); - done(); - }); - }); + Parse.Object.saveAll([new TestObject({ foo: 'bar' }), new TestObject({ foo: 'bar' })]).then( + function () { + const query = new Parse.Query(TestObject); + query.equalTo('foo', 'bar'); + query.first().then(function (result) { + equal(result.get('foo'), 'bar'); + done(); + }); + } + ); }); it('first with error', function (done) { @@ -1529,7 +1462,7 @@ describe('Parse.Query testing', () => { query .first() .then(done.fail) - .catch((e) => expect(e.code).toBe(Parse.Error.INVALID_KEY_NAME)) + .catch(e => expect(e.code).toBe(Parse.Error.INVALID_KEY_NAME)) .then(done); }); @@ -1542,62 +1475,54 @@ describe('Parse.Query testing', () => { const item2 = new TestObject(); const container1 = new Container({ item: item1 }); const container2 = new Container({ item: item2 }); - Parse.Object.saveAll([item1, item2, container1, container2]).then( - function () { - const query = new Parse.Query(Container); - query.notEqualTo('item', item1); - query.find().then(function (results) { - equal(results.length, 1); - done(); - }); - } - ); + Parse.Object.saveAll([item1, item2, container1, container2]).then(function () { + const query = new Parse.Query(Container); + query.notEqualTo('item', item1); + query.find().then(function (results) { + equal(results.length, 1); + done(); + }); + }); }); it('skip', function (done) { - Parse.Object.saveAll([new TestObject(), new TestObject()]).then( - function () { - const query = new Parse.Query(TestObject); - query.skip(1); + Parse.Object.saveAll([new TestObject(), new TestObject()]).then(function () { + const query = new Parse.Query(TestObject); + query.skip(1); + query.find().then(function (results) { + equal(results.length, 1); + query.skip(3); query.find().then(function (results) { - equal(results.length, 1); - query.skip(3); - query.find().then(function (results) { - equal(results.length, 0); - done(); - }); + equal(results.length, 0); + done(); }); - } - ); + }); + }); }); it("skip doesn't affect count", function (done) { - Parse.Object.saveAll([new TestObject(), new TestObject()]).then( - function () { - const query = new Parse.Query(TestObject); + Parse.Object.saveAll([new TestObject(), new TestObject()]).then(function () { + const query = new Parse.Query(TestObject); + query.count().then(function (count) { + equal(count, 2); + query.skip(1); query.count().then(function (count) { equal(count, 2); - query.skip(1); + query.skip(3); query.count().then(function (count) { equal(count, 2); - query.skip(3); - query.count().then(function (count) { - equal(count, 2); - done(); - }); + done(); }); }); - } - ); + }); + }); }); it('count', function (done) { const makeBoxedNumber = function (i) { return new BoxedNumber({ number: i }); }; - Parse.Object.saveAll( - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber) - ).then(function () { + Parse.Object.saveAll([0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(makeBoxedNumber)).then(function () { const query = new Parse.Query(BoxedNumber); query.greaterThan('number', 1); query.count().then(function (count) { @@ -1648,16 +1573,14 @@ describe('Parse.Query testing', () => { { sortField: { value: 'M' } }, ]; - const objects = testSet.map((e) => new Parse.Object('Test', e)); + const objects = testSet.map(e => new Parse.Object('Test', e)); Parse.Object.saveAll(objects) - .then(() => - new Parse.Query('Test').addDescending('sortField.value').first() - ) - .then((result) => { + .then(() => new Parse.Query('Test').addDescending('sortField.value').first()) + .then(result => { expect(result.get('sortField').value).toBe('Z'); return new Parse.Query('Test').addAscending('sortField.value').first(); }) - .then((result) => { + .then(result => { expect(result.get('sortField').value).toBe('A'); done(); }) @@ -1671,18 +1594,14 @@ describe('Parse.Query testing', () => { { sortField: { value: { field: 'M' } } }, ]; - const objects = testSet.map((e) => new Parse.Object('Test', e)); + const objects = testSet.map(e => new Parse.Object('Test', e)); Parse.Object.saveAll(objects) - .then(() => - new Parse.Query('Test').addDescending('sortField.value.field').first() - ) - .then((result) => { + .then(() => new Parse.Query('Test').addDescending('sortField.value.field').first()) + .then(result => { expect(result.get('sortField').value.field).toBe('Z'); - return new Parse.Query('Test') - .addAscending('sortField.value.field') - .first(); + return new Parse.Query('Test').addAscending('sortField.value.field').first(); }) - .then((result) => { + .then(result => { expect(result.get('sortField').value.field).toBe('A'); done(); }) @@ -1696,16 +1615,14 @@ describe('Parse.Query testing', () => { { sortField: { value: 5 } }, ]; - const objects = testSet.map((e) => new Parse.Object('Test', e)); + const objects = testSet.map(e => new Parse.Object('Test', e)); Parse.Object.saveAll(objects) - .then(() => - new Parse.Query('Test').addDescending('sortField.value').first() - ) - .then((result) => { + .then(() => new Parse.Query('Test').addDescending('sortField.value').first()) + .then(result => { expect(result.get('sortField').value).toBe(10); return new Parse.Query('Test').addAscending('sortField.value').first(); }) - .then((result) => { + .then(result => { expect(result.get('sortField').value).toBe(1); done(); }) @@ -1719,18 +1636,14 @@ describe('Parse.Query testing', () => { { sortField: { value: { field: 5 } } }, ]; - const objects = testSet.map((e) => new Parse.Object('Test', e)); + const objects = testSet.map(e => new Parse.Object('Test', e)); Parse.Object.saveAll(objects) - .then(() => - new Parse.Query('Test').addDescending('sortField.value.field').first() - ) - .then((result) => { + .then(() => new Parse.Query('Test').addDescending('sortField.value.field').first()) + .then(result => { expect(result.get('sortField').value.field).toBe(10); - return new Parse.Query('Test') - .addAscending('sortField.value.field') - .first(); + return new Parse.Query('Test').addAscending('sortField.value.field').first(); }) - .then((result) => { + .then(result => { expect(result.get('sortField').value.field).toBe(1); done(); }) @@ -1774,7 +1687,7 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { equal(results.length, 4); equal(results[0].get('number'), 3); equal(results[0].get('string'), 'a'); @@ -1786,7 +1699,7 @@ describe('Parse.Query testing', () => { equal(results[3].get('string'), 'b'); done(); }, - (err) => { + err => { jfail(err); done(); } @@ -1838,7 +1751,7 @@ describe('Parse.Query testing', () => { done(); }); }, - (err) => { + err => { jfail(err); done(); } @@ -1901,7 +1814,7 @@ describe('Parse.Query testing', () => { query .find() .then(done.fail) - .catch((e) => expect(e.code).toBe(Parse.Error.INVALID_KEY_NAME)) + .catch(e => expect(e.code).toBe(Parse.Error.INVALID_KEY_NAME)) .then(done); }); }); @@ -2029,15 +1942,15 @@ describe('Parse.Query testing', () => { const start = new Date(); let one, two, three; return makeTimeObject(start, 1) - .then((o1) => { + .then(o1 => { one = o1; return makeTimeObject(start, 2); }) - .then((o2) => { + .then(o2 => { two = o2; return makeTimeObject(start, 3); }) - .then((o3) => { + .then(o3 => { three = o3; return [one, two, three]; }); @@ -2124,7 +2037,7 @@ describe('Parse.Query testing', () => { query .find() .then(done.fail) - .catch((e) => expect(e.code).toBe(Parse.Error.INVALID_QUERY)) + .catch(e => expect(e.code).toBe(Parse.Error.INVALID_QUERY)) .then(done); }); @@ -2186,7 +2099,7 @@ describe('Parse.Query testing', () => { }); }); - it('nested contains', (done) => { + it('nested contains', done => { const sender1 = { group: ['A', 'B'] }; const sender2 = { group: ['A', 'C'] }; const sender3 = { group: ['B', 'C'] }; @@ -2199,7 +2112,7 @@ describe('Parse.Query testing', () => { query.contains('sender.group', 'A'); return query.find(); }) - .then((results) => { + .then(results => { equal(results.length, 2); done(); }, done.fail); @@ -2462,7 +2375,7 @@ describe('Parse.Query testing', () => { }); }); - it('properly includes array', (done) => { + it('properly includes array', done => { const objects = []; let total = 0; while (objects.length != 5) { @@ -2483,12 +2396,12 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toBe(1); const res = results[0]; const objects = res.get('objects'); expect(objects.length).toBe(5); - objects.forEach((object) => { + objects.forEach(object => { total -= object.get('key'); }); expect(total).toBe(0); @@ -2501,7 +2414,7 @@ describe('Parse.Query testing', () => { ); }); - it('properly includes array of mixed objects', (done) => { + it('properly includes array of mixed objects', done => { const objects = []; let total = 0; while (objects.length != 5) { @@ -2528,18 +2441,18 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toBe(1); const res = results[0]; const objects = res.get('objects'); expect(objects.length).toBe(10); - objects.forEach((object) => { + objects.forEach(object => { total -= object.get('key'); }); expect(total).toBe(0); done(); }, - (e) => { + e => { fail('should not fail'); fail(JSON.stringify(e)); done(); @@ -2547,7 +2460,7 @@ 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 => { const objects = []; let total = 0; while (objects.length != 5) { @@ -2579,18 +2492,18 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toBe(1); const res = results[0]; const objects = res.get('objects'); expect(objects.length).toBe(5); - objects.forEach((object) => { + objects.forEach(object => { total -= object.get('key'); }); expect(total).toBe(0); done(); }, - (err) => { + err => { jfail(err); fail('should not fail'); done(); @@ -2598,7 +2511,7 @@ describe('Parse.Query testing', () => { ); }); - it('properly fetches nested pointers', (done) => { + it('properly fetches nested pointers', done => { const color = new Parse.Object('Color'); color.set('hex', '#133733'); const circle = new Parse.Object('Circle'); @@ -2619,13 +2532,11 @@ describe('Parse.Query testing', () => { return q.find(); }) .then( - (results) => { + results => { expect(results.length).toBe(1); const figure = results[0]; 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(); }, () => { @@ -2728,7 +2639,7 @@ describe('Parse.Query testing', () => { }); }); - it('$select inside $or', (done) => { + it('$select inside $or', done => { const Restaurant = Parse.Object.extend('Restaurant'); const Person = Parse.Object.extend('Person'); const objects = [ @@ -2751,19 +2662,19 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toEqual(2); done(); }, - (error) => { + error => { jfail(error); done(); } ); }); - it('$nor valid query', (done) => { - const objects = Array.from(Array(10).keys()).map((rating) => { + it('$nor valid query', done => { + const objects = Array.from(Array(10).keys()).map(rating => { return new TestObject({ rating: rating }); }); @@ -2772,36 +2683,26 @@ describe('Parse.Query testing', () => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ - $nor: [ - { rating: { $gt: highValue } }, - { rating: { $lte: lowValue } }, - ], + $nor: [{ rating: { $gt: highValue } }, { rating: { $lte: lowValue } }], }), }, }); Parse.Object.saveAll(objects) .then(() => { - return request( - Object.assign( - { url: Parse.serverURL + '/classes/TestObject' }, - options - ) - ); + return request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)); }) - .then((response) => { + .then(response => { const results = response.data; expect(results.results.length).toBe(highValue - lowValue); - expect( - results.results.every( - (res) => res.rating > lowValue && res.rating <= highValue - ) - ).toBe(true); + expect(results.results.every(res => res.rating > lowValue && res.rating <= highValue)).toBe( + true + ); done(); }); }); - it('$nor invalid query - empty array', (done) => { + it('$nor invalid query - empty array', done => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ $nor: [] }), @@ -2811,21 +2712,16 @@ describe('Parse.Query testing', () => { obj .save() .then(() => { - return request( - Object.assign( - { url: Parse.serverURL + '/classes/TestObject' }, - options - ) - ); + return request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)); }) .then(done.fail) - .catch((response) => { + .catch(response => { equal(response.data.code, Parse.Error.INVALID_QUERY); done(); }); }); - it('$nor invalid query - wrong type', (done) => { + it('$nor invalid query - wrong type', done => { const options = Object.assign({}, masterKeyOptions, { qs: { where: JSON.stringify({ $nor: 1337 }), @@ -2835,15 +2731,10 @@ describe('Parse.Query testing', () => { obj .save() .then(() => { - return request( - Object.assign( - { url: Parse.serverURL + '/classes/TestObject' }, - options - ) - ); + return request(Object.assign({ url: Parse.serverURL + '/classes/TestObject' }, options)); }) .then(done.fail) - .catch((response) => { + .catch(response => { equal(response.data.code, Parse.Error.INVALID_QUERY); done(); }); @@ -2888,7 +2779,7 @@ describe('Parse.Query testing', () => { const query = new Parse.Query(RestaurantObject); const mainQuery = new Parse.Query(PersonObject); mainQuery.doesNotMatchKeyInQuery('hometown', 'location', query); - mainQuery.find().then((results) => { + mainQuery.find().then(results => { equal(results.length, 1); equal(results[0].get('name'), 'Tom'); done(); @@ -2906,11 +2797,11 @@ describe('Parse.Query testing', () => { return new AuthorObject({ name: 'Julius' }) .save() - .then((user) => { + .then(user => { postAuthor = user; return new AuthorObject({ name: 'Bob' }).save(); }) - .then((user) => { + .then(user => { requestUser = user; const objects = [ new PostObject({ author: postAuthor, title: 'Lorem ipsum' }), @@ -2931,7 +2822,7 @@ describe('Parse.Query testing', () => { .equalTo('author', postAuthor) .doesNotMatchKeyInQuery('author', 'blockedBy', banListQuery) .find() - .then((r) => { + .then(r => { expect(r.length).toEqual(0); done(); }, done.fail); @@ -2960,11 +2851,7 @@ describe('Parse.Query testing', () => { const subQuery2 = new Parse.Query(PersonObject); subQuery2.matchesKeyInQuery('hometown', 'location', query2); const mainQuery = new Parse.Query(PersonObject); - mainQuery.doesNotMatchKeyInQuery( - 'objectId', - 'objectId', - Parse.Query.or(subQuery, subQuery2) - ); + mainQuery.doesNotMatchKeyInQuery('objectId', 'objectId', Parse.Query.or(subQuery, subQuery2)); mainQuery.find().then(function (results) { equal(results.length, 1); equal(results[0].get('name'), 'Bob'); @@ -3160,7 +3047,7 @@ describe('Parse.Query testing', () => { query.lessThan('x', COUNT); return query.each( function (obj) { - return new Promise((resolve) => { + return new Promise(resolve => { process.nextTick(function () { seen[obj.get('x')] = (seen[obj.get('x')] || 0) + 1; resolve(); @@ -3296,11 +3183,7 @@ describe('Parse.Query testing', () => { ok(result.updatedAt, 'expected object updatedAt to be set'); ok(!result.dirty(), 'expected result not to be dirty'); strictEqual(result.get('foo'), 'baz'); - strictEqual( - result.get('bar'), - undefined, - "expected 'bar' field to be unset" - ); + strictEqual(result.get('bar'), undefined, "expected 'bar' field to be unset"); return result.fetch(); }) .then(function (result) { @@ -3316,16 +3199,8 @@ describe('Parse.Query testing', () => { .then(function (result) { ok(result.id, 'expected object id to be set'); ok(!result.dirty(), 'expected result not to be dirty'); - strictEqual( - result.get('foo'), - undefined, - "expected 'foo' field to be unset" - ); - strictEqual( - result.get('bar'), - undefined, - "expected 'bar' field to be unset" - ); + strictEqual(result.get('foo'), undefined, "expected 'foo' field to be unset"); + strictEqual(result.get('bar'), undefined, "expected 'bar' field to be unset"); }) .then(function () { obj._clearServerData(); @@ -3492,11 +3367,7 @@ describe('Parse.Query testing', () => { ok(result.updatedAt, 'expected object updatedAt to be set'); ok(!result.dirty(), 'expected result not to be dirty'); strictEqual(result.get('foo'), 'baz'); - strictEqual( - result.get('bar'), - undefined, - 'expected "bar" field to be unset' - ); + strictEqual(result.get('bar'), undefined, 'expected "bar" field to be unset'); }) .then( function () { @@ -3510,12 +3381,12 @@ describe('Parse.Query testing', () => { }); }); - it('notEqual with array of pointers', (done) => { + it('notEqual with array of pointers', done => { const children = []; const parents = []; const promises = []; for (let i = 0; i < 2; i++) { - const proc = (iter) => { + const proc = iter => { const child = new Parse.Object('Child'); children.push(child); const parent = new Parse.Object('Parent'); @@ -3535,18 +3406,18 @@ describe('Parse.Query testing', () => { query.notEqualTo('child', children[0]); return query.find(); }) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); expect(results[0].id).toEqual(parents[1].id); done(); }) - .catch((error) => { + .catch(error => { console.log(error); }); }); // PG don't support creating a null column - it_exclude_dbs(['postgres'])('querying for null value', (done) => { + it_exclude_dbs(['postgres'])('querying for null value', done => { const obj = new Parse.Object('TestObject'); obj.set('aNull', null); obj @@ -3556,17 +3427,17 @@ describe('Parse.Query testing', () => { query.equalTo('aNull', null); return query.find(); }) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); expect(results[0].get('aNull')).toEqual(null); done(); }); }); - it('query within dictionary', (done) => { + it('query within dictionary', done => { const promises = []; for (let i = 0; i < 2; i++) { - const proc = (iter) => { + const proc = iter => { const obj = new Parse.Object('TestObject'); obj.set('aDict', { x: iter + 1, y: iter + 2 }); promises.push(obj.save()); @@ -3580,11 +3451,11 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toEqual(1); done(); }, - (error) => { + error => { console.log(error); } ); @@ -3610,7 +3481,7 @@ describe('Parse.Query testing', () => { return q.find(); }) .then( - (objs) => { + objs => { expect(objs.length).toBe(1); expect(objs[0].get('child').get('hello')).toEqual('world'); expect(objs[0].createdAt instanceof Date).toBe(true); @@ -3623,7 +3494,7 @@ describe('Parse.Query testing', () => { ); }); - it('query match on array with single object', (done) => { + it('query match on array with single object', done => { const target = { __type: 'Pointer', className: 'TestObject', @@ -3639,17 +3510,17 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toEqual(1); done(); }, - (error) => { + error => { console.log(error); } ); }); - it('query match on array with multiple objects', (done) => { + it('query match on array with multiple objects', done => { const target1 = { __type: 'Pointer', className: 'TestObject', @@ -3670,17 +3541,17 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toEqual(1); done(); }, - (error) => { + error => { console.log(error); } ); }); - it('query should not match on array when searching for null', (done) => { + it('query should not match on array when searching for null', done => { const target = { __type: 'Pointer', className: 'TestObject', @@ -3698,18 +3569,18 @@ describe('Parse.Query testing', () => { return query.find(); }) .then( - (results) => { + results => { expect(results.length).toEqual(0); done(); }, - (error) => { + error => { console.log(error); } ); }); // #371 - it('should properly interpret a query v1', (done) => { + it('should properly interpret a query v1', done => { const query = new Parse.Query('C1'); const auxQuery = new Parse.Query('C1'); query.matchesKeyInQuery('A1', 'A2', auxQuery); @@ -3719,7 +3590,7 @@ describe('Parse.Query testing', () => { () => { done(); }, - (err) => { + err => { jfail(err); fail('should not failt'); done(); @@ -3727,44 +3598,29 @@ describe('Parse.Query testing', () => { ); }); - it('should properly interpret a query v2', (done) => { + it('should properly interpret a query v2', done => { const user = new Parse.User(); user.set('username', 'foo'); user.set('password', 'bar'); return user .save() - .then((user) => { - const objIdQuery = new Parse.Query('_User').equalTo( - 'objectId', - user.id - ); + .then(user => { + const objIdQuery = new Parse.Query('_User').equalTo('objectId', user.id); const blockedUserQuery = user.relation('blockedUsers').query(); - const aResponseQuery = new Parse.Query( - 'MatchRelationshipActivityResponse' - ); + const aResponseQuery = new Parse.Query('MatchRelationshipActivityResponse'); aResponseQuery.equalTo('userA', user); aResponseQuery.equalTo('userAResponse', 1); - const bResponseQuery = new Parse.Query( - 'MatchRelationshipActivityResponse' - ); + const bResponseQuery = new Parse.Query('MatchRelationshipActivityResponse'); bResponseQuery.equalTo('userB', user); bResponseQuery.equalTo('userBResponse', 1); const matchOr = Parse.Query.or(aResponseQuery, bResponseQuery); const matchRelationshipA = new Parse.Query('_User'); - matchRelationshipA.matchesKeyInQuery( - 'objectId', - 'userAObjectId', - matchOr - ); + matchRelationshipA.matchesKeyInQuery('objectId', 'userAObjectId', matchOr); const matchRelationshipB = new Parse.Query('_User'); - matchRelationshipB.matchesKeyInQuery( - 'objectId', - 'userBObjectId', - matchOr - ); + matchRelationshipB.matchesKeyInQuery('objectId', 'userBObjectId', matchOr); const orQuery = Parse.Query.or( objIdQuery, @@ -3780,7 +3636,7 @@ describe('Parse.Query testing', () => { () => { done(); }, - (err) => { + err => { jfail(err); fail('should not fail'); done(); @@ -3795,7 +3651,7 @@ describe('Parse.Query testing', () => { return new AuthorObject() .save() - .then((user) => { + .then(user => { const post = new PostObject({ author: user, }); @@ -3806,12 +3662,12 @@ describe('Parse.Query testing', () => { return Promise.all([post.save(), group.save()]); }) - .then((results) => { + .then(results => { const p = results[0]; return new Parse.Query(PostObject) .matchesKeyInQuery('author', 'members', new Parse.Query(GroupObject)) .find() - .then((r) => { + .then(r => { expect(r.length).toEqual(1); if (r.length > 0) { expect(r[0].id).toEqual(p.id); @@ -3821,7 +3677,7 @@ describe('Parse.Query testing', () => { }); }); - it('should find objects with array of pointers', (done) => { + it('should find objects with array of pointers', done => { const objects = []; while (objects.length != 5) { const object = new Parse.Object('ContainedObject'); @@ -3830,9 +3686,9 @@ describe('Parse.Query testing', () => { } Parse.Object.saveAll(objects) - .then((objects) => { + .then(objects => { const container = new Parse.Object('Container'); - const pointers = objects.map((obj) => { + const pointers = objects.map(obj => { return { __type: 'Pointer', className: 'ContainedObject', @@ -3851,37 +3707,37 @@ describe('Parse.Query testing', () => { query.matchesQuery('objects', inQuery); return query.find(); }) - .then((results) => { + .then(results => { if (results) { expect(results.length).toBe(2); } done(); }) - .catch((err) => { + .catch(err => { jfail(err); fail('should not fail'); done(); }); }); - it('query with two OR subqueries (regression test #1259)', (done) => { + it('query with two OR subqueries (regression test #1259)', done => { const relatedObject = new Parse.Object('Class2'); relatedObject .save() - .then((relatedObject) => { + .then(relatedObject => { const anObject = new Parse.Object('Class1'); const relation = anObject.relation('relation'); relation.add(relatedObject); return anObject.save(); }) - .then((anObject) => { + .then(anObject => { const q1 = anObject.relation('relation').query(); q1.doesNotExist('nonExistantKey1'); const q2 = anObject.relation('relation').query(); q2.doesNotExist('nonExistantKey2'); Parse.Query.or(q1, q2) .find() - .then((results) => { + .then(results => { expect(results.length).toEqual(1); if (results.length == 1) { expect(results[0].objectId).toEqual(q1.objectId); @@ -3891,11 +3747,11 @@ describe('Parse.Query testing', () => { }); }); - it('objectId containedIn with multiple large array', (done) => { + it('objectId containedIn with multiple large array', done => { const obj = new Parse.Object('MyClass'); obj .save() - .then((obj) => { + .then(obj => { const longListOfStrings = []; for (let i = 0; i < 130; i++) { longListOfStrings.push(i.toString()); @@ -3906,13 +3762,13 @@ describe('Parse.Query testing', () => { q.containedIn('objectId', longListOfStrings); return q.find(); }) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); done(); }); }); - it('containedIn with pointers should work with string array', (done) => { + it('containedIn with pointers should work with string array', done => { const obj = new Parse.Object('MyClass'); const child = new Parse.Object('Child'); child @@ -3933,14 +3789,14 @@ describe('Parse.Query testing', () => { query.containedIn('child', [child.id]); return query.find(); }) - .then((results) => { + .then(results => { expect(results.length).toBe(1); }) .then(done) .catch(done.fail); }); - it('containedIn with pointers should work with string array, with many objects', (done) => { + it('containedIn with pointers should work with string array, with many objects', done => { const objs = []; const children = []; for (let i = 0; i < 10; i++) { @@ -3960,13 +3816,13 @@ describe('Parse.Query testing', () => { }) .then(() => { const query = new Parse.Query('MyClass'); - const subset = children.slice(0, 5).map((child) => { + const subset = children.slice(0, 5).map(child => { return child.id; }); query.containedIn('child', subset); return query.find(); }) - .then((results) => { + .then(results => { expect(results.length).toBe(5); }) .then(done) @@ -4068,10 +3924,7 @@ describe('Parse.Query testing', () => { equal(foobarObj.get('barBaz').get('key'), 'value'); equal(foobarObj.get('barBaz').get('otherKey'), undefined); equal(foobarObj.get('barBaz').get('bazoo').get('some'), 'thing'); - equal( - foobarObj.get('barBaz').get('bazoo').get('otherSome'), - undefined - ); + equal(foobarObj.get('barBaz').get('bazoo').get('otherSome'), undefined); } else { fail('barBaz should be set'); } @@ -4128,7 +3981,7 @@ describe('Parse.Query testing', () => { equal(result.child3.name, 'mo'); }); - it('includeAll', (done) => { + it('includeAll', done => { const child1 = new TestObject({ foo: 'bar', name: 'ac' }); const child2 = new TestObject({ foo: 'baz', name: 'flo' }); const child3 = new TestObject({ foo: 'bad', name: 'mo' }); @@ -4141,14 +3994,9 @@ describe('Parse.Query testing', () => { includeAll: true, }, }); - return request( - Object.assign( - { url: Parse.serverURL + '/classes/Container' }, - options - ) - ); + return request(Object.assign({ url: Parse.serverURL + '/classes/Container' }, options)); }) - .then((resp) => { + .then(resp => { const result = resp.data.results[0]; equal(result.child1.foo, 'bar'); equal(result.child2.foo, 'baz'); @@ -4160,7 +4008,7 @@ describe('Parse.Query testing', () => { }); }); - it('select nested keys 2 level includeAll', (done) => { + it('select nested keys 2 level includeAll', done => { const Foobar = new Parse.Object('Foobar'); const BarBaz = new Parse.Object('Barbaz'); const Bazoo = new Parse.Object('Bazoo'); @@ -4186,7 +4034,7 @@ describe('Parse.Query testing', () => { Foobar.set('group', Tang); return Foobar.save(); }) - .then((savedFoobar) => { + .then(savedFoobar => { const options = Object.assign( { url: Parse.serverURL + '/classes/Foobar', @@ -4202,7 +4050,7 @@ describe('Parse.Query testing', () => { ); return request(options); }) - .then((resp) => { + .then(resp => { const result = resp.data.results[0]; equal(result.group.clan, 'wu'); equal(result.foo, undefined); @@ -4241,7 +4089,7 @@ describe('Parse.Query testing', () => { foobarQuery.select(['fizz', 'barBaz.key', 'barBaz.bazoo.some']); return foobarQuery.get(savedFoobar.id); }) - .then((foobarObj) => { + .then(foobarObj => { equal(foobarObj.get('fizz'), 'buzz'); equal(foobarObj.get('foo'), undefined); if (foobarObj.has('barBaz')) { @@ -4249,10 +4097,7 @@ describe('Parse.Query testing', () => { equal(foobarObj.get('barBaz').get('otherKey'), undefined); if (foobarObj.get('barBaz').has('bazoo')) { equal(foobarObj.get('barBaz').get('bazoo').get('some'), 'thing'); - equal( - foobarObj.get('barBaz').get('bazoo').get('otherSome'), - undefined - ); + equal(foobarObj.get('barBaz').get('bazoo').get('otherSome'), undefined); } else { fail('bazoo should be set'); } @@ -4281,11 +4126,11 @@ describe('Parse.Query testing', () => { const or01 = Parse.Query.or(q0, q1); return Parse.Query.or(or01, q2).find(); }) - .then((results) => { + .then(results => { expect(results.length).toBe(3); done(); }) - .catch((error) => { + .catch(error => { fail('should not fail'); jfail(error); done(); @@ -4323,16 +4168,16 @@ describe('Parse.Query testing', () => { }); }) .then( - (response) => { + response => { const results = response.data; expect(results.results.length).toBe(1); done(); }, - (res) => done.fail(res.data) + res => done.fail(res.data) ); }); - it('should not interfere with has when using select on field with undefined value #3999', (done) => { + it('should not interfere with has when using select on field with undefined value #3999', done => { const obj1 = new Parse.Object('TestObject'); const obj2 = new Parse.Object('OtherObject'); obj2.set('otherField', 1); @@ -4344,15 +4189,11 @@ describe('Parse.Query testing', () => { .then(() => { const query = new Parse.Query('TestObject'); query.include('testPointerField'); - query.select([ - 'testPointerField', - 'testPointerField.otherField', - 'shouldBe', - ]); + query.select(['testPointerField', 'testPointerField.otherField', 'shouldBe']); return query.find(); }) - .then((results) => { - results.forEach((result) => { + .then(results => { + results.forEach(result => { equal(result.has('testPointerField'), result.get('shouldBe')); }); done(); @@ -4360,9 +4201,7 @@ describe('Parse.Query testing', () => { .catch(done.fail); }); - it_only_db('mongo')('should handle relative times correctly', function ( - done - ) { + it_only_db('mongo')('should handle relative times correctly', function (done) { const now = Date.now(); const obj1 = new Parse.Object('MyCustomObject', { name: 'obj1', @@ -4379,7 +4218,7 @@ describe('Parse.Query testing', () => { q.greaterThan('ttl', { $relativeTime: 'in 1 day' }); return q.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { expect(results.length).toBe(1); }) .then(() => { @@ -4387,7 +4226,7 @@ describe('Parse.Query testing', () => { q.greaterThan('ttl', { $relativeTime: '1 day ago' }); return q.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { expect(results.length).toBe(1); }) .then(() => { @@ -4395,7 +4234,7 @@ describe('Parse.Query testing', () => { q.lessThan('ttl', { $relativeTime: '5 days ago' }); return q.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { expect(results.length).toBe(0); }) .then(() => { @@ -4403,7 +4242,7 @@ describe('Parse.Query testing', () => { q.greaterThan('ttl', { $relativeTime: '3 days ago' }); return q.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { expect(results.length).toBe(2); }) .then(() => { @@ -4411,7 +4250,7 @@ describe('Parse.Query testing', () => { q.greaterThan('ttl', { $relativeTime: 'now' }); return q.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { expect(results.length).toBe(1); }) .then(() => { @@ -4420,7 +4259,7 @@ describe('Parse.Query testing', () => { q.lessThan('ttl', { $relativeTime: 'in 1 day' }); return q.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { expect(results.length).toBe(0); }) .then(() => { @@ -4428,7 +4267,7 @@ describe('Parse.Query testing', () => { q.greaterThan('ttl', { $relativeTime: '1 year 3 weeks ago' }); return q.find({ useMasterKey: true }); }) - .then((results) => { + .then(results => { expect(results.length).toBe(2); }) .then(done, done.fail); @@ -4448,23 +4287,20 @@ describe('Parse.Query testing', () => { .then(done.fail, () => done()); }); - it_only_db('mongo')( - 'should error when using $relativeTime on non-Date field', - function (done) { - const obj1 = new Parse.Object('MyCustomObject', { - name: 'obj1', - nonDateField: 'abcd', - ttl: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days from now - }); + it_only_db('mongo')('should error when using $relativeTime on non-Date field', function (done) { + const obj1 = new Parse.Object('MyCustomObject', { + name: 'obj1', + nonDateField: 'abcd', + ttl: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days from now + }); - const q = new Parse.Query('MyCustomObject'); - q.greaterThan('nonDateField', { $relativeTime: '1 day ago' }); - obj1 - .save({ useMasterKey: true }) - .then(() => q.find({ useMasterKey: true })) - .then(done.fail, () => done()); - } - ); + const q = new Parse.Query('MyCustomObject'); + q.greaterThan('nonDateField', { $relativeTime: '1 day ago' }); + obj1 + .save({ useMasterKey: true }) + .then(() => q.find({ useMasterKey: true })) + .then(done.fail, () => done()); + }); it('should match complex structure with dot notation when using matchesKeyInQuery', function (done) { const group1 = new Parse.Object('Group', { @@ -4496,11 +4332,7 @@ describe('Parse.Query testing', () => { rolesOfTypeX.equalTo('type', 'x'); const groupsWithRoleX = new Parse.Query('Group'); - groupsWithRoleX.matchesKeyInQuery( - 'objectId', - 'belongsTo.objectId', - rolesOfTypeX - ); + groupsWithRoleX.matchesKeyInQuery('objectId', 'belongsTo.objectId', rolesOfTypeX); groupsWithRoleX.find().then(function (results) { equal(results.length, 1); @@ -4540,11 +4372,7 @@ describe('Parse.Query testing', () => { rolesOfTypeX.equalTo('type', 'x'); const groupsWithRoleX = new Parse.Query('Group'); - groupsWithRoleX.doesNotMatchKeyInQuery( - 'objectId', - 'belongsTo.objectId', - rolesOfTypeX - ); + groupsWithRoleX.doesNotMatchKeyInQuery('objectId', 'belongsTo.objectId', rolesOfTypeX); groupsWithRoleX.find().then(function (results) { equal(results.length, 1); @@ -4575,11 +4403,7 @@ describe('Parse.Query testing', () => { rolesOfTypeX.equalTo('type', 'x'); const groupsWithRoleX = new Parse.Query('Group'); - groupsWithRoleX.matchesKeyInQuery( - 'objectId', - 'belongsTo.objectId', - rolesOfTypeX - ); + groupsWithRoleX.matchesKeyInQuery('objectId', 'belongsTo.objectId', rolesOfTypeX); const results = await groupsWithRoleX.find(); equal(results.length, 1); @@ -4608,18 +4432,14 @@ describe('Parse.Query testing', () => { rolesOfTypeX.equalTo('type', 'x'); const groupsWithRoleX = new Parse.Query('Group'); - groupsWithRoleX.doesNotMatchKeyInQuery( - 'objectId', - 'belongsTo.objectId', - rolesOfTypeX - ); + groupsWithRoleX.doesNotMatchKeyInQuery('objectId', 'belongsTo.objectId', rolesOfTypeX); const results = await groupsWithRoleX.find(); equal(results.length, 1); equal(results[0].get('name'), group2.get('name')); }); - it('withJSON supports geoWithin.centerSphere', (done) => { + it('withJSON supports geoWithin.centerSphere', done => { const inbound = new Parse.GeoPoint(1.5, 1.5); const onbound = new Parse.GeoPoint(10, 10); const outbound = new Parse.GeoPoint(20, 20); @@ -4640,7 +4460,7 @@ describe('Parse.Query testing', () => { q.withJSON(jsonQ); return q.find(); }) - .then((results) => { + .then(results => { equal(results.length, 2); const q = new Parse.Query(TestObject); const jsonQ = q.toJSON(); @@ -4652,17 +4472,17 @@ describe('Parse.Query testing', () => { q.withJSON(jsonQ); return q.find(); }) - .then((results) => { + .then(results => { equal(results.length, 2); done(); }) - .catch((error) => { + .catch(error => { fail(error); done(); }); }); - it('withJSON with geoWithin.centerSphere fails without parameters', (done) => { + it('withJSON with geoWithin.centerSphere fails without parameters', done => { const q = new Parse.Query(TestObject); const jsonQ = q.toJSON(); jsonQ.where.location = { @@ -4673,11 +4493,11 @@ describe('Parse.Query testing', () => { q.withJSON(jsonQ); q.find() .then(done.fail) - .catch((e) => expect(e.code).toBe(Parse.Error.INVALID_JSON)) + .catch(e => expect(e.code).toBe(Parse.Error.INVALID_JSON)) .then(done); }); - it('withJSON with geoWithin.centerSphere fails with invalid distance', (done) => { + it('withJSON with geoWithin.centerSphere fails with invalid distance', done => { const q = new Parse.Query(TestObject); const jsonQ = q.toJSON(); jsonQ.where.location = { @@ -4688,11 +4508,11 @@ describe('Parse.Query testing', () => { q.withJSON(jsonQ); q.find() .then(done.fail) - .catch((e) => expect(e.code).toBe(Parse.Error.INVALID_JSON)) + .catch(e => expect(e.code).toBe(Parse.Error.INVALID_JSON)) .then(done); }); - it('withJSON with geoWithin.centerSphere fails with invalid coordinate', (done) => { + it('withJSON with geoWithin.centerSphere fails with invalid coordinate', done => { const q = new Parse.Query(TestObject); const jsonQ = q.toJSON(); jsonQ.where.location = { @@ -4706,7 +4526,7 @@ describe('Parse.Query testing', () => { .catch(() => done()); }); - it('withJSON with geoWithin.centerSphere fails with invalid geo point', (done) => { + it('withJSON with geoWithin.centerSphere fails with invalid geo point', done => { const q = new Parse.Query(TestObject); const jsonQ = q.toJSON(); jsonQ.where.location = { @@ -4848,7 +4668,7 @@ describe('Parse.Query testing', () => { equal(results[0].get('array').length, 105); }); - it('exclude keys (sdk query)', async (done) => { + it('exclude keys (sdk query)', async done => { const obj = new TestObject({ foo: 'baz', hello: 'world' }); await obj.save(); @@ -4861,7 +4681,7 @@ describe('Parse.Query testing', () => { done(); }); - xit('todo: exclude keys with select key (sdk query get)', async (done) => { + xit('todo: exclude keys with select key (sdk query get)', async done => { // there is some problem with js sdk caching const obj = new TestObject({ foo: 'baz', hello: 'world' }); diff --git a/spec/ParseRelation.spec.js b/spec/ParseRelation.spec.js index bd677145..a51d4c90 100644 --- a/spec/ParseRelation.spec.js +++ b/spec/ParseRelation.spec.js @@ -101,7 +101,7 @@ describe('Parse.Relation testing', () => { let relation; Parse.Object.saveAll(childObjects) - .then(function() { + .then(function () { const ParentObject = Parse.Object.extend('ParentObject'); parent = new ParentObject(); parent.set('x', 4); @@ -112,10 +112,10 @@ describe('Parse.Relation testing', () => { relation.add(childObjects[2]); return parent.save(); }) - .then(function() { + .then(function () { return relation.query().find(); }) - .then(function(list) { + .then(function (list) { equal(list.length, 2, 'Should have gotten two elements back'); ok(!parent.dirty('child'), 'The relation should not be dirty'); relation.remove(childObjects[1]); @@ -124,16 +124,16 @@ describe('Parse.Relation testing', () => { relation.add(childObjects[0]); return parent.save(); }) - .then(function() { + .then(function () { return relation.query().find(); }) .then( - function(list) { + function (list) { equal(list.length, 2, 'Deletes and then adds should have worked'); ok(!parent.dirty('child'), 'The relation should not be dirty'); done(); }, - function(err) { + function (err) { ok(false, err.message); done(); } @@ -151,7 +151,7 @@ describe('Parse.Relation testing', () => { let relation; Parse.Object.saveAll(childObjects) - .then(function() { + .then(function () { const ParentObject = Parse.Object.extend('ParentObject'); parent = new ParentObject(); parent.set('x', 4); @@ -159,14 +159,14 @@ describe('Parse.Relation testing', () => { relation.add(childObjects); return parent.save(); }) - .then(function() { + .then(function () { const query = relation.query(); query.descending('createdAt'); query.skip(1); query.limit(3); return query.find(); }) - .then(function(list) { + .then(function (list) { expect(list.length).toBe(3); }) .then(done, done.fail); @@ -193,11 +193,7 @@ describe('Parse.Relation testing', () => { 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' - ); + equal(list[0].id, childObjects[2].id, 'We should have gotten back the right result'); }); it('queries on relation fields', async () => { @@ -267,9 +263,7 @@ describe('Parse.Relation testing', () => { .then(() => { const objectsWithChild0InBothChildren = new Parse.Query(ParentObject); objectsWithChild0InBothChildren.containedIn('child', [childObjects[0]]); - objectsWithChild0InBothChildren.containedIn('otherChild', [ - childObjects[0], - ]); + objectsWithChild0InBothChildren.containedIn('otherChild', [childObjects[0]]); return objectsWithChild0InBothChildren.find(); }) .then(objectsWithChild0InBothChildren => { @@ -279,9 +273,7 @@ describe('Parse.Relation testing', () => { .then(() => { const objectsWithChild4andOtherChild1 = new Parse.Query(ParentObject); objectsWithChild4andOtherChild1.containedIn('child', [childObjects[4]]); - objectsWithChild4andOtherChild1.containedIn('otherChild', [ - childObjects[1], - ]); + objectsWithChild4andOtherChild1.containedIn('otherChild', [childObjects[1]]); return objectsWithChild4andOtherChild1.find(); }) .then(objects => { @@ -291,51 +283,48 @@ describe('Parse.Relation testing', () => { }); }); - it_exclude_dbs(['postgres'])( - 'query on pointer and relation fields with equal', - done => { - 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) - .then(() => { - const ParentObject = Parse.Object.extend('ParentObject'); - const parent = new ParentObject(); - parent.set('x', 4); - const relation = parent.relation('toChilds'); - relation.add(childObjects[0]); - relation.add(childObjects[1]); - relation.add(childObjects[2]); - - const parent2 = new ParentObject(); - parent2.set('x', 3); - parent2.set('toChild', childObjects[2]); - - const parents = []; - parents.push(parent); - parents.push(parent2); - parents.push(new ParentObject()); - - return Parse.Object.saveAll(parents).then(() => { - const query = new Parse.Query(ParentObject); - query.equalTo('objectId', parent.id); - query.equalTo('toChilds', childObjects[2]); - - return query.find().then(list => { - equal(list.length, 1, 'There should be 1 result'); - done(); - }); - }); - }) - .catch(err => { - jfail(err); - done(); - }); + it_exclude_dbs(['postgres'])('query on pointer and relation fields with equal', done => { + 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) + .then(() => { + const ParentObject = Parse.Object.extend('ParentObject'); + const parent = new ParentObject(); + parent.set('x', 4); + const relation = parent.relation('toChilds'); + relation.add(childObjects[0]); + relation.add(childObjects[1]); + relation.add(childObjects[2]); + + const parent2 = new ParentObject(); + parent2.set('x', 3); + parent2.set('toChild', childObjects[2]); + + const parents = []; + parents.push(parent); + parents.push(parent2); + parents.push(new ParentObject()); + + return Parse.Object.saveAll(parents).then(() => { + const query = new Parse.Query(ParentObject); + query.equalTo('objectId', parent.id); + query.equalTo('toChilds', childObjects[2]); + + return query.find().then(list => { + equal(list.length, 1, 'There should be 1 result'); + done(); + }); + }); + }) + .catch(err => { + jfail(err); + done(); + }); + }); it('query on pointer and relation fields with equal bis', done => { const ChildObject = Parse.Object.extend('ChildObject'); @@ -377,52 +366,49 @@ describe('Parse.Relation testing', () => { }); }); - it_exclude_dbs(['postgres'])( - 'or queries on pointer and relation fields', - done => { - const ChildObject = Parse.Object.extend('ChildObject'); - const childObjects = []; - for (let i = 0; i < 10; i++) { - childObjects.push(new ChildObject({ x: i })); - } + it_exclude_dbs(['postgres'])('or queries on pointer and relation fields', done => { + 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).then(() => { - const ParentObject = Parse.Object.extend('ParentObject'); - const parent = new ParentObject(); - parent.set('x', 4); - const relation = parent.relation('toChilds'); - relation.add(childObjects[0]); - relation.add(childObjects[1]); - relation.add(childObjects[2]); + Parse.Object.saveAll(childObjects).then(() => { + const ParentObject = Parse.Object.extend('ParentObject'); + const parent = new ParentObject(); + parent.set('x', 4); + const relation = parent.relation('toChilds'); + relation.add(childObjects[0]); + relation.add(childObjects[1]); + relation.add(childObjects[2]); - const parent2 = new ParentObject(); - parent2.set('x', 3); - parent2.set('toChild', childObjects[2]); + const parent2 = new ParentObject(); + parent2.set('x', 3); + parent2.set('toChild', childObjects[2]); - const parents = []; - parents.push(parent); - parents.push(parent2); - parents.push(new ParentObject()); + const parents = []; + parents.push(parent); + parents.push(parent2); + parents.push(new ParentObject()); - return Parse.Object.saveAll(parents).then(() => { - const query1 = new Parse.Query(ParentObject); - query1.containedIn('toChilds', [childObjects[2]]); - const query2 = new Parse.Query(ParentObject); - query2.equalTo('toChild', childObjects[2]); - const query = Parse.Query.or(query1, query2); - return query.find().then(list => { - const objectIds = list.map(function(item) { - return item.id; - }); - expect(objectIds.indexOf(parent.id)).not.toBe(-1); - expect(objectIds.indexOf(parent2.id)).not.toBe(-1); - equal(list.length, 2, 'There should be 2 results'); - done(); + return Parse.Object.saveAll(parents).then(() => { + const query1 = new Parse.Query(ParentObject); + query1.containedIn('toChilds', [childObjects[2]]); + const query2 = new Parse.Query(ParentObject); + query2.equalTo('toChild', childObjects[2]); + const query = Parse.Query.or(query1, query2); + return query.find().then(list => { + const objectIds = list.map(function (item) { + return item.id; }); + expect(objectIds.indexOf(parent.id)).not.toBe(-1); + expect(objectIds.indexOf(parent2.id)).not.toBe(-1); + equal(list.length, 2, 'There should be 2 results'); + done(); }); }); - } - ); + }); + }); it('Get query on relation using un-fetched parent object', done => { // Setup data model @@ -431,13 +417,13 @@ describe('Parse.Relation testing', () => { const origWheel = new Wheel(); origWheel .save() - .then(function() { + .then(function () { const car = new Car(); const relation = car.relation('wheels'); relation.add(origWheel); return car.save(); }) - .then(function(car) { + .then(function (car) { // Test starts here. // Create an un-fetched shell car object const unfetchedCar = new Car(); @@ -449,16 +435,16 @@ describe('Parse.Relation testing', () => { // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }. return query.get(origWheel.id); }) - .then(function(wheel) { + .then(function (wheel) { // Make sure this is Wheel and not Car. strictEqual(wheel.className, 'Wheel'); strictEqual(wheel.id, origWheel.id); }) .then( - function() { + function () { done(); }, - function(err) { + function (err) { ok(false, 'unexpected error: ' + JSON.stringify(err)); done(); } @@ -472,13 +458,13 @@ describe('Parse.Relation testing', () => { const origWheel = new Wheel(); origWheel .save() - .then(function() { + .then(function () { const car = new Car(); const relation = car.relation('wheels'); relation.add(origWheel); return car.save(); }) - .then(function(car) { + .then(function (car) { // Test starts here. // Create an un-fetched shell car object const unfetchedCar = new Car(); @@ -490,17 +476,17 @@ describe('Parse.Relation testing', () => { // of /1/classes/Wheel and pass { "redirectClassNameForKey":"wheels" }. return query.find(origWheel.id); }) - .then(function(results) { + .then(function (results) { // Make sure this is Wheel and not Car. const wheel = results[0]; strictEqual(wheel.className, 'Wheel'); strictEqual(wheel.id, origWheel.id); }) .then( - function() { + function () { done(); }, - function(err) { + function (err) { ok(false, 'unexpected error: ' + JSON.stringify(err)); done(); } @@ -611,7 +597,7 @@ describe('Parse.Relation testing', () => { ); }); - it('select query', function(done) { + it('select query', function (done) { const RestaurantObject = Parse.Object.extend('Restaurant'); const PersonObject = Parse.Object.extend('Person'); const OwnerObject = Parse.Object.extend('Owner'); @@ -628,7 +614,7 @@ describe('Parse.Relation testing', () => { const allObjects = [owner].concat(restaurants).concat(persons); expect(allObjects.length).toEqual(6); Parse.Object.saveAll([owner].concat(restaurants).concat(persons)) - .then(function() { + .then(function () { owner.relation('restaurants').add(restaurants); return owner.save(); }) @@ -654,7 +640,7 @@ describe('Parse.Relation testing', () => { ); }); - it('dontSelect query', function(done) { + it('dontSelect query', function (done) { const RestaurantObject = Parse.Object.extend('Restaurant'); const PersonObject = Parse.Object.extend('Person'); const OwnerObject = Parse.Object.extend('Owner'); @@ -671,7 +657,7 @@ describe('Parse.Relation testing', () => { const allObjects = [owner].concat(restaurants).concat(persons); expect(allObjects.length).toEqual(6); Parse.Object.saveAll([owner].concat(restaurants).concat(persons)) - .then(function() { + .then(function () { owner.relation('restaurants').add(restaurants); return owner.save(); }) @@ -838,10 +824,7 @@ describe('Parse.Relation testing', () => { // After saves or finds const otherParent = new Parse.Object('Parent'); otherParent.id = parent.id; - return otherParent - .relation('children') - .query() - .find(); + return otherParent.relation('children').query().find(); }) .then(children => { // Without an after find all is good, all results have been redirected with proper className @@ -857,10 +840,7 @@ describe('Parse.Relation testing', () => { }); const otherParent = new Parse.Object('Parent'); otherParent.id = parent.id; - return otherParent - .relation('children') - .query() - .find(); + return otherParent.relation('children').query().find(); }) .then(children => { children.forEach(child => { diff --git a/spec/ParseRole.spec.js b/spec/ParseRole.spec.js index 47af0345..544b5f87 100644 --- a/spec/ParseRole.spec.js +++ b/spec/ParseRole.spec.js @@ -74,7 +74,7 @@ describe('Parse Role testing', () => { ); }); - const createRole = function(name, sibling, user) { + const createRole = function (name, sibling, user) { const role = new Parse.Role(name, new Parse.ACL()); if (user) { const users = role.relation('users'); @@ -92,9 +92,9 @@ describe('Parse Role testing', () => { const allRoles = [rootRole].concat(roleNames); const roleObjs = {}; - const createAllRoles = function(user) { - const promises = allRoles.map(function(roleName) { - return createRole(roleName, null, user).then(function(roleObj) { + const createAllRoles = function (user) { + const promises = allRoles.map(function (roleName) { + return createRole(roleName, null, user).then(function (roleObj) { roleObjs[roleName] = roleObj; return roleObj; }); @@ -112,7 +112,7 @@ describe('Parse Role testing', () => { }) .then(roles => { const rootRoleObj = roleObjs[rootRole]; - roles.forEach(function(role, i) { + roles.forEach(function (role, i) { // Add all roles to the RootRole if (role.id !== rootRoleObj.id) { role.relation('roles').add(rootRoleObj); @@ -131,17 +131,14 @@ describe('Parse Role testing', () => { isMaster: true, user: user, }); - getAllRolesSpy = spyOn( - auth, - '_getAllRolesNamesForRoleIds' - ).and.callThrough(); + getAllRolesSpy = spyOn(auth, '_getAllRolesNamesForRoleIds').and.callThrough(); return auth._loadRoles(); }) .then(roles => { expect(roles.length).toEqual(4); - allRoles.forEach(function(name) { + allRoles.forEach(function (name) { expect(roles.indexOf('role:' + name)).not.toBe(-1); }); @@ -193,7 +190,7 @@ describe('Parse Role testing', () => { }); done(); }, - function() { + function () { fail('should succeed'); done(); } @@ -259,26 +256,16 @@ describe('Parse Role testing', () => { const moderator = new Parse.Role('Moderator', new Parse.ACL()); const superModerator = new Parse.Role('SuperModerator', new Parse.ACL()); const contentManager = new Parse.Role('ContentManager', new Parse.ACL()); - const superContentManager = new Parse.Role( - 'SuperContentManager', - new Parse.ACL() - ); - Parse.Object.saveAll( - [admin, moderator, contentManager, superModerator, superContentManager], - { useMasterKey: true } - ) + const superContentManager = new Parse.Role('SuperContentManager', new Parse.ACL()); + Parse.Object.saveAll([admin, moderator, contentManager, superModerator, superContentManager], { + useMasterKey: true, + }) .then(() => { contentManager.getRoles().add([moderator, superContentManager]); moderator.getRoles().add([admin, superModerator]); superContentManager.getRoles().add(superModerator); return Parse.Object.saveAll( - [ - admin, - moderator, - contentManager, - superModerator, - superContentManager, - ], + [admin, moderator, contentManager, superModerator, superContentManager], { useMasterKey: true } ); }) @@ -286,17 +273,15 @@ describe('Parse Role testing', () => { const auth = new Auth({ config: Config.get('test'), isMaster: true }); // For each role, fetch their sibling, what they inherit // return with result and roleId for later comparison - const promises = [admin, moderator, contentManager, superModerator].map( - role => { - return auth._getAllRolesNamesForRoleIds([role.id]).then(result => { - return Promise.resolve({ - id: role.id, - name: role.get('name'), - roleNames: result, - }); + const promises = [admin, moderator, contentManager, superModerator].map(role => { + return auth._getAllRolesNamesForRoleIds([role.id]).then(result => { + return Promise.resolve({ + id: role.id, + name: role.get('name'), + roleNames: result, }); - } - ); + }); + }); return Promise.all(promises); }) @@ -563,7 +548,7 @@ describe('Parse Role testing', () => { const query = new Parse.Query(Parse.Role); query.equalTo('name', 'admin'); query.equalTo('users', user); - query.find().then(function(roles) { + query.find().then(function (roles) { expect(roles.length).toEqual(1); done(); }); @@ -582,17 +567,15 @@ describe('Parse Role testing', () => { users.add(user); role.save({}, { useMasterKey: true }).then(() => { const otherUser = new Parse.User(); - otherUser - .save({ username: 'otherUser', password: 'otherUser' }) - .then(otherUser => { - const query = new Parse.Query(Parse.Role); - query.equalTo('name', 'admin'); - query.equalTo('users', otherUser); - query.find().then(function(roles) { - expect(roles.length).toEqual(0); - done(); - }); + otherUser.save({ username: 'otherUser', password: 'otherUser' }).then(otherUser => { + const query = new Parse.Query(Parse.Role); + query.equalTo('name', 'admin'); + query.equalTo('users', otherUser); + query.find().then(function (roles) { + expect(roles.length).toEqual(0); + done(); }); + }); }); }); }); @@ -610,7 +593,7 @@ describe('Parse Role testing', () => { const query = new Parse.Query(Parse.Role); query.equalTo('name', 'admin'); query.equalTo('users', null); - query.find().then(function(roles) { + query.find().then(function (roles) { expect(roles.length).toEqual(0); done(); }); diff --git a/spec/ParseServer.spec.js b/spec/ParseServer.spec.js index 9f026f3f..03d1eaf4 100644 --- a/spec/ParseServer.spec.js +++ b/spec/ParseServer.spec.js @@ -1,8 +1,7 @@ 'use strict'; /* Tests for ParseServer.js */ const express = require('express'); -const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter') - .default; +const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; const PostgresStorageAdapter = require('../lib/Adapters/Storage/Postgres/PostgresStorageAdapter') .default; const ParseServer = require('../lib/ParseServer').default; @@ -13,7 +12,7 @@ describe('Server Url Checks', () => { let server; beforeAll(done => { const app = express(); - app.get('/health', function(req, res) { + app.get('/health', function (req, res) { res.json({ status: 'ok', }); @@ -27,7 +26,7 @@ describe('Server Url Checks', () => { it('validate good server url', done => { Parse.serverURL = 'http://localhost:13376'; - ParseServer.verifyServerUrl(function(result) { + ParseServer.verifyServerUrl(function (result) { if (!result) { done.fail('Did not pass valid url'); } @@ -38,7 +37,7 @@ describe('Server Url Checks', () => { it('mark bad server url', done => { spyOn(console, 'warn').and.callFake(() => {}); Parse.serverURL = 'notavalidurl'; - ParseServer.verifyServerUrl(function(result) { + ParseServer.verifyServerUrl(function (result) { if (result) { done.fail('Did not mark invalid url'); } @@ -47,10 +46,8 @@ describe('Server Url Checks', () => { }); xit('handleShutdown, close connection', done => { - const mongoURI = - 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; - const postgresURI = - 'postgres://localhost:5432/parse_server_postgres_adapter_test_database'; + const mongoURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; + const postgresURI = 'postgres://localhost:5432/parse_server_postgres_adapter_test_database'; let databaseAdapter; if (process.env.PARSE_SERVER_TEST_DB === 'postgres') { databaseAdapter = new PostgresStorageAdapter({ @@ -92,9 +89,7 @@ describe('Server Url Checks', () => { }); it('does not have unhandled promise rejection in the case of load error', done => { - const parseServerProcess = spawn( - path.resolve(__dirname, './support/FailingServer.js') - ); + const parseServerProcess = spawn(path.resolve(__dirname, './support/FailingServer.js')); let stdout; let stderr; parseServerProcess.stdout.on('data', data => { diff --git a/spec/ParseServerRESTController.spec.js b/spec/ParseServerRESTController.spec.js index 62e454bb..fcf8281a 100644 --- a/spec/ParseServerRESTController.spec.js +++ b/spec/ParseServerRESTController.spec.js @@ -106,17 +106,11 @@ describe('ParseServerRESTController', () => { spyOn(router, 'tryRouteRequest').and.callThrough(); RESTController = ParseServerRESTController(Parse.applicationId, router); const resp = await RESTController.request('POST', '/classes/MyObject'); - const { - status, - response, - location, - } = await router.tryRouteRequest.calls.all()[0].returnValue; + const { status, response, location } = await router.tryRouteRequest.calls.all()[0].returnValue; expect(status).toBe(201); expect(response).toEqual(resp); - expect(location).toBe( - `http://localhost:8378/1/classes/MyObject/${resp.objectId}` - ); + expect(location).toBe(`http://localhost:8378/1/classes/MyObject/${resp.objectId}`); }); it('should handle response status in batch', async () => { @@ -229,9 +223,10 @@ describe('ParseServerRESTController', () => { expect(databaseAdapter.createObject.calls.argsFor(0)[3]).toBe( databaseAdapter.createObject.calls.argsFor(1)[3] ); - expect( - results.map(result => result.get('key')).sort() - ).toEqual(['value1', 'value2']); + expect(results.map(result => result.get('key')).sort()).toEqual([ + 'value1', + 'value2', + ]); done(); }); }); @@ -508,10 +503,7 @@ describe('ParseServerRESTController', () => { const query = new Parse.Query('MyObject'); const results = await query.find(); - expect(results.map(result => result.get('key')).sort()).toEqual([ - 'value1', - 'value2', - ]); + expect(results.map(result => result.get('key')).sort()).toEqual(['value1', 'value2']); const query2 = new Parse.Query('MyObject2'); const results2 = await query2.find(); @@ -519,10 +511,7 @@ describe('ParseServerRESTController', () => { const query3 = new Parse.Query('MyObject3'); const results3 = await query3.find(); - expect(results3.map(result => result.get('key')).sort()).toEqual([ - 'value1', - 'value2', - ]); + expect(results3.map(result => result.get('key')).sort()).toEqual(['value1', 'value2']); expect(databaseAdapter.createObject.calls.count()).toBe(13); let transactionalSession; @@ -653,11 +642,7 @@ describe('ParseServerRESTController', () => { password: 'world', }).then( () => { - jfail( - new Error( - 'Success callback should not be called when passing an empty username.' - ) - ); + jfail(new Error('Success callback should not be called when passing an empty username.')); done(); }, err => { @@ -674,11 +659,7 @@ describe('ParseServerRESTController', () => { password: '', }).then( () => { - jfail( - new Error( - 'Success callback should not be called when passing an empty password.' - ) - ); + jfail(new Error('Success callback should not be called when passing an empty password.')); done(); }, err => { diff --git a/spec/ParseUser.spec.js b/spec/ParseUser.spec.js index 1c4d6dbb..a44926ca 100644 --- a/spec/ParseUser.spec.js +++ b/spec/ParseUser.spec.js @@ -7,8 +7,7 @@ 'use strict'; -const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter') - .default; +const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; const request = require('../lib/request'); const passwordCrypto = require('../lib/password'); const Config = require('../lib/Config'); @@ -87,9 +86,7 @@ describe('Parse.User testing', () => { }) .catch(err => { expect(err.status).toBe(404); - expect(err.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(err.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }); }); @@ -116,9 +113,7 @@ describe('Parse.User testing', () => { }) .catch(err => { expect(err.status).toBe(404); - expect(err.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(err.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }); }); @@ -243,8 +238,7 @@ describe('Parse.User testing', () => { }); it_only_db('mongo')('should let legacy users without ACL login', async () => { - const databaseURI = - 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; + const databaseURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; const adapter = new MongoStorageAdapter({ collectionPrefix: 'test_', uri: databaseURI, @@ -262,8 +256,7 @@ describe('Parse.User testing', () => { const collection = await adapter._adaptiveCollection('_User'); await collection.insertOne({ // the hashed password is 'password' hashed - _hashed_password: - '$2b$10$mJ2ca2UbCM9hlojYHZxkQe8pyEXe5YMg0nMdvP4AJBeqlTEZJ6/Uu', + _hashed_password: '$2b$10$mJ2ca2UbCM9hlojYHZxkQe8pyEXe5YMg0nMdvP4AJBeqlTEZJ6/Uu', _session_token: 'xxx', email: 'xxx@a.b', username: 'oldUser', @@ -419,10 +412,7 @@ describe('Parse.User testing', () => { .then( function () { // This should have failed actually. - ok( - false, - "Shouldn't have been able to log in with garbage session token." - ); + ok(false, "Shouldn't have been able to log in with garbage session token."); }, function (error) { ok(error); @@ -576,10 +566,7 @@ describe('Parse.User testing', () => { await user.save({ ACL: acl }, { useMasterKey: true }); // Try to update from admin... should all work fine - await user.save( - { key: 'fromAdmin' }, - { sessionToken: admin.getSessionToken() } - ); + await user.save({ key: 'fromAdmin' }, { sessionToken: admin.getSessionToken() }); await user.fetch(); expect(user.toJSON().key).toEqual('fromAdmin'); @@ -896,11 +883,7 @@ describe('Parse.User testing', () => { equal(aliceAgain.get('username'), 'alice'); equal(aliceAgain.id, alice.id, 'currentUser should have objectId'); ok(aliceAgain.getSessionToken(), 'currentUser should have a sessionToken'); - equal( - alice.get('password'), - undefined, - 'currentUser should not have password' - ); + equal(alice.get('password'), undefined, 'currentUser should not have password'); done(); }); @@ -920,16 +903,9 @@ describe('Parse.User testing', () => { delete Parse.User._currentUserMatchesDisk; const userFromDisk = Parse.User.current(); - equal( - userFromDisk.get('password'), - undefined, - 'password should not be in attributes' - ); + equal(userFromDisk.get('password'), undefined, 'password should not be in attributes'); equal(userFromDisk.id, id, 'id should be set'); - ok( - userFromDisk.getSessionToken(), - 'currentUser should have a sessionToken' - ); + ok(userFromDisk.getSessionToken(), 'currentUser should have a sessionToken'); done(); }); }); @@ -963,11 +939,7 @@ describe('Parse.User testing', () => { 'saving user should not remove existing fields' ); - equal( - userInMemory.get('some_field'), - 1, - 'saving user should save specified field' - ); + equal(userInMemory.get('some_field'), 1, 'saving user should save specified field'); equal( userInMemory.get('password'), @@ -993,10 +965,7 @@ describe('Parse.User testing', () => { ok(userInMemory.createdAt instanceof Date); - ok( - userInMemory.getSessionToken(), - 'user should have a sessionToken after saving' - ); + ok(userInMemory.getSessionToken(), 'user should have a sessionToken after saving'); // Force the current user to read from localStorage, and check again delete Parse.User._currentUser; @@ -1009,11 +978,7 @@ describe('Parse.User testing', () => { 'userFromDisk should have previously existing fields' ); - equal( - userFromDisk.get('some_field'), - 1, - 'userFromDisk should have saved field' - ); + equal(userFromDisk.get('some_field'), 1, 'userFromDisk should have saved field'); equal( userFromDisk.get('password'), @@ -1039,10 +1004,7 @@ describe('Parse.User testing', () => { ok(userFromDisk.createdAt instanceof Date); - ok( - userFromDisk.getSessionToken(), - 'userFromDisk should have a sessionToken' - ); + ok(userFromDisk.getSessionToken(), 'userFromDisk should have a sessionToken'); done(); }, @@ -1239,10 +1201,7 @@ describe('Parse.User testing', () => { ok(model.extended(), 'Should have used subclass.'); strictEqual(provider.authData.id, provider.synchronizedUserId); strictEqual(provider.authData.access_token, provider.synchronizedAuthToken); - strictEqual( - provider.authData.expiration_date, - provider.synchronizedExpiration - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked to facebook'); done(); }); @@ -1288,10 +1247,7 @@ describe('Parse.User testing', () => { ok(model.extended(), 'Should have used subclass.'); strictEqual(provider.authData.id, provider.synchronizedUserId); strictEqual(provider.authData.access_token, provider.synchronizedAuthToken); - strictEqual( - provider.authData.expiration_date, - provider.synchronizedExpiration - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked to facebook'); Parse.Cloud.run('checkLogin').then(done, done); @@ -1299,10 +1255,7 @@ describe('Parse.User testing', () => { it('log in with provider and update token', async done => { const provider = getMockFacebookProvider(); - const secondProvider = getMockFacebookProviderWithIdToken( - '8675309', - 'jenny_valid_token' - ); + const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token'); Parse.User._registerAuthenticationProvider(provider); await Parse.User._logInWith('facebook'); Parse.User._registerAuthenticationProvider(secondProvider); @@ -1384,10 +1337,7 @@ describe('Parse.User testing', () => { 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 - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked to facebook'); Parse.User.logOut().then(async () => { @@ -1395,10 +1345,7 @@ describe('Parse.User testing', () => { provider.loggedOut = false; const innerModel = await Parse.User._logInWith('facebook'); ok(innerModel instanceof Parse.User, 'Model should be a Parse.User'); - ok( - innerModel === Parse.User.current(), - 'Returned model should be the current user' - ); + ok(innerModel === Parse.User.current(), 'Returned model should be the current user'); ok(provider.authData.id === provider.synchronizedUserId); ok(provider.authData.access_token === provider.synchronizedAuthToken); ok(innerModel._isLinked('facebook'), 'User should be linked to facebook'); @@ -1584,10 +1531,7 @@ describe('Parse.User testing', () => { strictEqual(Parse.User.current(), model); strictEqual(provider.authData.id, provider.synchronizedUserId); strictEqual(provider.authData.access_token, provider.synchronizedAuthToken); - strictEqual( - provider.authData.expiration_date, - provider.synchronizedExpiration - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked'); done(); }); @@ -1606,10 +1550,7 @@ describe('Parse.User testing', () => { strictEqual(Parse.User.current(), model); strictEqual(provider.authData.id, provider.synchronizedUserId); strictEqual(provider.authData.access_token, provider.synchronizedAuthToken); - strictEqual( - provider.authData.expiration_date, - provider.synchronizedExpiration - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked.'); const user2 = new Parse.User(); user2.set('username', 'testLinkWithProviderToAlreadyLinkedUser2'); @@ -1704,10 +1645,7 @@ describe('Parse.User testing', () => { 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 - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked to facebook.'); await model._unlinkFrom('facebook'); ok(!model._isLinked('facebook'), 'User should not be linked.'); @@ -1726,10 +1664,7 @@ describe('Parse.User testing', () => { 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 - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked to facebook'); await model._unlinkFrom('facebook'); @@ -1756,10 +1691,7 @@ describe('Parse.User testing', () => { 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 - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked to facebook'); Parse.User._registerAuthenticationProvider(mockProvider); const objectId = model.id; @@ -1772,10 +1704,7 @@ describe('Parse.User testing', () => { it('link multiple providers and updates token', async done => { const provider = getMockFacebookProvider(); - const secondProvider = getMockFacebookProviderWithIdToken( - '8675309', - 'jenny_valid_token' - ); + const secondProvider = getMockFacebookProviderWithIdToken('8675309', 'jenny_valid_token'); const mockProvider = getMockMyOauthProvider(); Parse.User._registerAuthenticationProvider(provider); @@ -1802,10 +1731,7 @@ describe('Parse.User testing', () => { 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 - ); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked('facebook'), 'User should be linked to facebook'); Parse.User._registerAuthenticationProvider(mockProvider); const objectId = model.id; @@ -1857,9 +1783,7 @@ describe('Parse.User testing', () => { // make sure the location header is properly set expect(userId).not.toBeUndefined(); expect(body.objectId).toEqual(userId); - expect(response.headers.location).toEqual( - Parse.serverURL + '/users/' + userId - ); + expect(response.headers.location).toEqual(Parse.serverURL + '/users/' + userId); done(); }); }); @@ -1891,9 +1815,7 @@ describe('Parse.User testing', () => { // Simulate a remotely expired token (like a short lived one) // In this case, we want success as it was valid once. // If the client needs an updated one, do lock the user out - defaultConfiguration.auth.shortLivedAuth.setValidAccessToken( - 'otherToken' - ); + defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('otherToken'); return Parse.User._logInWith('shortLivedAuth', {}); }) .then( @@ -1932,9 +1854,7 @@ describe('Parse.User testing', () => { // Simulate a remotely expired token (like a short lived one) // In this case, we want success as it was valid once. // If the client needs an updated one, do lock the user out - defaultConfiguration.auth.shortLivedAuth.setValidAccessToken( - 'otherToken' - ); + defaultConfiguration.auth.shortLivedAuth.setValidAccessToken('otherToken'); return request({ method: 'PUT', url: Parse.serverURL + '/users/' + Parse.User.current().id, @@ -2176,10 +2096,7 @@ describe('Parse.User testing', () => { equal(users.length, 2); users.forEach(user => { expect(user.getSessionToken()).toBeUndefined(); - ok( - !user.getSessionToken(), - 'user should not have a session token.' - ); + ok(!user.getSessionToken(), 'user should not have a session token.'); }); done(); }, @@ -2286,10 +2203,7 @@ describe('Parse.User testing', () => { user2.set('username', 'Test1'); user2.set('password', 'test'); await expectAsync(user2.signUp()).toBeRejectedWith( - new Parse.Error( - Parse.Error.USERNAME_TAKEN, - 'Account already exists for this username.' - ) + new Parse.Error(Parse.Error.USERNAME_TAKEN, 'Account already exists for this username.') ); }); @@ -2303,10 +2217,7 @@ describe('Parse.User testing', () => { user2.setUsername('Test1'); user2.setPassword('test'); await expectAsync(user2.signUp()).toBeRejectedWith( - new Parse.Error( - Parse.Error.USERNAME_TAKEN, - 'Account already exists for this username.' - ) + new Parse.Error(Parse.Error.USERNAME_TAKEN, 'Account already exists for this username.') ); }); @@ -2322,10 +2233,7 @@ describe('Parse.User testing', () => { user2.setPassword('test'); user2.setEmail('Test@Example.Com'); await expectAsync(user2.signUp()).toBeRejectedWith( - new Parse.Error( - Parse.Error.EMAIL_TAKEN, - 'Account already exists for this email address.' - ) + new Parse.Error(Parse.Error.EMAIL_TAKEN, 'Account already exists for this email address.') ); }); @@ -2344,10 +2252,7 @@ describe('Parse.User testing', () => { user2.setEmail('Test@Example.Com'); await expectAsync(user2.save()).toBeRejectedWith( - new Parse.Error( - Parse.Error.EMAIL_TAKEN, - 'Account already exists for this email address.' - ) + new Parse.Error(Parse.Error.EMAIL_TAKEN, 'Account already exists for this email address.') ); }); @@ -2375,9 +2280,7 @@ describe('Parse.User testing', () => { ]; // need a bunch of spare random strings per api request - spyOn(cryptoUtils, 'randomString').and.returnValues( - ...insensitiveCollisions - ); + spyOn(cryptoUtils, 'randomString').and.returnValues(...insensitiveCollisions); }); it('should not fail on case insensitive matches', async () => { @@ -2721,8 +2624,7 @@ describe('Parse.User testing', () => { }); it('password format matches hosted parse', done => { - const hashed = - '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie'; + const hashed = '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie'; passwordCrypto.compare('test', hashed).then( pass => { expect(pass).toBe(true); @@ -2876,8 +2778,7 @@ describe('Parse.User testing', () => { '_User', { username: 'user', - _hashed_password: - '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie', + _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie', _auth_data_facebook: null, }, {} @@ -2911,8 +2812,7 @@ describe('Parse.User testing', () => { '_User', { username: 'user', - _hashed_password: - '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie', + _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie', _auth_data_facebook: null, }, {} @@ -3114,9 +3014,7 @@ describe('Parse.User testing', () => { expect(emailCalled).toBeTruthy(); expect(emailOptions).toBeDefined(); expect(err.status).toBe(400); - expect(err.text).toMatch( - '{"code":125,"error":"you must provide a valid email string"}' - ); + expect(err.text).toMatch('{"code":125,"error":"you must provide a valid email string"}'); done(); }); }); @@ -3405,9 +3303,7 @@ describe('Parse.User testing', () => { done(); }) .catch(err => { - expect(err.message).toBe( - "Clients aren't allowed to manually update email verification." - ); + expect(err.message).toBe("Clients aren't allowed to manually update email verification."); done(); }); }); @@ -3525,8 +3421,7 @@ describe('Parse.User testing', () => { }) .then(() => request({ - url: - 'http://localhost:8378/1/login?email=test@email.com&username=hello&password=world', + url: 'http://localhost:8378/1/login?email=test@email.com&username=hello&password=world', headers: { 'X-Parse-Application-Id': Parse.applicationId, 'X-Parse-REST-API-Key': 'rest', @@ -3629,9 +3524,7 @@ describe('Parse.User testing', () => { done(); }); }); - }).pend( - 'this test fails. See: https://github.com/parse-community/parse-server/issues/5097' - ); + }).pend('this test fails. See: https://github.com/parse-community/parse-server/issues/5097'); it('should be able to update user with authData passed', done => { let objectId; @@ -4033,44 +3926,35 @@ describe('Parse.User testing', () => { }); describe('issue #4897', () => { - it_only_db('mongo')( - 'should be able to login with a legacy user (no ACL)', - async () => { - // This issue is a side effect of the locked users and legacy users which don't have ACL's - // In this scenario, a legacy user wasn't be able to login as there's no ACL on it - const database = Config.get(Parse.applicationId).database; - const collection = await database.adapter._adaptiveCollection('_User'); - await collection.insertOne({ - _id: 'ABCDEF1234', - name: '', - email: '', - username: '', - _hashed_password: '', - _auth_data_facebook: { - id: '8675309', - access_token: 'jenny', - }, - sessionToken: '', - }); - const provider = getMockFacebookProvider(); - Parse.User._registerAuthenticationProvider(provider); - const model = await Parse.User._logInWith('facebook', {}); - expect(model.id).toBe('ABCDEF1234'); - ok(model instanceof Parse.User, 'Model should be a Parse.User'); - strictEqual(Parse.User.current(), model); - ok(model.extended(), 'Should have used subclass.'); - strictEqual(provider.authData.id, provider.synchronizedUserId); - strictEqual( - provider.authData.access_token, - provider.synchronizedAuthToken - ); - strictEqual( - provider.authData.expiration_date, - provider.synchronizedExpiration - ); - ok(model._isLinked('facebook'), 'User should be linked to facebook'); - } - ); + it_only_db('mongo')('should be able to login with a legacy user (no ACL)', async () => { + // This issue is a side effect of the locked users and legacy users which don't have ACL's + // In this scenario, a legacy user wasn't be able to login as there's no ACL on it + const database = Config.get(Parse.applicationId).database; + const collection = await database.adapter._adaptiveCollection('_User'); + await collection.insertOne({ + _id: 'ABCDEF1234', + name: '', + email: '', + username: '', + _hashed_password: '', + _auth_data_facebook: { + id: '8675309', + access_token: 'jenny', + }, + sessionToken: '', + }); + const provider = getMockFacebookProvider(); + Parse.User._registerAuthenticationProvider(provider); + const model = await Parse.User._logInWith('facebook', {}); + expect(model.id).toBe('ABCDEF1234'); + ok(model instanceof Parse.User, 'Model should be a Parse.User'); + strictEqual(Parse.User.current(), model); + ok(model.extended(), 'Should have used subclass.'); + strictEqual(provider.authData.id, provider.synchronizedUserId); + strictEqual(provider.authData.access_token, provider.synchronizedAuthToken); + strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); + ok(model._isLinked('facebook'), 'User should be linked to facebook'); + }); }); }); diff --git a/spec/ParseWebSocket.spec.js b/spec/ParseWebSocket.spec.js index ce540b9a..fe64bce1 100644 --- a/spec/ParseWebSocket.spec.js +++ b/spec/ParseWebSocket.spec.js @@ -1,15 +1,14 @@ -const ParseWebSocket = require('../lib/LiveQuery/ParseWebSocketServer') - .ParseWebSocket; +const ParseWebSocket = require('../lib/LiveQuery/ParseWebSocketServer').ParseWebSocket; -describe('ParseWebSocket', function() { - it('can be initialized', function() { +describe('ParseWebSocket', function () { + it('can be initialized', function () { const ws = {}; const parseWebSocket = new ParseWebSocket(ws); expect(parseWebSocket.ws).toBe(ws); }); - it('can handle disconnect event', function(done) { + it('can handle disconnect event', function (done) { const ws = { onclose: () => {}, }; @@ -20,7 +19,7 @@ describe('ParseWebSocket', function() { ws.onclose(); }); - it('can handle message event', function(done) { + it('can handle message event', function (done) { const ws = { onmessage: () => {}, }; @@ -31,7 +30,7 @@ describe('ParseWebSocket', function() { ws.onmessage(); }); - it('can send a message', function() { + it('can send a message', function () { const ws = { send: jasmine.createSpy('send'), }; diff --git a/spec/ParseWebSocketServer.spec.js b/spec/ParseWebSocketServer.spec.js index 7bf8a5c5..6050ea0f 100644 --- a/spec/ParseWebSocketServer.spec.js +++ b/spec/ParseWebSocketServer.spec.js @@ -1,28 +1,24 @@ -const { - ParseWebSocketServer, -} = require('../lib/LiveQuery/ParseWebSocketServer'); +const { ParseWebSocketServer } = require('../lib/LiveQuery/ParseWebSocketServer'); const EventEmitter = require('events'); -describe('ParseWebSocketServer', function() { - beforeEach(function(done) { +describe('ParseWebSocketServer', function () { + beforeEach(function (done) { // Mock ws server - const mockServer = function() { + const mockServer = function () { return new EventEmitter(); }; jasmine.mockLibrary('ws', 'Server', mockServer); done(); }); - it('can handle connect event when ws is open', function(done) { + it('can handle connect event when ws is open', function (done) { const onConnectCallback = jasmine.createSpy('onConnectCallback'); const http = require('http'); const server = http.createServer(); - const parseWebSocketServer = new ParseWebSocketServer( - server, - onConnectCallback, - { websocketTimeout: 5 } - ).server; + const parseWebSocketServer = new ParseWebSocketServer(server, onConnectCallback, { + websocketTimeout: 5, + }).server; const ws = new EventEmitter(); ws.readyState = 0; ws.OPEN = 0; @@ -33,7 +29,7 @@ describe('ParseWebSocketServer', function() { // Make sure callback is called expect(onConnectCallback).toHaveBeenCalled(); // Make sure we ping to the client - setTimeout(function() { + setTimeout(function () { expect(ws.ping).toHaveBeenCalled(); server.close(); done(); @@ -79,7 +75,7 @@ describe('ParseWebSocketServer', function() { expect(wssError).toBe('Invalid Packet'); }); - afterEach(function() { + afterEach(function () { jasmine.restoreLibrary('ws', 'Server'); }); }); diff --git a/spec/PasswordPolicy.spec.js b/spec/PasswordPolicy.spec.js index 6bc076af..79099226 100644 --- a/spec/PasswordPolicy.spec.js +++ b/spec/PasswordPolicy.spec.js @@ -131,15 +131,11 @@ describe('Password Policy: ', () => { publicServerURL: 'http://localhost:8378/1', }) .then(() => { - fail( - 'passwordPolicy.resetTokenValidityDuration "not a number" test failed' - ); + fail('passwordPolicy.resetTokenValidityDuration "not a number" test failed'); done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.resetTokenValidityDuration must be a positive number' - ); + expect(err).toEqual('passwordPolicy.resetTokenValidityDuration must be a positive number'); done(); }); }); @@ -157,9 +153,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.resetTokenValidityDuration must be a positive number' - ); + expect(err).toEqual('passwordPolicy.resetTokenValidityDuration must be a positive number'); done(); }); }); @@ -197,9 +191,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.validatorCallback must be a function.' - ); + expect(err).toEqual('passwordPolicy.validatorCallback must be a function.'); done(); }); }); @@ -219,9 +211,7 @@ describe('Password Policy: ', () => { user .signUp() .then(() => { - fail( - 'Should have failed as password does not conform to the policy.' - ); + fail('Should have failed as password does not conform to the policy.'); done(); }) .catch(error => { @@ -246,9 +236,7 @@ describe('Password Policy: ', () => { user .signUp() .then(() => { - fail( - 'Should have failed as password does not conform to the policy.' - ); + fail('Should have failed as password does not conform to the policy.'); done(); }) .catch(error => { @@ -273,15 +261,11 @@ describe('Password Policy: ', () => { user .signUp() .then(() => { - fail( - 'Should have failed as password does not conform to the policy.' - ); + fail('Should have failed as password does not conform to the policy.'); done(); }) .catch(error => { - expect(error.message).toEqual( - 'Cannot sign up user with an empty password.' - ); + expect(error.message).toEqual('Cannot sign up user with an empty password.'); done(); }); }); @@ -305,7 +289,7 @@ describe('Password Policy: ', () => { Parse.User.logOut() .then(() => { Parse.User.logIn('user1', '1digit') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -322,9 +306,7 @@ describe('Password Policy: ', () => { }) .catch(error => { jfail(error); - fail( - 'Signup should have succeeded as password conforms to the policy.' - ); + fail('Signup should have succeeded as password conforms to the policy.'); done(); }); }); @@ -348,7 +330,7 @@ describe('Password Policy: ', () => { Parse.User.logOut() .then(() => { Parse.User.logIn('user1', 'p@sswrod') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -365,9 +347,7 @@ describe('Password Policy: ', () => { }) .catch(error => { jfail(error); - fail( - 'Signup should have succeeded as password conforms to the policy.' - ); + fail('Signup should have succeeded as password conforms to the policy.'); done(); }); }); @@ -388,9 +368,7 @@ describe('Password Policy: ', () => { user .signUp() .then(() => { - fail( - 'Should have failed as password does not conform to the policy.' - ); + fail('Should have failed as password does not conform to the policy.'); done(); }) .catch(error => { @@ -418,7 +396,7 @@ describe('Password Policy: ', () => { Parse.User.logOut() .then(() => { Parse.User.logIn('user1', 'oneUpper') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -457,9 +435,7 @@ describe('Password Policy: ', () => { user .signUp() .then(() => { - fail( - 'Should have failed as password does not conform to the policy.' - ); + fail('Should have failed as password does not conform to the policy.'); done(); }) .catch(error => { @@ -485,9 +461,7 @@ describe('Password Policy: ', () => { user .signUp() .then(() => { - fail( - 'Should have failed as password does not conform to the policy.' - ); + fail('Should have failed as password does not conform to the policy.'); done(); }) .catch(error => { @@ -516,7 +490,7 @@ describe('Password Policy: ', () => { Parse.User.logOut() .then(() => { Parse.User.logIn('user1', 'oneUpper') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -579,7 +553,7 @@ describe('Password Policy: ', () => { ); Parse.User.logIn('user1', 'has2init') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -671,7 +645,7 @@ describe('Password Policy: ', () => { ); Parse.User.logIn('user1', 'has 1 digit') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -737,9 +711,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.doNotAllowUsername must be a boolean value.' - ); + expect(err).toEqual('passwordPolicy.doNotAllowUsername must be a boolean value.'); done(); }); }); @@ -765,9 +737,7 @@ describe('Password Policy: ', () => { }) .catch(error => { expect(error.code).toEqual(142); - expect(error.message).toEqual( - 'Password cannot contain your username.' - ); + expect(error.message).toEqual('Password cannot contain your username.'); done(); }); }); @@ -861,7 +831,7 @@ describe('Password Policy: ', () => { ); Parse.User.logIn('user1', 'r@nd0m') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -1012,7 +982,7 @@ describe('Password Policy: ', () => { ); Parse.User.logIn('user1', 'uuser11') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -1075,9 +1045,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.maxPasswordAge must be a positive number' - ); + expect(err).toEqual('passwordPolicy.maxPasswordAge must be a positive number'); done(); }); }); @@ -1095,9 +1063,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.maxPasswordAge must be a positive number' - ); + expect(err).toEqual('passwordPolicy.maxPasswordAge must be a positive number'); done(); }); }); @@ -1207,9 +1173,7 @@ describe('Password Policy: ', () => { done(); }) .catch(error => { - expect(error.code).toEqual( - Parse.Error.OBJECT_NOT_FOUND - ); + expect(error.code).toEqual(Parse.Error.OBJECT_NOT_FOUND); expect(error.message).toEqual( 'Your password has expired. Please reset your password.' ); @@ -1284,7 +1248,7 @@ describe('Password Policy: ', () => { ); Parse.User.logIn('user1', 'uuser11') - .then(function() { + .then(function () { done(); }) .catch(err => { @@ -1331,13 +1295,11 @@ describe('Password Policy: ', () => { expect(error.message).toEqual( 'Your password has expired. Please reset your password.' ); - Parse.User.requestPasswordReset('user1@parse.com').catch( - err => { - jfail(err); - fail('Reset password request should not fail'); - done(); - } - ); + Parse.User.requestPasswordReset('user1@parse.com').catch(err => { + jfail(err); + fail('Reset password request should not fail'); + done(); + }); }); }, 1000); }) @@ -1362,9 +1324,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.maxPasswordHistory must be an integer ranging 0 - 20' - ); + expect(err).toEqual('passwordPolicy.maxPasswordHistory must be an integer ranging 0 - 20'); done(); }); }); @@ -1382,9 +1342,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.maxPasswordHistory must be an integer ranging 0 - 20' - ); + expect(err).toEqual('passwordPolicy.maxPasswordHistory must be an integer ranging 0 - 20'); done(); }); }); @@ -1402,9 +1360,7 @@ describe('Password Policy: ', () => { done(); }) .catch(err => { - expect(err).toEqual( - 'passwordPolicy.maxPasswordHistory must be an integer ranging 0 - 20' - ); + expect(err).toEqual('passwordPolicy.maxPasswordHistory must be an integer ranging 0 - 20'); done(); }); }); @@ -1511,15 +1467,11 @@ describe('Password Policy: ', () => { return user.save(); }) .then(() => { - fail( - 'should have failed because the new password is same as the old' - ); + fail('should have failed because the new password is same as the old'); done(); }) .catch(error => { - expect(error.message).toEqual( - 'New password should not be the same as last 5 passwords.' - ); + expect(error.message).toEqual('New password should not be the same as last 5 passwords.'); expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); done(); }); @@ -1565,15 +1517,11 @@ describe('Password Policy: ', () => { return user.save(); }) .then(() => { - fail( - 'should have failed because the new password is same as the old' - ); + fail('should have failed because the new password is same as the old'); done(); }) .catch(error => { - expect(error.message).toEqual( - 'New password should not be the same as last 5 passwords.' - ); + expect(error.message).toEqual('New password should not be the same as last 5 passwords.'); expect(error.code).toEqual(Parse.Error.VALIDATION_ERROR); done(); }); @@ -1626,9 +1574,7 @@ describe('Password Policy: ', () => { done(); }) .catch(() => { - fail( - 'should have succeeded because the new password is not in history' - ); + fail('should have succeeded because the new password is not in history'); done(); }); }); @@ -1663,8 +1609,6 @@ describe('Password Policy: ', () => { const result2 = await query.get(user.id, { useMasterKey: true }); expect(result2.get('_password_history').length).toBe(1); - expect(result1.get('_password_history')).not.toEqual( - result2.get('_password_history') - ); + expect(result1.get('_password_history')).not.toEqual(result2.get('_password_history')); }); }); diff --git a/spec/PointerPermissions.spec.js b/spec/PointerPermissions.spec.js index a3a1b9f4..fa847749 100644 --- a/spec/PointerPermissions.spec.js +++ b/spec/PointerPermissions.spec.js @@ -30,11 +30,7 @@ describe('Pointer Permissions', () => { }) .then(() => { return config.database.loadSchema().then(schema => { - return schema.updateClass( - 'AnObject', - {}, - { readUserFields: ['owner'] } - ); + return schema.updateClass('AnObject', {}, { readUserFields: ['owner'] }); }); }) .then(() => { @@ -518,11 +514,7 @@ describe('Pointer Permissions', () => { .then(() => { return config.database.loadSchema().then(schema => { // Lock the update, and let only owner write - return schema.updateClass( - 'AnObject', - {}, - { update: {}, writeUserFields: ['owner'] } - ); + return schema.updateClass('AnObject', {}, { update: {}, writeUserFields: ['owner'] }); }); }) .then(() => { @@ -575,11 +567,7 @@ describe('Pointer Permissions', () => { .then(() => { return config.database.loadSchema().then(schema => { // Lock the update, and let only owner write - return schema.updateClass( - 'AnObject', - {}, - { update: {}, writeUserFields: ['owner'] } - ); + return schema.updateClass('AnObject', {}, { update: {}, writeUserFields: ['owner'] }); }); }) .then(() => { @@ -632,11 +620,7 @@ describe('Pointer Permissions', () => { .then(() => { return config.database.loadSchema().then(schema => { // Lock the update, and let only owner write - return schema.updateClass( - 'AnObject', - {}, - { update: {}, writeUserFields: ['owner'] } - ); + return schema.updateClass('AnObject', {}, { update: {}, writeUserFields: ['owner'] }); }); }) .then(() => { @@ -1185,11 +1169,7 @@ describe('Pointer Permissions', () => { await Parse.Object.saveAll([obj, obj2]); const schema = await config.database.loadSchema(); - await schema.updateClass( - 'AnObject', - {}, - { find: {}, get: {}, readUserFields: ['owners'] } - ); + await schema.updateClass('AnObject', {}, { find: {}, get: {}, readUserFields: ['owners'] }); let q = new Parse.Query('AnObject'); let result = await q.find(); @@ -1252,11 +1232,7 @@ describe('Pointer Permissions', () => { await Parse.Object.saveAll([obj, obj2]); const schema = await config.database.loadSchema(); - await schema.updateClass( - 'AnObject', - {}, - { find: {}, get: {}, readUserFields: ['owners'] } - ); + await schema.updateClass('AnObject', {}, { find: {}, get: {}, readUserFields: ['owners'] }); for (const owner of ['user1', 'user2']) { await Parse.User.logIn(owner, 'password'); @@ -1301,11 +1277,7 @@ describe('Pointer Permissions', () => { await Parse.Object.saveAll([obj, obj2]); const schema = await config.database.loadSchema(); - await schema.updateClass( - 'AnObject', - {}, - { find: {}, get: {}, readUserFields: ['owners'] } - ); + await schema.updateClass('AnObject', {}, { find: {}, get: {}, readUserFields: ['owners'] }); for (const owner of ['user1', 'user2']) { try { @@ -1561,11 +1533,7 @@ describe('Pointer Permissions', () => { const schema = await config.database.loadSchema(); // Lock the update, and let only owners write - await schema.updateClass( - 'AnObject', - {}, - { update: {}, writeUserFields: ['owners'] } - ); + await schema.updateClass('AnObject', {}, { update: {}, writeUserFields: ['owners'] }); await Parse.User.logIn('user1', 'password'); try { @@ -1614,11 +1582,7 @@ describe('Pointer Permissions', () => { const schema = await config.database.loadSchema(); // Lock the update, and let only owners write - await schema.updateClass( - 'AnObject', - {}, - { update: {}, writeUserFields: ['owners'] } - ); + await schema.updateClass('AnObject', {}, { update: {}, writeUserFields: ['owners'] }); for (const owner of ['user2', 'user3']) { await Parse.User.logIn(owner, 'password'); @@ -1668,11 +1632,7 @@ describe('Pointer Permissions', () => { const schema = await config.database.loadSchema(); // Lock the update, and let only owners write - await schema.updateClass( - 'AnObject', - {}, - { update: {}, writeUserFields: ['owners'] } - ); + await schema.updateClass('AnObject', {}, { update: {}, writeUserFields: ['owners'] }); for (const owner of ['user2', 'user3']) { await Parse.User.logIn(owner, 'password'); @@ -1724,11 +1684,7 @@ describe('Pointer Permissions', () => { const schema = await config.database.loadSchema(); // Lock reading, and let only owners read - await schema.updateClass( - 'AnObject', - {}, - { find: {}, get: {}, readUserFields: ['owners'] } - ); + await schema.updateClass('AnObject', {}, { find: {}, get: {}, readUserFields: ['owners'] }); await Parse.User.logIn('user1', 'password'); try { @@ -1942,10 +1898,7 @@ describe('Pointer Permissions', () => { } try { - const objectAgain = await object.save( - { hello: 'baz' }, - { useMasterKey: true } - ); + const objectAgain = await object.save({ hello: 'baz' }, { useMasterKey: true }); expect(objectAgain.get('hello')).toBe('baz'); done(); } catch (err) { @@ -2026,13 +1979,9 @@ describe('Pointer Permissions', () => { const actionDelete = obj => obj.destroy(); const actionAddFieldOnCreate = () => new Parse.Object(className, { ['extra' + Date.now()]: 'field' }).save(); - const actionAddFieldOnUpdate = obj => - obj.save({ ['another' + Date.now()]: 'field' }); + const actionAddFieldOnUpdate = obj => obj.save({ ['another' + Date.now()]: 'field' }); - const OBJECT_NOT_FOUND = new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); + const OBJECT_NOT_FOUND = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); const PERMISSION_DENIED = jasmine.stringMatching('Permission denied'); async function createUser(username, password = 'password') { @@ -2073,10 +2022,7 @@ describe('Pointer Permissions', () => { async function initialize() { await Config.get(Parse.applicationId).database.schemaCache.clear(); - [user1, user2] = await Promise.all([ - createUser('user1'), - createUser('user2'), - ]); + [user1, user2] = await Promise.all([createUser('user1'), createUser('user2')]); obj1 = new Parse.Object(className, { owner: user1, @@ -2121,9 +2067,7 @@ describe('Pointer Permissions', () => { await logIn(user2); - await expectAsync(actionGet(obj1.id)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionGet(obj1.id)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2283,9 +2227,7 @@ describe('Pointer Permissions', () => { await logIn(user2); - await expectAsync(actionUpdate(obj1)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionUpdate(obj1)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2337,9 +2279,7 @@ describe('Pointer Permissions', () => { await logIn(user2); - await expectAsync(actionDelete(obj1)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionDelete(obj1)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2418,9 +2358,7 @@ describe('Pointer Permissions', () => { owner: user1, extra: 'field', }); - await expectAsync(newObject.save()).toBeRejectedWith( - PERMISSION_DENIED - ); + await expectAsync(newObject.save()).toBeRejectedWith(PERMISSION_DENIED); done(); }); @@ -2453,9 +2391,7 @@ describe('Pointer Permissions', () => { await logIn(user2); - await expectAsync(actionAddFieldOnUpdate(obj1)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionAddFieldOnUpdate(obj1)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2590,9 +2526,7 @@ describe('Pointer Permissions', () => { await logIn(user1); - await expectAsync(actionGet(obj3.id)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionGet(obj3.id)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2773,9 +2707,7 @@ describe('Pointer Permissions', () => { await logIn(user2); - await expectAsync(actionUpdate(obj3)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionUpdate(obj3)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2841,9 +2773,7 @@ describe('Pointer Permissions', () => { await logIn(user1); - await expectAsync(actionDelete(obj3)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionDelete(obj3)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2923,9 +2853,7 @@ describe('Pointer Permissions', () => { moderators: user1, extra: 'field', }); - await expectAsync(newObject.save()).toBeRejectedWith( - PERMISSION_DENIED - ); + await expectAsync(newObject.save()).toBeRejectedWith(PERMISSION_DENIED); done(); }); @@ -2958,9 +2886,7 @@ describe('Pointer Permissions', () => { await logIn(user1); - await expectAsync(actionAddFieldOnUpdate(obj2)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionAddFieldOnUpdate(obj2)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); @@ -2995,10 +2921,7 @@ describe('Pointer Permissions', () => { async function initialize() { await Config.get(Parse.applicationId).database.schemaCache.clear(); - [user1, user2] = await Promise.all([ - createUser('user1'), - createUser('user2'), - ]); + [user1, user2] = await Promise.all([createUser('user1'), createUser('user2')]); // User1 owns object1 // User2 owns object2 @@ -3091,9 +3014,7 @@ describe('Pointer Permissions', () => { await logIn(user1); - await expectAsync(actionDelete(obj2)).toBeRejectedWith( - OBJECT_NOT_FOUND - ); + await expectAsync(actionDelete(obj2)).toBeRejectedWith(OBJECT_NOT_FOUND); done(); }); diff --git a/spec/PostgresConfigParser.spec.js b/spec/PostgresConfigParser.spec.js index d3b86b2c..412e7b20 100644 --- a/spec/PostgresConfigParser.spec.js +++ b/spec/PostgresConfigParser.spec.js @@ -60,9 +60,7 @@ dbOptionsTest[ dbOptionsTest[`${baseURI}?rejectUnauthorized=true`] = { ssl: { rejectUnauthorized: true }, }; -dbOptionsTest[ - `${baseURI}?max=5&query_timeout=100&idleTimeoutMillis=1000&keepAlive=true` -] = { +dbOptionsTest[`${baseURI}?max=5&query_timeout=100&idleTimeoutMillis=1000&keepAlive=true`] = { max: 5, query_timeout: 100, idleTimeoutMillis: 1000, diff --git a/spec/PostgresInitOptions.spec.js b/spec/PostgresInitOptions.spec.js index 31caf739..29962710 100644 --- a/spec/PostgresInitOptions.spec.js +++ b/spec/PostgresInitOptions.spec.js @@ -83,8 +83,6 @@ describe_only_db('postgres')('Postgres database init options', () => { databaseOptions: databaseOptions2, }); - createParseServer({ databaseAdapter: adapter }).then(done.fail, () => - done() - ); + createParseServer({ databaseAdapter: adapter }).then(done.fail, () => done()); }); }); diff --git a/spec/PostgresStorageAdapter.spec.js b/spec/PostgresStorageAdapter.spec.js index 8b02fecb..e51f2bb7 100644 --- a/spec/PostgresStorageAdapter.spec.js +++ b/spec/PostgresStorageAdapter.spec.js @@ -9,7 +9,7 @@ const getColumns = (client, className) => { return client.map( 'SELECT column_name FROM information_schema.columns WHERE table_name = $', { className }, - (a) => a.column_name + a => a.column_name ); }; @@ -25,7 +25,7 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { return adapter.deleteAllClasses(); }); - it('schemaUpgrade, upgrade the database schema when schema changes', (done) => { + it('schemaUpgrade, upgrade the database schema when schema changes', done => { const client = adapter._client; const className = '_PushStatus'; const schema = { @@ -39,7 +39,7 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { adapter .createTable(className, schema) .then(() => getColumns(client, className)) - .then((columns) => { + .then(columns => { expect(columns).toContain('pushTime'); expect(columns).toContain('source'); expect(columns).toContain('query'); @@ -49,17 +49,17 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { return adapter.schemaUpgrade(className, schema); }) .then(() => getColumns(client, className)) - .then((columns) => { + .then(columns => { expect(columns).toContain('pushTime'); expect(columns).toContain('source'); expect(columns).toContain('query'); expect(columns).toContain('expiration_interval'); done(); }) - .catch((error) => done.fail(error)); + .catch(error => done.fail(error)); }); - it('schemaUpgrade, maintain correct schema', (done) => { + it('schemaUpgrade, maintain correct schema', done => { const client = adapter._client; const className = 'Table'; const schema = { @@ -73,7 +73,7 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { adapter .createTable(className, schema) .then(() => getColumns(client, className)) - .then((columns) => { + .then(columns => { expect(columns).toContain('columnA'); expect(columns).toContain('columnB'); expect(columns).toContain('columnC'); @@ -81,7 +81,7 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { return adapter.schemaUpgrade(className, schema); }) .then(() => getColumns(client, className)) - .then((columns) => { + .then(columns => { expect(columns.length).toEqual(3); expect(columns).toContain('columnA'); expect(columns).toContain('columnB'); @@ -89,16 +89,16 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { done(); }) - .catch((error) => done.fail(error)); + .catch(error => done.fail(error)); }); - it('Create a table without columns and upgrade with columns', (done) => { + it('Create a table without columns and upgrade with columns', done => { const client = adapter._client; const className = 'EmptyTable'; dropTable(client, className) .then(() => adapter.createTable(className, {})) .then(() => getColumns(client, className)) - .then((columns) => { + .then(columns => { expect(columns.length).toBe(0); const newSchema = { @@ -111,7 +111,7 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { return adapter.schemaUpgrade(className, newSchema); }) .then(() => getColumns(client, className)) - .then((columns) => { + .then(columns => { expect(columns.length).toEqual(2); expect(columns).toContain('columnA'); expect(columns).toContain('columnB'); @@ -142,9 +142,7 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { }, }; await adapter.createClass('MyClass', schema); - await expectAsync(adapter.getClass('UnknownClass')).toBeRejectedWith( - undefined - ); + await expectAsync(adapter.getClass('UnknownClass')).toBeRejectedWith(undefined); }); it('should use index for caseInsensitive query using Postgres', async () => { @@ -158,93 +156,76 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { }; const client = adapter._client; await adapter.createTable(tableName, schema); - await client.none( - 'INSERT INTO $1:name ($2:name, $3:name) VALUES ($4, $5)', - [tableName, 'objectId', 'username', 'Bugs', 'Bunny'] - ); + await client.none('INSERT INTO $1:name ($2:name, $3:name) VALUES ($4, $5)', [ + tableName, + 'objectId', + 'username', + 'Bugs', + 'Bunny', + ]); //Postgres won't take advantage of the index until it has a lot of records because sequential is faster for small db's await client.none( 'INSERT INTO $1:name ($2:name, $3:name) SELECT MD5(random()::text), MD5(random()::text) FROM generate_series(1,5000)', [tableName, 'objectId', 'username'] ); const caseInsensitiveData = 'bugs'; - const originalQuery = - 'SELECT * FROM $1:name WHERE lower($2:name)=lower($3)'; - const analyzedExplainQuery = adapter.createExplainableQuery( - originalQuery, - true - ); + const originalQuery = 'SELECT * FROM $1:name WHERE lower($2:name)=lower($3)'; + const analyzedExplainQuery = adapter.createExplainableQuery(originalQuery, true); await client .one(analyzedExplainQuery, [tableName, 'objectId', caseInsensitiveData]) - .then((explained) => { + .then(explained => { const preIndexPlan = explained; - preIndexPlan['QUERY PLAN'].forEach((element) => { + preIndexPlan['QUERY PLAN'].forEach(element => { //Make sure search returned with only 1 result expect(element.Plan['Actual Rows']).toBe(1); expect(element.Plan['Node Type']).toBe('Seq Scan'); }); const indexName = 'test_case_insensitive_column'; - adapter - .ensureIndex(tableName, schema, ['objectId'], indexName, true) - .then(() => { - client - .one(analyzedExplainQuery, [ - tableName, - 'objectId', - caseInsensitiveData, - ]) - .then((explained) => { - const postIndexPlan = explained; + adapter.ensureIndex(tableName, schema, ['objectId'], indexName, true).then(() => { + client + .one(analyzedExplainQuery, [tableName, 'objectId', caseInsensitiveData]) + .then(explained => { + const postIndexPlan = explained; - postIndexPlan['QUERY PLAN'].forEach((element) => { - //Make sure search returned with only 1 result - expect(element.Plan['Actual Rows']).toBe(1); - //Should not be a sequential scan - expect(element.Plan['Node Type']).not.toContain('Seq Scan'); + postIndexPlan['QUERY PLAN'].forEach(element => { + //Make sure search returned with only 1 result + expect(element.Plan['Actual Rows']).toBe(1); + //Should not be a sequential scan + expect(element.Plan['Node Type']).not.toContain('Seq Scan'); - //Should be using the index created for this - element.Plan.Plans.forEach((innerElement) => { - expect(innerElement['Index Name']).toBe(indexName); + //Should be using the index created for this + element.Plan.Plans.forEach(innerElement => { + expect(innerElement['Index Name']).toBe(indexName); + }); + }); + + //These are the same query so should be the same size + for (let i = 0; i < preIndexPlan['QUERY PLAN'].length; i++) { + //Sequential should take more time to execute than indexed + expect(preIndexPlan['QUERY PLAN'][i]['Execution Time']).toBeGreaterThan( + postIndexPlan['QUERY PLAN'][i]['Execution Time'] + ); + } + + //Test explaining without analyzing + const basicExplainQuery = adapter.createExplainableQuery(originalQuery); + client + .one(basicExplainQuery, [tableName, 'objectId', caseInsensitiveData]) + .then(explained => { + explained['QUERY PLAN'].forEach(element => { + //Check that basic query plans isn't a sequential scan + expect(element.Plan['Node Type']).not.toContain('Seq Scan'); + + //Basic query plans shouldn't have an execution time + expect(element['Execution Time']).toBeUndefined(); }); }); - - //These are the same query so should be the same size - for (let i = 0; i < preIndexPlan['QUERY PLAN'].length; i++) { - //Sequential should take more time to execute than indexed - expect( - preIndexPlan['QUERY PLAN'][i]['Execution Time'] - ).toBeGreaterThan( - postIndexPlan['QUERY PLAN'][i]['Execution Time'] - ); - } - - //Test explaining without analyzing - const basicExplainQuery = adapter.createExplainableQuery( - originalQuery - ); - client - .one(basicExplainQuery, [ - tableName, - 'objectId', - caseInsensitiveData, - ]) - .then((explained) => { - explained['QUERY PLAN'].forEach((element) => { - //Check that basic query plans isn't a sequential scan - expect(element.Plan['Node Type']).not.toContain( - 'Seq Scan' - ); - - //Basic query plans shouldn't have an execution time - expect(element['Execution Time']).toBeUndefined(); - }); - }); - }); - }); + }); + }); }) - .catch((error) => { + .catch(error => { // Query on non existing table, don't crash if (error.code !== '42P01') { throw error; @@ -276,8 +257,8 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { { caseInsensitive: true, explain: true } ); - preIndexPlan.forEach((element) => { - element['QUERY PLAN'].forEach((innerElement) => { + preIndexPlan.forEach(element => { + element['QUERY PLAN'].forEach(innerElement => { //Check that basic query plans isn't a sequential scan, be careful as find uses "any" to query expect(innerElement.Plan['Node Type']).toBe('Seq Scan'); //Basic query plans shouldn't have an execution time @@ -287,13 +268,7 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { const indexName = 'test_case_insensitive_column'; const schema = await new Parse.Schema('_User').get(); - await adapter.ensureIndex( - tableName, - schema, - [fieldToSearch], - indexName, - true - ); + await adapter.ensureIndex(tableName, schema, [fieldToSearch], indexName, true); //Check using find method for Parse const postIndexPlan = await database.find( @@ -302,8 +277,8 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { { caseInsensitive: true, explain: true } ); - postIndexPlan.forEach((element) => { - element['QUERY PLAN'].forEach((innerElement) => { + postIndexPlan.forEach(element => { + element['QUERY PLAN'].forEach(innerElement => { //Check that basic query plans isn't a sequential scan expect(innerElement.Plan['Node Type']).not.toContain('Seq Scan'); @@ -339,8 +314,8 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { { username: caseInsensitiveData }, { caseInsensitive: true, explain: true } ); - indexPlan.forEach((element) => { - element['QUERY PLAN'].forEach((innerElement) => { + indexPlan.forEach(element => { + element['QUERY PLAN'].forEach(innerElement => { expect(innerElement.Plan['Node Type']).not.toContain('Seq Scan'); expect(innerElement.Plan['Index Name']).toContain('parse_default'); }); @@ -364,12 +339,8 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { const database = Config.get(Parse.applicationId).database; //Create index before data is inserted - await adapter.ensureUniqueness(firstTableName, firstTableSchema, [ - uniqueField, - ]); - await adapter.ensureUniqueness(secondTableName, secondTableSchema, [ - uniqueField, - ]); + await adapter.ensureUniqueness(firstTableName, firstTableSchema, [uniqueField]); + await adapter.ensureUniqueness(secondTableName, secondTableSchema, [uniqueField]); //Postgres won't take advantage of the index until it has a lot of records because sequential is faster for small db's const client = adapter._client; @@ -388,8 +359,8 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { { uuid: '1234' }, { caseInsensitive: false, explain: true } ); - indexPlan.forEach((element) => { - element['QUERY PLAN'].forEach((innerElement) => { + indexPlan.forEach(element => { + element['QUERY PLAN'].forEach(innerElement => { expect(innerElement.Plan['Node Type']).not.toContain('Seq Scan'); expect(innerElement.Plan['Index Name']).toContain(uniqueField); }); @@ -399,8 +370,8 @@ describe_only_db('postgres')('PostgresStorageAdapter', () => { { uuid: '1234' }, { caseInsensitive: false, explain: true } ); - indexPlan2.forEach((element) => { - element['QUERY PLAN'].forEach((innerElement) => { + indexPlan2.forEach(element => { + element['QUERY PLAN'].forEach(innerElement => { expect(innerElement.Plan['Node Type']).not.toContain('Seq Scan'); expect(innerElement.Plan['Index Name']).toContain(uniqueField); }); diff --git a/spec/ProtectedFields.spec.js b/spec/ProtectedFields.spec.js index fdc3c2d1..1bdc3177 100644 --- a/spec/ProtectedFields.spec.js +++ b/spec/ProtectedFields.spec.js @@ -1,16 +1,10 @@ const Config = require('../lib/Config'); const Parse = require('parse/node'); const request = require('../lib/request'); -const { - className, - createRole, - createUser, - logIn, - updateCLP, -} = require('./dev'); +const { className, createRole, createUser, logIn, updateCLP } = require('./dev'); -describe('ProtectedFields', function() { - it('should handle and empty protectedFields', async function() { +describe('ProtectedFields', function () { + it('should handle and empty protectedFields', async function () { const protectedFields = {}; await reconfigureServer({ protectedFields }); @@ -26,8 +20,8 @@ describe('ProtectedFields', function() { expect(fetched.has('favoriteColor')).toBeTruthy(); }); - describe('interaction with legacy userSensitiveFields', function() { - it('should fall back on sensitive fields if protected fields are not configured', async function() { + describe('interaction with legacy userSensitiveFields', function () { + it('should fall back on sensitive fields if protected fields are not configured', async function () { const userSensitiveFields = ['phoneNumber', 'timeZone']; const protectedFields = { _User: { '*': ['email'] } }; @@ -49,7 +43,7 @@ describe('ProtectedFields', function() { expect(fetched.has('favoriteColor')).toBeTruthy(); }); - it('should merge protected and sensitive for extra safety', async function() { + it('should merge protected and sensitive for extra safety', async function () { const userSensitiveFields = ['phoneNumber', 'timeZone']; const protectedFields = { _User: { '*': ['email', 'favoriteFood'] } }; @@ -73,23 +67,17 @@ describe('ProtectedFields', function() { }); }); - describe('non user class', function() { - it('should hide fields in a non user class', async function() { + describe('non user class', function () { + it('should hide fields in a non user class', async function () { const protectedFields = { ClassA: { '*': ['foo'] }, ClassB: { '*': ['bar'] }, }; await reconfigureServer({ protectedFields }); - const objA = await new Parse.Object('ClassA') - .set('foo', 'zzz') - .set('bar', 'yyy') - .save(); + const objA = await new Parse.Object('ClassA').set('foo', 'zzz').set('bar', 'yyy').save(); - const objB = await new Parse.Object('ClassB') - .set('foo', 'zzz') - .set('bar', 'yyy') - .save(); + const objB = await new Parse.Object('ClassB').set('foo', 'zzz').set('bar', 'yyy').save(); const [fetchedA, fetchedB] = await Promise.all([ new Parse.Query('ClassA').get(objA.id), @@ -103,7 +91,7 @@ describe('ProtectedFields', function() { expect(fetchedB.has('bar')).toBeFalsy(); }); - it('should hide fields in non user class and non standard user field at same time', async function() { + it('should hide fields in non user class and non standard user field at same time', async function () { const protectedFields = { _User: { '*': ['phoneNumber'] }, ClassA: { '*': ['foo'] }, @@ -122,15 +110,9 @@ describe('ProtectedFields', function() { user.set('favoriteFood', 'pizza'); await user.save(); - const objA = await new Parse.Object('ClassA') - .set('foo', 'zzz') - .set('bar', 'yyy') - .save(); + const objA = await new Parse.Object('ClassA').set('foo', 'zzz').set('bar', 'yyy').save(); - const objB = await new Parse.Object('ClassB') - .set('foo', 'zzz') - .set('bar', 'yyy') - .save(); + const objB = await new Parse.Object('ClassB').set('foo', 'zzz').set('bar', 'yyy').save(); const [fetchedUser, fetchedA, fetchedB] = await Promise.all([ new Parse.Query(Parse.User).get(user.id), @@ -823,10 +805,7 @@ describe('ProtectedFields', function() { }, }) ).toBeRejectedWith( - new Parse.Error( - Parse.Error.INVALID_JSON, - `Default field '${field}' can not be protected` - ) + new Parse.Error(Parse.Error.INVALID_JSON, `Default field '${field}' can not be protected`) ); } }); @@ -949,10 +928,7 @@ describe('ProtectedFields', function() { await Parse.User.logOut(); - [user1, user2] = await Promise.all([ - createUser('user1'), - createUser('user2'), - ]); + [user1, user2] = await Promise.all([createUser('user1'), createUser('user2')]); obj1 = new Parse.Object(className); obj2 = new Parse.Object(className); @@ -1151,10 +1127,7 @@ describe('ProtectedFields', function() { async function initialize() { await Config.get(Parse.applicationId).database.schemaCache.clear(); - [user1, user2] = await Promise.all([ - createUser('user1'), - createUser('user2'), - ]); + [user1, user2] = await Promise.all([createUser('user1'), createUser('user2')]); obj1 = new Parse.Object(className); obj2 = new Parse.Object(className); @@ -1244,10 +1217,7 @@ describe('ProtectedFields', function() { const object = await obj1.fetch(); - expect(object.get('test')).toBe( - undefined, - 'Field should not be visible - protected by role' - ); + expect(object.get('test')).toBe(undefined, 'Field should not be visible - protected by role'); expect(object.get('owner')).toBe( undefined, 'Field should not be visible - protected by role' @@ -1452,9 +1422,7 @@ describe('ProtectedFields', function() { expect(object.get('test')).toBeDefined( "Being both auhenticated and having a role leads to clearing protection on 'test' (by role rules)" ); - expect(object.get('owner')).toBeDefined( - 'All authenticated users allowed to see "owner"' - ); + expect(object.get('owner')).toBeDefined('All authenticated users allowed to see "owner"'); expect(object.get('testers')).toBeDefined(); done(); @@ -1588,10 +1556,7 @@ describe('ProtectedFields', function() { undefined, 'Should NOT be in response - protected by "userField:owner"' ); - expect(object.owner).toBe( - undefined, - 'Should not be in response - not included in "keys"' - ); + expect(object.owner).toBe(undefined, 'Should not be in response - not included in "keys"'); done(); }); @@ -1634,10 +1599,7 @@ describe('ProtectedFields', function() { undefined, 'Should not be in response - protected by "userField:owner"' ); - expect(object.owner).toBe( - undefined, - 'Should not be in response - not included in "keys"' - ); + expect(object.owner).toBe(undefined, 'Should not be in response - not included in "keys"'); done(); }); @@ -1667,10 +1629,7 @@ describe('ProtectedFields', function() { undefined, 'Should not be in response - protected by "userField:owner"' ); - expect(object['owner']).toBe( - undefined, - 'Should not be in response - not included in "keys"' - ); + expect(object['owner']).toBe(undefined, 'Should not be in response - not included in "keys"'); done(); }); @@ -1703,10 +1662,7 @@ describe('ProtectedFields', function() { undefined, 'Should not be in response - protected by "userField:owner"' ); - expect(object.owner).toBe( - undefined, - 'Should not be in response - not included in "keys"' - ); + expect(object.owner).toBe(undefined, 'Should not be in response - not included in "keys"'); done(); }); diff --git a/spec/PublicAPI.spec.js b/spec/PublicAPI.spec.js index 22c1383d..54566291 100644 --- a/spec/PublicAPI.spec.js +++ b/spec/PublicAPI.spec.js @@ -1,9 +1,12 @@ const req = require('../lib/request'); -const request = function(url, callback) { +const request = function (url, callback) { return req({ url, - }).then(response => callback(null, response), err => callback(err, err)); + }).then( + response => callback(null, response), + err => callback(err, err) + ); }; describe('public API', () => { @@ -74,13 +77,10 @@ describe('public API', () => { }); it('should get invalid_link.html', done => { - request( - 'http://localhost:8378/1/apps/invalid_link.html', - (err, httpResponse) => { - expect(httpResponse.status).toBe(200); - done(); - } - ); + request('http://localhost:8378/1/apps/invalid_link.html', (err, httpResponse) => { + expect(httpResponse.status).toBe(200); + done(); + }); }); it('should get choose_password', done => { @@ -88,34 +88,25 @@ describe('public API', () => { appName: 'unused', publicServerURL: 'http://localhost:8378/1', }).then(() => { - request( - 'http://localhost:8378/1/apps/choose_password?id=test', - (err, httpResponse) => { - expect(httpResponse.status).toBe(200); - done(); - } - ); + request('http://localhost:8378/1/apps/choose_password?id=test', (err, httpResponse) => { + expect(httpResponse.status).toBe(200); + done(); + }); }); }); it('should get verify_email_success.html', done => { - request( - 'http://localhost:8378/1/apps/verify_email_success.html', - (err, httpResponse) => { - expect(httpResponse.status).toBe(200); - done(); - } - ); + request('http://localhost:8378/1/apps/verify_email_success.html', (err, httpResponse) => { + expect(httpResponse.status).toBe(200); + done(); + }); }); it('should get password_reset_success.html', done => { - request( - 'http://localhost:8378/1/apps/password_reset_success.html', - (err, httpResponse) => { - expect(httpResponse.status).toBe(200); - done(); - } - ); + request('http://localhost:8378/1/apps/password_reset_success.html', (err, httpResponse) => { + expect(httpResponse.status).toBe(200); + done(); + }); }); }); @@ -124,33 +115,24 @@ describe('public API without publicServerURL', () => { reconfigureServer({ appName: 'unused' }).then(done, fail); }); it('should get 404 on verify_email', done => { - request( - 'http://localhost:8378/1/apps/test/verify_email', - (err, httpResponse) => { - expect(httpResponse.status).toBe(404); - done(); - } - ); + request('http://localhost:8378/1/apps/test/verify_email', (err, httpResponse) => { + expect(httpResponse.status).toBe(404); + done(); + }); }); it('should get 404 choose_password', done => { - request( - 'http://localhost:8378/1/apps/choose_password?id=test', - (err, httpResponse) => { - expect(httpResponse.status).toBe(404); - done(); - } - ); + request('http://localhost:8378/1/apps/choose_password?id=test', (err, httpResponse) => { + expect(httpResponse.status).toBe(404); + done(); + }); }); it('should get 404 on request_password_reset', done => { - request( - 'http://localhost:8378/1/apps/test/request_password_reset', - (err, httpResponse) => { - expect(httpResponse.status).toBe(404); - done(); - } - ); + request('http://localhost:8378/1/apps/test/request_password_reset', (err, httpResponse) => { + expect(httpResponse.status).toBe(404); + done(); + }); }); }); @@ -160,33 +142,24 @@ describe('public API supplied with invalid application id', () => { }); it('should get 403 on verify_email', done => { - request( - 'http://localhost:8378/1/apps/invalid/verify_email', - (err, httpResponse) => { - expect(httpResponse.status).toBe(403); - done(); - } - ); + request('http://localhost:8378/1/apps/invalid/verify_email', (err, httpResponse) => { + expect(httpResponse.status).toBe(403); + done(); + }); }); it('should get 403 choose_password', done => { - request( - 'http://localhost:8378/1/apps/choose_password?id=invalid', - (err, httpResponse) => { - expect(httpResponse.status).toBe(403); - done(); - } - ); + request('http://localhost:8378/1/apps/choose_password?id=invalid', (err, httpResponse) => { + expect(httpResponse.status).toBe(403); + done(); + }); }); it('should get 403 on get of request_password_reset', done => { - request( - 'http://localhost:8378/1/apps/invalid/request_password_reset', - (err, httpResponse) => { - expect(httpResponse.status).toBe(403); - done(); - } - ); + request('http://localhost:8378/1/apps/invalid/request_password_reset', (err, httpResponse) => { + expect(httpResponse.status).toBe(403); + done(); + }); }); it('should get 403 on post of request_password_reset', done => { diff --git a/spec/PurchaseValidation.spec.js b/spec/PurchaseValidation.spec.js index f3cf64eb..f139b1fd 100644 --- a/spec/PurchaseValidation.spec.js +++ b/spec/PurchaseValidation.spec.js @@ -8,7 +8,7 @@ function createProduct() { }, 'text' ); - return file.save().then(function() { + return file.save().then(function () { const product = new Parse.Object('_Product'); product.set({ download: file, @@ -26,7 +26,7 @@ describe('test validate_receipt endpoint', () => { beforeEach(done => { createProduct() .then(done) - .catch(function(err) { + .catch(function (err) { console.error({ err }); done(); }); @@ -151,20 +151,18 @@ describe('test validate_receipt endpoint', () => { fail('Body is not an object'); } else { expect(body.status).toBe(21002); - expect(body.error).toBe( - 'The data in the receipt-data property was malformed or missing.' - ); + expect(body.error).toBe('The data in the receipt-data property was malformed or missing.'); } }); it('should not create a _Product', done => { const product = new Parse.Object('_Product'); product.save().then( - function() { + function () { fail('Should not be able to save'); done(); }, - function(err) { + function (err) { expect(err.code).toEqual(Parse.Error.INCORRECT_TYPE); done(); } @@ -175,21 +173,19 @@ describe('test validate_receipt endpoint', () => { const query = new Parse.Query('_Product'); query .first() - .then(function(product) { + .then(function (product) { if (!product) { return Promise.reject(new Error('Product should be found')); } product.set('title', 'a new title'); return product.save(); }) - .then(function(productAgain) { - expect(productAgain.get('downloadName')).toEqual( - productAgain.get('download').name() - ); + .then(function (productAgain) { + expect(productAgain.get('downloadName')).toEqual(productAgain.get('download').name()); expect(productAgain.get('title')).toEqual('a new title'); done(); }) - .catch(function(err) { + .catch(function (err) { fail(JSON.stringify(err)); done(); }); @@ -199,18 +195,18 @@ describe('test validate_receipt endpoint', () => { const query = new Parse.Query('_Product'); query .first() - .then(function(product) { + .then(function (product) { if (!product) { return Promise.reject(new Error('Product should be found')); } product.unset('title'); return product.save(); }) - .then(function() { + .then(function () { fail('Should not succeed'); done(); }) - .catch(function(err) { + .catch(function (err) { expect(err.code).toEqual(Parse.Error.INCORRECT_TYPE); expect(err.message).toEqual('title is required.'); done(); diff --git a/spec/PushController.spec.js b/spec/PushController.spec.js index abed0577..2468ab21 100644 --- a/spec/PushController.spec.js +++ b/spec/PushController.spec.js @@ -1,11 +1,10 @@ 'use strict'; -const PushController = require('../lib/Controllers/PushController') - .PushController; +const PushController = require('../lib/Controllers/PushController').PushController; const StatusHandler = require('../lib/StatusHandler'); const Config = require('../lib/Config'); const validatePushType = require('../lib/Push/utils').validatePushType; -const successfulTransmissions = function(body, installations) { +const successfulTransmissions = function (body, installations) { const promises = installations.map(device => { return Promise.resolve({ transmitted: true, @@ -16,7 +15,7 @@ const successfulTransmissions = function(body, installations) { return Promise.all(promises); }; -const successfulIOS = function(body, installations) { +const successfulIOS = function (body, installations) { const promises = installations.map(device => { return Promise.resolve({ transmitted: device.deviceType == 'ios', @@ -33,7 +32,7 @@ describe('PushController', () => { const where = {}; const validPushTypes = ['ios', 'android']; - expect(function() { + expect(function () { validatePushType(where, validPushTypes); }).not.toThrow(); done(); @@ -46,7 +45,7 @@ describe('PushController', () => { }; const validPushTypes = ['ios', 'android']; - expect(function() { + expect(function () { validatePushType(where, validPushTypes); }).not.toThrow(); done(); @@ -61,7 +60,7 @@ describe('PushController', () => { }; const validPushTypes = ['ios', 'android']; - expect(function() { + expect(function () { validatePushType(where, validPushTypes); }).not.toThrow(); done(); @@ -74,7 +73,7 @@ describe('PushController', () => { }; const validPushTypes = ['ios', 'android']; - expect(function() { + expect(function () { validatePushType(where, validPushTypes); }).toThrow(); done(); @@ -87,7 +86,7 @@ describe('PushController', () => { }; const validPushTypes = ['ios', 'android']; - expect(function() { + expect(function () { validatePushType(where, validPushTypes); }).toThrow(); done(); @@ -123,7 +122,7 @@ describe('PushController', () => { expiration_time: 'abcd', }; - expect(function() { + expect(function () { PushController.getExpirationTime(body); }).toThrow(); done(); @@ -159,7 +158,7 @@ describe('PushController', () => { push_time: 'abcd', }; - expect(function() { + expect(function () { PushController.getPushTime(body); }).toThrow(); done(); @@ -167,7 +166,7 @@ describe('PushController', () => { it('properly increment badges', done => { const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { const badge = body.data.badge; installations.forEach(installation => { expect(installation.badge).toEqual(badge); @@ -175,7 +174,7 @@ describe('PushController', () => { }); return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios', 'android']; }, }; @@ -188,10 +187,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 10) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -201,10 +197,7 @@ describe('PushController', () => { while (installations.length != 15) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -253,9 +246,7 @@ describe('PushController', () => { expect(results.length).toBe(15); for (let i = 0; i < 15; i++) { const installation = results[i]; - expect(installation.get('badge')).toBe( - parseInt(installation.get('originalBadge')) + 1 - ); + expect(installation.get('badge')).toBe(parseInt(installation.get('originalBadge')) + 1); } done(); }) @@ -267,7 +258,7 @@ describe('PushController', () => { it('properly increment badges by more than 1', done => { const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { const badge = body.data.badge; installations.forEach(installation => { expect(installation.badge).toEqual(badge); @@ -275,7 +266,7 @@ describe('PushController', () => { }); return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios', 'android']; }, }; @@ -288,10 +279,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 10) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -301,10 +289,7 @@ describe('PushController', () => { while (installations.length != 15) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -353,9 +338,7 @@ describe('PushController', () => { expect(results.length).toBe(15); for (let i = 0; i < 15; i++) { const installation = results[i]; - expect(installation.get('badge')).toBe( - parseInt(installation.get('originalBadge')) + 3 - ); + expect(installation.get('badge')).toBe(parseInt(installation.get('originalBadge')) + 3); } done(); }) @@ -367,7 +350,7 @@ describe('PushController', () => { it('properly set badges to 1', done => { const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { const badge = body.data.badge; installations.forEach(installation => { expect(installation.badge).toEqual(badge); @@ -375,7 +358,7 @@ describe('PushController', () => { }); return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -389,10 +372,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 10) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -462,10 +442,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 10) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -474,7 +451,7 @@ describe('PushController', () => { } let matchedInstallationsCount = 0; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { matchedInstallationsCount += installations.length; const badge = body.data.badge; installations.forEach(installation => { @@ -483,7 +460,7 @@ describe('PushController', () => { }); return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -533,17 +510,14 @@ describe('PushController', () => { it('properly creates _PushStatus', done => { const pushStatusAfterSave = { - handler: function() {}, + handler: function () {}, }; const spy = spyOn(pushStatusAfterSave, 'handler').and.callThrough(); Parse.Cloud.afterSave('_PushStatus', pushStatusAfterSave.handler); const installations = []; while (installations.length != 10) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -553,10 +527,7 @@ describe('PushController', () => { while (installations.length != 15) { 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('deviceType', 'android'); installations.push(installation); @@ -569,10 +540,10 @@ describe('PushController', () => { }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return successfulIOS(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -663,7 +634,7 @@ describe('PushController', () => { it('properly creates _PushStatus without serverURL', done => { const pushStatusAfterSave = { - handler: function() {}, + handler: function () {}, }; Parse.Cloud.afterSave('_PushStatus', pushStatusAfterSave.handler); const installation = new Parse.Object('_Installation'); @@ -681,10 +652,10 @@ describe('PushController', () => { }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return successfulIOS(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -727,14 +698,14 @@ describe('PushController', () => { it('should properly report failures in _PushStatus', done => { const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return installations.map(installation => { return Promise.resolve({ deviceType: installation.deviceType, }); }); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -784,10 +755,10 @@ describe('PushController', () => { }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -810,14 +781,8 @@ describe('PushController', () => { const installations = []; while (installations.length != 5) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); - installation.set( - 'deviceToken', - 'device_token_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); + installation.set('deviceToken', 'device_token_' + installations.length); installation.set('badge', installations.length); installation.set('originalBadge', installations.length); installation.set('deviceType', 'ios'); @@ -862,10 +827,10 @@ describe('PushController', () => { }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -887,14 +852,8 @@ describe('PushController', () => { const installations = []; while (installations.length != 5) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); - installation.set( - 'deviceToken', - 'device_token_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); + installation.set('deviceToken', 'device_token_' + installations.length); installation.set('badge', installations.length); installation.set('originalBadge', installations.length); installation.set('deviceType', 'ios'); @@ -990,10 +949,10 @@ describe('PushController', () => { isMaster: true, }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -1009,10 +968,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 10) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -1051,7 +1007,7 @@ describe('PushController', () => { isMaster: true, }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { const promises = installations.map(device => { if (!device.deviceToken) { // Simulate error when device token is not set @@ -1065,7 +1021,7 @@ describe('PushController', () => { return Promise.all(promises); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -1081,10 +1037,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 10) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -1121,7 +1074,7 @@ describe('PushController', () => { isMaster: true, }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { const promises = installations.map(device => { if (!device.deviceToken) { // Simulate error when device token is not set @@ -1135,7 +1088,7 @@ describe('PushController', () => { return Promise.all(promises); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -1151,10 +1104,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 5) { 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('badge', installations.length); installation.set('originalBadge', installations.length); @@ -1164,10 +1114,7 @@ describe('PushController', () => { while (installations.length != 15) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); installation.set('badge', installations.length); installation.set('originalBadge', installations.length); installation.set('deviceType', 'ios'); @@ -1207,7 +1154,7 @@ describe('PushController', () => { isMaster: true, }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { const promises = installations.map(device => { if (!device.deviceToken) { // Simulate error when device token is not set @@ -1221,7 +1168,7 @@ describe('PushController', () => { return Promise.all(promises); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -1237,10 +1184,7 @@ describe('PushController', () => { const installations = []; while (installations.length != 5) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); installation.set('badge', installations.length); installation.set('originalBadge', installations.length); installation.set('deviceType', 'ios'); @@ -1285,10 +1229,10 @@ describe('PushController', () => { }; const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -1310,14 +1254,8 @@ describe('PushController', () => { const installations = []; while (installations.length != 5) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); - installation.set( - 'deviceToken', - 'device_token_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); + installation.set('deviceToken', 'device_token_' + installations.length); installation.set('badge', installations.length); installation.set('originalBadge', installations.length); installation.set('deviceType', 'ios'); @@ -1360,10 +1298,10 @@ describe('PushController', () => { it('should update audiences', done => { const pushAdapter = { - send: function(body, installations) { + send: function (body, installations) { return successfulTransmissions(body, installations); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios']; }, }; @@ -1389,14 +1327,8 @@ describe('PushController', () => { const installations = []; while (installations.length != 5) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); - installation.set( - 'deviceToken', - 'device_token_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); + installation.set('deviceToken', 'device_token_' + installations.length); installation.set('badge', installations.length); installation.set('originalBadge', installations.length); installation.set('deviceType', 'ios'); @@ -1468,25 +1400,24 @@ describe('PushController', () => { describe('pushTimeHasTimezoneComponent', () => { it('should be accurate', () => { - expect( - PushController.pushTimeHasTimezoneComponent('2017-09-06T17:14:01.048Z') - ).toBe(true, 'UTC time'); - expect( - PushController.pushTimeHasTimezoneComponent('2007-04-05T12:30-02:00') - ).toBe(true, 'Timezone offset'); - expect( - PushController.pushTimeHasTimezoneComponent( - '2007-04-05T12:30:00.000Z-02:00' - ) - ).toBe(true, 'Seconds + Milliseconds + Timezone offset'); - - expect( - PushController.pushTimeHasTimezoneComponent('2017-09-06T17:14:01.048') - ).toBe(false, 'No timezone'); - expect(PushController.pushTimeHasTimezoneComponent('2017-09-06')).toBe( - false, - 'YY-MM-DD' + expect(PushController.pushTimeHasTimezoneComponent('2017-09-06T17:14:01.048Z')).toBe( + true, + 'UTC time' ); + expect(PushController.pushTimeHasTimezoneComponent('2007-04-05T12:30-02:00')).toBe( + true, + 'Timezone offset' + ); + expect(PushController.pushTimeHasTimezoneComponent('2007-04-05T12:30:00.000Z-02:00')).toBe( + true, + 'Seconds + Milliseconds + Timezone offset' + ); + + expect(PushController.pushTimeHasTimezoneComponent('2017-09-06T17:14:01.048')).toBe( + false, + 'No timezone' + ); + expect(PushController.pushTimeHasTimezoneComponent('2017-09-06')).toBe(false, 'YY-MM-DD'); }); }); @@ -1517,10 +1448,7 @@ describe('PushController', () => { date: noTimezone, isLocalTime: true, }) - ).toBe( - `2017-09-${day}T${expectedHour.toString().padStart(2, '0')}:14:01.048`, - 'No timezone' - ); + ).toBe(`2017-09-${day}T${expectedHour.toString().padStart(2, '0')}:14:01.048`, 'No timezone'); expect( PushController.formatPushTime({ date: new Date('2017-09-06'), @@ -1582,9 +1510,7 @@ describe('PushController', () => { .then(pushStatus => { expect(pushStatus.get('status')).toBe('scheduled'); expect(pushStatus.get('pushTime')).toBe( - `2017-09-${day}T${expectedHour - .toString() - .padStart(2, '0')}:14:01.048` + `2017-09-${day}T${expectedHour.toString().padStart(2, '0')}:14:01.048` ); }) .then(done, done.fail); diff --git a/spec/PushQueue.spec.js b/spec/PushQueue.spec.js index 8cf42e81..db851ba2 100644 --- a/spec/PushQueue.spec.js +++ b/spec/PushQueue.spec.js @@ -22,10 +22,7 @@ describe('PushQueue', () => { }) .then(() => { const config = Config.get(Parse.applicationId); - expect(config.pushWorker.channel).toEqual( - 'my-specific-channel', - 'pushWorker.channel' - ); + expect(config.pushWorker.channel).toEqual('my-specific-channel', 'pushWorker.channel'); expect(config.pushControllerQueue.channel).toEqual( 'my-specific-channel', 'pushWorker.channel' @@ -54,13 +51,9 @@ describe('PushQueue', () => { }) .then(() => { const config = Config.get(Parse.applicationId); - expect(PushQueue.defaultPushChannel()).toEqual( - 'test-parse-server-push' - ); + expect(PushQueue.defaultPushChannel()).toEqual('test-parse-server-push'); expect(config.pushWorker.channel).toEqual('test-parse-server-push'); - expect(config.pushControllerQueue.channel).toEqual( - 'test-parse-server-push' - ); + expect(config.pushControllerQueue.channel).toEqual('test-parse-server-push'); }) .then(done, done.fail); }); diff --git a/spec/PushRouter.spec.js b/spec/PushRouter.spec.js index 38872922..99ff17d2 100644 --- a/spec/PushRouter.spec.js +++ b/spec/PushRouter.spec.js @@ -42,7 +42,7 @@ describe('PushRouter', () => { body: {}, }; - expect(function() { + expect(function () { PushRouter.getQueryCondition(request); }).toThrow(); done(); @@ -61,7 +61,7 @@ describe('PushRouter', () => { }, }; - expect(function() { + expect(function () { PushRouter.getQueryCondition(request); }).toThrow(); done(); diff --git a/spec/PushWorker.spec.js b/spec/PushWorker.spec.js index 8dc1068e..6f985209 100644 --- a/spec/PushWorker.spec.js +++ b/spec/PushWorker.spec.js @@ -24,21 +24,15 @@ describe('PushWorker', () => { sendCount += installations.length; return Promise.resolve(); }, - getValidPushTypes: function() { + getValidPushTypes: function () { return ['ios', 'android']; }, }); const installations = []; while (installations.length != 10) { const installation = new Parse.Object('_Installation'); - installation.set( - 'installationId', - 'installation_' + installations.length - ); - installation.set( - 'deviceToken', - 'device_token_' + installations.length - ); + installation.set('installationId', 'installation_' + installations.length); + installation.set('deviceToken', 'device_token_' + installations.length); installation.set('badge', 1); installation.set('deviceType', 'ios'); installations.push(installation); diff --git a/spec/QueryTools.spec.js b/spec/QueryTools.spec.js index 8f6f6c71..24e3f648 100644 --- a/spec/QueryTools.spec.js +++ b/spec/QueryTools.spec.js @@ -7,8 +7,8 @@ const matchesQuery = QueryTools.matchesQuery; const Item = Parse.Object.extend('Item'); -describe('queryHash', function() { - it('should always hash a query to the same string', function() { +describe('queryHash', function () { + it('should always hash a query to the same string', function () { const q = new Parse.Query(Item); q.equalTo('field', 'value'); q.exists('name'); @@ -19,7 +19,7 @@ describe('queryHash', function() { expect(firstHash).toBe(secondHash); }); - it('should return equivalent hashes for equivalent queries', function() { + it('should return equivalent hashes for equivalent queries', function () { let q1 = new Parse.Query(Item); q1.equalTo('field', 'value'); q1.exists('name'); @@ -68,7 +68,7 @@ describe('queryHash', function() { expect(firstHash).toBe(secondHash); }); - it('should not let fields of different types appear similar', function() { + it('should not let fields of different types appear similar', function () { let q1 = new Parse.Query(Item); q1.lessThan('age', 30); @@ -86,8 +86,8 @@ describe('queryHash', function() { }); }); -describe('matchesQuery', function() { - it('matches blanket queries', function() { +describe('matchesQuery', function () { + it('matches blanket queries', function () { const obj = { id: new Id('Klass', 'O1'), value: 12, @@ -99,7 +99,7 @@ describe('matchesQuery', function() { expect(matchesQuery(obj, q)).toBe(false); }); - it('matches existence queries', function() { + it('matches existence queries', function () { const obj = { id: new Id('Item', 'O1'), count: 15, @@ -111,7 +111,7 @@ describe('matchesQuery', function() { expect(matchesQuery(obj, q)).toBe(false); }); - it('matches queries with doesNotExist constraint', function() { + it('matches queries with doesNotExist constraint', function () { const obj = { id: new Id('Item', 'O1'), count: 15, @@ -125,7 +125,7 @@ describe('matchesQuery', function() { expect(matchesQuery(obj, q)).toBe(false); }); - it('matches on equality queries', function() { + it('matches on equality queries', function () { const day = new Date(); const location = new Parse.GeoPoint({ latitude: 37.484815, @@ -255,7 +255,7 @@ describe('matchesQuery', function() { expect(matchesQuery(img, q)).toBe(false); }); - it('matches on inequalities', function() { + it('matches on inequalities', function () { const player = { id: new Id('Person', 'O1'), score: 12, @@ -297,7 +297,7 @@ describe('matchesQuery', function() { expect(matchesQuery(player, q)).toBe(true); }); - it('matches an $or query', function() { + it('matches an $or query', function () { const player = { id: new Id('Player', 'P1'), name: 'Player 1', @@ -313,7 +313,7 @@ describe('matchesQuery', function() { expect(matchesQuery(player, orQuery)).toBe(true); }); - it('matches $regex queries', function() { + it('matches $regex queries', function () { const player = { id: new Id('Player', 'P1'), name: 'Player 1', @@ -362,7 +362,7 @@ describe('matchesQuery', function() { expect(matchesQuery(player, q)).toBe(false); }); - it('matches $nearSphere queries', function() { + it('matches $nearSphere queries', function () { let q = new Parse.Query('Checkin'); q.near('location', new Parse.GeoPoint(20, 20)); // With no max distance, any GeoPoint is 'near' @@ -390,7 +390,7 @@ describe('matchesQuery', function() { expect(matchesQuery(pt, q)).toBe(false); }); - it('matches $within queries', function() { + it('matches $within queries', function () { const caltrainStation = { id: new Id('Checkin', 'C1'), location: new Parse.GeoPoint(37.776346, -122.394218), @@ -444,7 +444,7 @@ describe('matchesQuery', function() { expect(matchesQuery(santaClara, q)).toBe(false); }); - it('matches on subobjects with dot notation', function() { + it('matches on subobjects with dot notation', function () { const message = { id: new Id('Message', 'O1'), text: 'content', diff --git a/spec/ReadPreferenceOption.spec.js b/spec/ReadPreferenceOption.spec.js index 20f9c0cf..4328201f 100644 --- a/spec/ReadPreferenceOption.spec.js +++ b/spec/ReadPreferenceOption.spec.js @@ -16,10 +16,7 @@ describe_only_db('mongo')('Read preference option', () => { Parse.Object.saveAll([obj0, obj1]) .then(() => { - spyOn( - databaseAdapter.database.serverConfig, - 'cursor' - ).and.callThrough(); + spyOn(databaseAdapter.database.serverConfig, 'cursor').and.callThrough(); const query = new Parse.Query('MyObject'); query.equalTo('boolKey', false); @@ -28,16 +25,12 @@ describe_only_db('mongo')('Read preference option', () => { expect(results.length).toBe(1); expect(results[0].get('boolKey')).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.PRIMARY - ); - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = true; + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.PRIMARY); + } + }); expect(myObjectReadPreference).toBe(true); @@ -48,9 +41,7 @@ describe_only_db('mongo')('Read preference option', () => { }); it('should preserve the read preference set (#4831)', async () => { - const { - MongoStorageAdapter, - } = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter'); + const { MongoStorageAdapter } = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter'); const adapterOptions = { uri: 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase', mongoOptions: { @@ -82,9 +73,7 @@ describe_only_db('mongo')('Read preference option', () => { databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { myObjectReadPreference = true; - expect(call.args[0].options.readPreference.mode).toBe( - ReadPreference.NEAREST - ); + expect(call.args[0].options.readPreference.mode).toBe(ReadPreference.NEAREST); } }); @@ -116,14 +105,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -158,14 +144,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -201,14 +184,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(true); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -247,14 +227,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(true); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -293,14 +270,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(true); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -335,18 +309,13 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); - expect(myObjectReadPreference).toEqual( - ReadPreference.PRIMARY_PREFERRED - ); + expect(myObjectReadPreference).toEqual(ReadPreference.PRIMARY_PREFERRED); done(); }) @@ -379,18 +348,13 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); - expect(myObjectReadPreference).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -423,14 +387,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(results[0].get('boolKey')).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.NEAREST); @@ -463,14 +424,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(result.get('boolKey')).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -509,14 +467,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(body.boolKey).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -539,10 +494,7 @@ describe_only_db('mongo')('Read preference option', () => { request({ method: 'GET', - url: - 'http://localhost:8378/1/classes/MyObject/' + - obj0.id + - '?readPreference=SECONDARY', + url: 'http://localhost:8378/1/classes/MyObject/' + obj0.id + '?readPreference=SECONDARY', headers: { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -553,14 +505,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(response.data.boolKey).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -587,10 +536,7 @@ describe_only_db('mongo')('Read preference option', () => { request({ method: 'GET', - url: - 'http://localhost:8378/1/classes/MyObject/' + - obj0.id + - '?readPreference=SECONDARY', + url: 'http://localhost:8378/1/classes/MyObject/' + obj0.id + '?readPreference=SECONDARY', headers: { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -601,18 +547,13 @@ describe_only_db('mongo')('Read preference option', () => { expect(response.data.boolKey).toBe(false); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); - expect(myObjectReadPreference).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -648,14 +589,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(response.data.results.length).toEqual(2); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -678,8 +616,7 @@ describe_only_db('mongo')('Read preference option', () => { request({ method: 'GET', - url: - 'http://localhost:8378/1/classes/MyObject?readPreference=SECONDARY', + url: 'http://localhost:8378/1/classes/MyObject?readPreference=SECONDARY', headers: { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -690,14 +627,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(response.data.results.length).toEqual(2); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -724,8 +658,7 @@ describe_only_db('mongo')('Read preference option', () => { request({ method: 'GET', - url: - 'http://localhost:8378/1/classes/MyObject/?readPreference=SECONDARY', + url: 'http://localhost:8378/1/classes/MyObject/?readPreference=SECONDARY', headers: { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', @@ -736,18 +669,13 @@ describe_only_db('mongo')('Read preference option', () => { expect(response.data.results.length).toEqual(2); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); - expect(myObjectReadPreference).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -779,14 +707,11 @@ describe_only_db('mongo')('Read preference option', () => { expect(result).toBe(1); let myObjectReadPreference = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { + myObjectReadPreference = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); @@ -796,7 +721,7 @@ describe_only_db('mongo')('Read preference option', () => { }); }); - it('should change read preference for `aggregate` using `beforeFind`', async() => { + it('should change read preference for `aggregate` using `beforeFind`', async () => { // Save objects const obj0 = new Parse.Object('MyObject'); obj0.set('boolKey', false); @@ -812,7 +737,7 @@ describe_only_db('mongo')('Read preference option', () => { spyOn(databaseAdapter.database.serverConfig, 'startSession').and.callThrough(); // Query const query = new Parse.Query('MyObject'); - const results = await query.aggregate([{match:{boolKey: false}}]); + const results = await query.aggregate([{ match: { boolKey: false } }]); // Validate expect(results.length).toBe(1); let readPreference = null; @@ -824,7 +749,7 @@ describe_only_db('mongo')('Read preference option', () => { expect(readPreference).toEqual(ReadPreference.SECONDARY); }); - it('should change read preference for `find` using query option', async() => { + it('should change read preference for `find` using query option', async () => { // Save objects const obj0 = new Parse.Object('MyObject'); obj0.set('boolKey', false); @@ -844,14 +769,13 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference = null; databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { if (call.args[0].ns.collection.indexOf('MyObject') >= 0) { - myObjectReadPreference = - call.args[0].options.readPreference.mode; + myObjectReadPreference = call.args[0].options.readPreference.mode; } }); expect(myObjectReadPreference).toEqual(ReadPreference.SECONDARY); }); - it('should change read preference for `aggregate` using query option', async() => { + it('should change read preference for `aggregate` using query option', async () => { // Save objects const obj0 = new Parse.Object('MyObject'); obj0.set('boolKey', false); @@ -864,7 +788,7 @@ describe_only_db('mongo')('Read preference option', () => { // Query const query = new Parse.Query('MyObject'); query.readPreference('SECONDARY'); - const results = await query.aggregate([{match:{boolKey: false}}]); + const results = await query.aggregate([{ match: { boolKey: false } }]); // Validate expect(results.length).toBe(1); let readPreference = null; @@ -907,32 +831,22 @@ describe_only_db('mongo')('Read preference option', () => { const firstResult = results[0]; expect(firstResult.get('boolKey')).toBe(false); expect(firstResult.get('myObject1').get('boolKey')).toBe(true); - expect( - firstResult - .get('myObject1') - .get('myObject0') - .get('boolKey') - ).toBe(false); + expect(firstResult.get('myObject1').get('myObject0').get('boolKey')).toBe(false); let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); @@ -976,38 +890,26 @@ describe_only_db('mongo')('Read preference option', () => { const firstResult = results[0]; expect(firstResult.get('boolKey')).toBe(false); expect(firstResult.get('myObject1').get('boolKey')).toBe(true); - expect( - firstResult - .get('myObject1') - .get('myObject0') - .get('boolKey') - ).toBe(false); + expect(firstResult.get('myObject1').get('myObject0').get('boolKey')).toBe(false); let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); - expect(myObjectReadPreference2).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference2).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -1053,28 +955,21 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); - expect(myObjectReadPreference2).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference2).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -1121,28 +1016,21 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); - expect(myObjectReadPreference2).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference2).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -1187,22 +1075,17 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); @@ -1252,28 +1135,21 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); - expect(myObjectReadPreference2).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference2).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -1319,28 +1195,21 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); - expect(myObjectReadPreference2).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference2).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -1387,28 +1256,21 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); - expect(myObjectReadPreference2).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference2).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) @@ -1469,28 +1331,21 @@ describe_only_db('mongo')('Read preference option', () => { let myObjectReadPreference0 = null; let myObjectReadPreference1 = null; let myObjectReadPreference2 = null; - databaseAdapter.database.serverConfig.cursor.calls - .all() - .forEach(call => { - if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { - myObjectReadPreference0 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { - myObjectReadPreference1 = - call.args[0].options.readPreference.mode; - } - if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { - myObjectReadPreference2 = - call.args[0].options.readPreference.mode; - } - }); + databaseAdapter.database.serverConfig.cursor.calls.all().forEach(call => { + if (call.args[0].ns.collection.indexOf('MyObject0') >= 0) { + myObjectReadPreference0 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject1') >= 0) { + myObjectReadPreference1 = call.args[0].options.readPreference.mode; + } + if (call.args[0].ns.collection.indexOf('MyObject2') >= 0) { + myObjectReadPreference2 = call.args[0].options.readPreference.mode; + } + }); expect(myObjectReadPreference0).toEqual(ReadPreference.SECONDARY); expect(myObjectReadPreference1).toEqual(ReadPreference.SECONDARY); - expect(myObjectReadPreference2).toEqual( - ReadPreference.SECONDARY_PREFERRED - ); + expect(myObjectReadPreference2).toEqual(ReadPreference.SECONDARY_PREFERRED); done(); }) diff --git a/spec/RedisCacheAdapter.spec.js b/spec/RedisCacheAdapter.spec.js index d4ff0327..4991d2b9 100644 --- a/spec/RedisCacheAdapter.spec.js +++ b/spec/RedisCacheAdapter.spec.js @@ -1,5 +1,4 @@ -const RedisCacheAdapter = require('../lib/Adapters/Cache/RedisCacheAdapter') - .default; +const RedisCacheAdapter = require('../lib/Adapters/Cache/RedisCacheAdapter').default; const Config = require('../lib/Config'); /* @@ -19,7 +18,7 @@ describe_only(() => { }); } - it('should get/set/clear', (done) => { + it('should get/set/clear', done => { const cache = new RedisCacheAdapter({ ttl: NaN, }); @@ -27,78 +26,78 @@ describe_only(() => { cache .put(KEY, VALUE) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(VALUE)) + .then(value => expect(value).toEqual(VALUE)) .then(() => cache.clear()) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(null)) + .then(value => expect(value).toEqual(null)) .then(done); }); - it('should expire after ttl', (done) => { + it('should expire after ttl', done => { const cache = new RedisCacheAdapter(null, 50); cache .put(KEY, VALUE) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(VALUE)) + .then(value => expect(value).toEqual(VALUE)) .then(wait.bind(null, 52)) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(null)) + .then(value => expect(value).toEqual(null)) .then(done); }); - it('should not store value for ttl=0', (done) => { + it('should not store value for ttl=0', done => { const cache = new RedisCacheAdapter(null, 5); cache .put(KEY, VALUE, 0) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(null)) + .then(value => expect(value).toEqual(null)) .then(done); }); - it('should not expire when ttl=Infinity', (done) => { + it('should not expire when ttl=Infinity', done => { const cache = new RedisCacheAdapter(null, 1); cache .put(KEY, VALUE, Infinity) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(VALUE)) + .then(value => expect(value).toEqual(VALUE)) .then(wait.bind(null, 5)) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(VALUE)) + .then(value => expect(value).toEqual(VALUE)) .then(done); }); - it('should fallback to default ttl', (done) => { + it('should fallback to default ttl', done => { const cache = new RedisCacheAdapter(null, 1); let promise = Promise.resolve(); - [-100, null, undefined, 'not number', true].forEach((ttl) => { + [-100, null, undefined, 'not number', true].forEach(ttl => { promise = promise.then(() => cache .put(KEY, VALUE, ttl) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(VALUE)) + .then(value => expect(value).toEqual(VALUE)) .then(wait.bind(null, 5)) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(null)) + .then(value => expect(value).toEqual(null)) ); }); promise.then(done); }); - it('should find un-expired records', (done) => { + it('should find un-expired records', done => { const cache = new RedisCacheAdapter(null, 5); cache .put(KEY, VALUE) .then(() => cache.get(KEY)) - .then((value) => expect(value).toEqual(VALUE)) + .then(value => expect(value).toEqual(VALUE)) .then(wait.bind(null, 1)) .then(() => cache.get(KEY)) - .then((value) => expect(value).not.toEqual(null)) + .then(value => expect(value).not.toEqual(null)) .then(done); }); @@ -129,7 +128,7 @@ describe_only(() => { return Object.keys(cache.queue.queue).length; } - it('it should clear completed operations from queue', (done) => { + it('it should clear completed operations from queue', done => { const cache = new RedisCacheAdapter({ ttl: NaN }); // execute a bunch of operations in sequence @@ -151,7 +150,7 @@ describe_only(() => { promise.then(() => expect(getQueueCount(cache)).toEqual(0)).then(done); }); - it('it should count per key chained operations correctly', (done) => { + it('it should count per key chained operations correctly', done => { const cache = new RedisCacheAdapter({ ttl: NaN }); let key1Promise = Promise.resolve(); diff --git a/spec/RedisPubSub.spec.js b/spec/RedisPubSub.spec.js index ffb189aa..c7def313 100644 --- a/spec/RedisPubSub.spec.js +++ b/spec/RedisPubSub.spec.js @@ -1,14 +1,14 @@ const RedisPubSub = require('../lib/Adapters/PubSub/RedisPubSub').RedisPubSub; -describe('RedisPubSub', function() { - beforeEach(function(done) { +describe('RedisPubSub', function () { + beforeEach(function (done) { // Mock redis const createClient = jasmine.createSpy('createClient'); jasmine.mockLibrary('redis', 'createClient', createClient); done(); }); - it('can create publisher', function() { + it('can create publisher', function () { RedisPubSub.createPublisher({ redisURL: 'redisAddress', redisOptions: { socket_keepalive: true }, @@ -21,7 +21,7 @@ describe('RedisPubSub', function() { }); }); - it('can create subscriber', function() { + it('can create subscriber', function () { RedisPubSub.createSubscriber({ redisURL: 'redisAddress', redisOptions: { socket_keepalive: true }, @@ -34,7 +34,7 @@ describe('RedisPubSub', function() { }); }); - afterEach(function() { + afterEach(function () { jasmine.restoreLibrary('redis', 'createClient'); }); }); diff --git a/spec/RegexVulnerabilities.spec.js b/spec/RegexVulnerabilities.spec.js index 58f5afac..1a96ebfd 100644 --- a/spec/RegexVulnerabilities.spec.js +++ b/spec/RegexVulnerabilities.spec.js @@ -16,8 +16,8 @@ const emailAdapter = { const appName = 'test'; const publicServerURL = 'http://localhost:8378/1'; -describe('Regex Vulnerabilities', function() { - beforeEach(async function() { +describe('Regex Vulnerabilities', function () { + beforeEach(async function () { await reconfigureServer({ verifyUserEmails: true, emailAdapter, @@ -42,8 +42,8 @@ describe('Regex Vulnerabilities', function() { this.partialSessionToken = this.sessionToken.slice(0, 3); }); - describe('on session token', function() { - it('should not work with regex', async function() { + describe('on session token', function () { + it('should not work with regex', async function () { try { await request({ url: `${serverURL}/users/me`, @@ -64,7 +64,7 @@ describe('Regex Vulnerabilities', function() { } }); - it('should work with plain token', async function() { + it('should work with plain token', async function () { const meResponse = await request({ url: `${serverURL}/users/me`, method: 'POST', @@ -80,13 +80,13 @@ describe('Regex Vulnerabilities', function() { }); }); - describe('on verify e-mail', function() { - beforeEach(async function() { + describe('on verify e-mail', function () { + beforeEach(async function () { const userQuery = new Parse.Query(Parse.User); this.user = await userQuery.get(this.objectId, { useMasterKey: true }); }); - it('should not work with regex', async function() { + it('should not work with regex', async function () { expect(this.user.get('emailVerified')).toEqual(false); await request({ url: `${serverURL}/apps/test/verify_email?username=someemail@somedomain.com&token[$regex]=`, @@ -96,7 +96,7 @@ describe('Regex Vulnerabilities', function() { expect(this.user.get('emailVerified')).toEqual(false); }); - it('should work with plain token', async function() { + it('should work with plain token', async function () { expect(this.user.get('emailVerified')).toEqual(false); // It should work await request({ @@ -110,15 +110,12 @@ describe('Regex Vulnerabilities', function() { }); }); - describe('on password reset', function() { - beforeEach(async function() { - this.user = await Parse.User.logIn( - 'someemail@somedomain.com', - 'somepassword' - ); + describe('on password reset', function () { + beforeEach(async function () { + this.user = await Parse.User.logIn('someemail@somedomain.com', 'somepassword'); }); - it('should not work with regex', async function() { + it('should not work with regex', async function () { expect(this.user.id).toEqual(this.objectId); await request({ url: `${serverURL}/requestPasswordReset`, @@ -136,9 +133,7 @@ describe('Regex Vulnerabilities', function() { method: 'GET', }); expect(passwordResetResponse.status).toEqual(302); - expect(passwordResetResponse.headers.location).toMatch( - `\\/invalid\\_link\\.html` - ); + expect(passwordResetResponse.headers.location).toMatch(`\\/invalid\\_link\\.html`); await request({ url: `${serverURL}/apps/test/request_password_reset`, method: 'POST', @@ -157,7 +152,7 @@ describe('Regex Vulnerabilities', function() { } }); - it('should work with plain token', async function() { + it('should work with plain token', async function () { expect(this.user.id).toEqual(this.objectId); await request({ url: `${serverURL}/requestPasswordReset`, @@ -188,10 +183,7 @@ describe('Regex Vulnerabilities', function() { new_password: 'newpassword', }, }); - const userAgain = await Parse.User.logIn( - 'someemail@somedomain.com', - 'newpassword' - ); + const userAgain = await Parse.User.logIn('someemail@somedomain.com', 'newpassword'); expect(userAgain.id).toEqual(this.objectId); }); }); diff --git a/spec/RestQuery.spec.js b/spec/RestQuery.spec.js index 412394df..629cc7e5 100644 --- a/spec/RestQuery.spec.js +++ b/spec/RestQuery.spec.js @@ -137,13 +137,7 @@ describe('rest query', () => { }) .then(() => { queryWhere.photo.objectId = photo.objectId; - return rest.find( - config, - nobody, - 'TestActivity', - queryWhere, - queryOptions - ); + return rest.find(config, nobody, 'TestActivity', queryWhere, queryOptions); }) .then(response => { const results = response.results; @@ -163,22 +157,19 @@ describe('rest query', () => { const customConfig = Object.assign({}, config, { allowClientClassCreation: false, }); - rest - .find(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}) - .then( - () => { - fail('Should throw an error'); - done(); - }, - err => { - expect(err.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); - expect(err.message).toEqual( - 'This user is not allowed to access ' + - 'non-existent class: ClientClassCreation' - ); - done(); - } - ); + rest.find(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}).then( + () => { + fail('Should throw an error'); + done(); + }, + err => { + expect(err.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); + expect(err.message).toEqual( + 'This user is not allowed to access ' + 'non-existent class: ClientClassCreation' + ); + done(); + } + ); }); it('query existent class when disabled client class creation', async () => { @@ -186,10 +177,7 @@ describe('rest query', () => { allowClientClassCreation: false, }); const schema = await config.database.loadSchema(); - const actualSchema = await schema.addClassIfNotExists( - 'ClientClassCreation', - {} - ); + const actualSchema = await schema.addClassIfNotExists('ClientClassCreation', {}); expect(actualSchema.className).toEqual('ClientClassCreation'); await schema.reloadData({ clearCache: true }); @@ -277,13 +265,7 @@ describe('rest query', () => { return rest.create(config, nobody, 'TestObject', { foo: 'qux' }); }) .then(() => { - return rest.find( - config, - nobody, - 'TestObject', - {}, - { limit: 0, count: 1 } - ); + return rest.find(config, nobody, 'TestObject', {}, { limit: 0, count: 1 }); }) .then(response => { expect(response.results.length).toEqual(0); @@ -421,12 +403,12 @@ describe('RestQuery.each', () => { }); it('test afterSave response object is return', done => { - Parse.Cloud.beforeSave('TestObject2', function(req) { + Parse.Cloud.beforeSave('TestObject2', function (req) { req.object.set('tobeaddbefore', true); req.object.set('tobeaddbeforeandremoveafter', true); }); - Parse.Cloud.afterSave('TestObject2', function(req) { + Parse.Cloud.afterSave('TestObject2', function (req) { const jsonObject = req.object.toJSON(); delete jsonObject.todelete; delete jsonObject.tobeaddbeforeandremoveafter; @@ -435,15 +417,13 @@ describe('RestQuery.each', () => { return jsonObject; }); - rest - .create(config, nobody, 'TestObject2', { todelete: true, tokeep: true }) - .then(response => { - expect(response.response.toadd).toBeTruthy(); - expect(response.response.tokeep).toBeTruthy(); - expect(response.response.tobeaddbefore).toBeTruthy(); - expect(response.response.tobeaddbeforeandremoveafter).toBeUndefined(); - expect(response.response.todelete).toBeUndefined(); - done(); - }); + rest.create(config, nobody, 'TestObject2', { todelete: true, tokeep: true }).then(response => { + expect(response.response.toadd).toBeTruthy(); + expect(response.response.tokeep).toBeTruthy(); + expect(response.response.tobeaddbefore).toBeTruthy(); + expect(response.response.tobeaddbeforeandremoveafter).toBeUndefined(); + expect(response.response.todelete).toBeUndefined(); + done(); + }); }); }); diff --git a/spec/RevocableSessionsUpgrade.spec.js b/spec/RevocableSessionsUpgrade.spec.js index 4587d99f..e60448d0 100644 --- a/spec/RevocableSessionsUpgrade.spec.js +++ b/spec/RevocableSessionsUpgrade.spec.js @@ -39,12 +39,7 @@ describe_only_db('mongo')('revocable sessions', () => { return schemaController.getOneSchema('_User', true); }) .then(schema => { - return config.database.adapter.find( - '_User', - schema, - { objectId: '1234567890' }, - {} - ); + return config.database.adapter.find('_User', schema, { objectId: '1234567890' }, {}); }) .then(results => { expect(results.length).toBe(1); diff --git a/spec/Schema.spec.js b/spec/Schema.spec.js index 7cdc88a6..932eec16 100644 --- a/spec/Schema.spec.js +++ b/spec/Schema.spec.js @@ -16,10 +16,7 @@ const hasAllPODobject = () => { obj.set('aObject', { k1: 'value', k2: true, k3: 5 }); obj.set('aArray', ['contents', true, 5]); obj.set('aGeoPoint', new Parse.GeoPoint({ latitude: 0, longitude: 0 })); - obj.set( - 'aFile', - new Parse.File('f.txt', { base64: 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=' }) - ); + obj.set('aFile', new Parse.File('f.txt', { base64: 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=' })); return obj; }; @@ -292,9 +289,7 @@ describe('SchemaController', () => { fail('Class permissions should have rejected this query.'); }, err => { - expect(err.message).toEqual( - 'Permission denied for action count on class Stuff.' - ); + expect(err.message).toEqual('Permission denied for action count on class Stuff.'); done(); } ) @@ -441,19 +436,9 @@ describe('SchemaController', () => { schema .validateObject('NewClass', { foo: 2 }) .then(() => schema.reloadData()) - .then(() => - schema.updateClass( - 'NewClass', - {}, - newLevelPermissions, - {}, - config.database - ) - ) + .then(() => schema.updateClass('NewClass', {}, newLevelPermissions, {}, config.database)) .then(actualSchema => { - expect( - dd(actualSchema.classLevelPermissions, newLevelPermissions) - ).toEqual(undefined); + expect(dd(actualSchema.classLevelPermissions, newLevelPermissions)).toEqual(undefined); done(); }) .catch(error => { @@ -539,14 +524,12 @@ describe('SchemaController', () => { it('refuses to create classes with invalid names', done => { config.database.loadSchema().then(schema => { - schema - .addClassIfNotExists('_InvalidName', { foo: { type: 'String' } }) - .catch(error => { - expect(error.message).toEqual( - 'Invalid classname: _InvalidName, classnames can only have alphanumeric characters and _, and must start with an alpha character ' - ); - done(); - }); + schema.addClassIfNotExists('_InvalidName', { foo: { type: 'String' } }).catch(error => { + expect(error.message).toEqual( + 'Invalid classname: _InvalidName, classnames can only have alphanumeric characters and _, and must start with an alpha character ' + ); + done(); + }); }); }); @@ -568,9 +551,7 @@ describe('SchemaController', () => { it('refuses to explicitly create the default fields for custom classes', done => { config.database .loadSchema() - .then(schema => - schema.addClassIfNotExists('NewClass', { objectId: { type: 'String' } }) - ) + .then(schema => schema.addClassIfNotExists('NewClass', { objectId: { type: 'String' } })) .catch(error => { expect(error.code).toEqual(136); expect(error.message).toEqual('field objectId cannot be added'); @@ -731,15 +712,7 @@ describe('SchemaController', () => { schema .validateObject('NewClass', {}) .then(() => schema.reloadData()) - .then(() => - schema.updateClass( - 'NewClass', - {}, - levelPermissions, - {}, - config.database - ) - ) + .then(() => schema.updateClass('NewClass', {}, levelPermissions, {}, config.database)) .then(done.fail) .catch(error => { expect(error.code).toEqual(Parse.Error.INVALID_JSON); @@ -762,15 +735,7 @@ describe('SchemaController', () => { schema .validateObject('NewClass', {}) .then(() => schema.reloadData()) - .then(() => - schema.updateClass( - 'NewClass', - {}, - levelPermissions, - {}, - config.database - ) - ) + .then(() => schema.updateClass('NewClass', {}, levelPermissions, {}, config.database)) .then(done.fail) .catch(error => { expect(error.code).toEqual(Parse.Error.INVALID_JSON); @@ -1019,9 +984,7 @@ describe('SchemaController', () => { it('refuses to delete invalid fields', done => { config.database .loadSchema() - .then(schema => - schema.deleteField('invalid field name', 'ValidClassName') - ) + .then(schema => schema.deleteField('invalid field name', 'ValidClassName')) .catch(error => { expect(error.code).toEqual(Parse.Error.INVALID_KEY_NAME); done(); @@ -1057,9 +1020,7 @@ describe('SchemaController', () => { .then(schema => schema.deleteField('missingField', 'HasAllPOD')) .catch(error => { expect(error.code).toEqual(255); - expect(error.message).toEqual( - 'Field missingField does not exist, cannot delete.' - ); + expect(error.message).toEqual('Field missingField does not exist, cannot delete.'); done(); }); }); @@ -1075,35 +1036,19 @@ describe('SchemaController', () => { relation.add(obj1); return obj2.save(); }) - .then(() => - config.database.collectionExists( - '_Join:aRelation:HasPointersAndRelations' - ) - ) + .then(() => config.database.collectionExists('_Join:aRelation:HasPointersAndRelations')) .then(exists => { if (!exists) { fail('Relation collection ' + 'should exist after save.'); } }) .then(() => config.database.loadSchema()) - .then(schema => - schema.deleteField( - 'aRelation', - 'HasPointersAndRelations', - config.database - ) - ) - .then(() => - config.database.collectionExists( - '_Join:aRelation:HasPointersAndRelations' - ) - ) + .then(schema => schema.deleteField('aRelation', 'HasPointersAndRelations', config.database)) + .then(() => config.database.collectionExists('_Join:aRelation:HasPointersAndRelations')) .then( exists => { if (exists) { - fail( - 'Relation collection should not exist after deleting relation field.' - ); + fail('Relation collection should not exist after deleting relation field.'); } done(); }, @@ -1143,9 +1088,7 @@ describe('SchemaController', () => { }; expect(dd(actualSchema, expectedSchema)).toEqual(undefined); }) - .then(() => - config.database.collectionExists('_Join:relationField:NewClass') - ) + .then(() => config.database.collectionExists('_Join:relationField:NewClass')) .then(exist => { on_db( 'postgres', @@ -1158,9 +1101,7 @@ describe('SchemaController', () => { } ); }) - .then(() => - schema.deleteField('relationField', 'NewClass', config.database) - ) + .then(() => schema.deleteField('relationField', 'NewClass', config.database)) .then(() => schema.reloadData()) .then(() => { const expectedSchema = { @@ -1169,9 +1110,7 @@ describe('SchemaController', () => { createdAt: { type: 'Date' }, ACL: { type: 'ACL' }, }; - expect(dd(schema.schemaData.NewClass.fields, expectedSchema)).toEqual( - undefined - ); + expect(dd(schema.schemaData.NewClass.fields, expectedSchema)).toEqual(undefined); }) .then(done) .catch(done.fail); @@ -1184,9 +1123,7 @@ describe('SchemaController', () => { const obj2 = hasAllPODobject(); Parse.Object.saveAll([obj1, obj2]) .then(() => config.database.loadSchema()) - .then(schema => - schema.deleteField('aString', 'HasAllPOD', config.database) - ) + .then(schema => schema.deleteField('aString', 'HasAllPOD', config.database)) .then(() => new Parse.Query('HasAllPOD').get(obj1.id)) .then(obj1Reloaded => { expect(obj1Reloaded.get('aString')).toEqual(undefined); @@ -1194,10 +1131,7 @@ describe('SchemaController', () => { obj1Reloaded .save() .then(obj1reloadedAgain => { - expect(obj1reloadedAgain.get('aString')).toEqual([ - 'not a string', - 'this time', - ]); + expect(obj1reloadedAgain.get('aString')).toEqual(['not a string', 'this time']); return new Parse.Query('HasAllPOD').get(obj2.id); }) .then(obj2reloaded => { @@ -1224,9 +1158,7 @@ describe('SchemaController', () => { expect(obj1.get('aPointer').id).toEqual(obj1.id); }) .then(() => config.database.loadSchema()) - .then(schema => - schema.deleteField('aPointer', 'NewClass', config.database) - ) + .then(schema => schema.deleteField('aPointer', 'NewClass', config.database)) .then(() => new Parse.Query('NewClass').get(obj1.id)) .then(obj1 => { expect(obj1.get('aPointer')).toEqual(undefined); @@ -1382,29 +1314,19 @@ describe('SchemaController', () => { it('properly handles volatile _Schemas', done => { function validateSchemaStructure(schema) { - expect(Object.prototype.hasOwnProperty.call(schema, 'className')).toBe( - true - ); + expect(Object.prototype.hasOwnProperty.call(schema, 'className')).toBe(true); expect(Object.prototype.hasOwnProperty.call(schema, 'fields')).toBe(true); - expect( - Object.prototype.hasOwnProperty.call(schema, 'classLevelPermissions') - ).toBe(true); + expect(Object.prototype.hasOwnProperty.call(schema, 'classLevelPermissions')).toBe(true); } function validateSchemaDataStructure(schemaData) { Object.keys(schemaData).forEach(className => { const schema = schemaData[className]; // Hooks has className... if (className != '_Hooks') { - expect( - Object.prototype.hasOwnProperty.call(schema, 'className') - ).toBe(false); + expect(Object.prototype.hasOwnProperty.call(schema, 'className')).toBe(false); } - expect(Object.prototype.hasOwnProperty.call(schema, 'fields')).toBe( - false - ); - expect( - Object.prototype.hasOwnProperty.call(schema, 'classLevelPermissions') - ).toBe(false); + expect(Object.prototype.hasOwnProperty.call(schema, 'fields')).toBe(false); + expect(Object.prototype.hasOwnProperty.call(schema, 'classLevelPermissions')).toBe(false); }); } let schema; @@ -1430,26 +1352,17 @@ describe('SchemaController', () => { it('setAllClasses return classes if cache fails', async () => { const schema = await config.database.loadSchema(); - spyOn(schema._cache, 'setAllClasses').and.callFake(() => - Promise.reject('Oops!') - ); + spyOn(schema._cache, 'setAllClasses').and.callFake(() => Promise.reject('Oops!')); const errorSpy = spyOn(console, 'error').and.callFake(() => {}); const allSchema = await schema.setAllClasses(); expect(allSchema).toBeDefined(); - expect(errorSpy).toHaveBeenCalledWith( - 'Error saving schema to cache:', - 'Oops!' - ); + expect(errorSpy).toHaveBeenCalledWith('Error saving schema to cache:', 'Oops!'); }); it('should not throw on null field types', async () => { const schema = await config.database.loadSchema(); - const result = await schema.enforceFieldExists( - 'NewClass', - 'fieldName', - null - ); + const result = await schema.enforceFieldExists('NewClass', 'fieldName', null); expect(result).toBeUndefined(); }); @@ -1505,9 +1418,7 @@ describe('Class Level Permissions for requiredAuth', () => { done(); }, e => { - expect(e.message).toEqual( - 'Permission denied, user needs to be authenticated.' - ); + expect(e.message).toEqual('Permission denied, user needs to be authenticated.'); done(); } ); @@ -1606,9 +1517,7 @@ describe('Class Level Permissions for requiredAuth', () => { done(); }, e => { - expect(e.message).toEqual( - 'Permission denied, user needs to be authenticated.' - ); + expect(e.message).toEqual('Permission denied, user needs to be authenticated.'); done(); } ); @@ -1696,9 +1605,7 @@ describe('Class Level Permissions for requiredAuth', () => { done(); }, e => { - expect(e.message).toEqual( - 'Permission denied, user needs to be authenticated.' - ); + expect(e.message).toEqual('Permission denied, user needs to be authenticated.'); done(); } ); @@ -1743,9 +1650,7 @@ describe('Class Level Permissions for requiredAuth', () => { done(); }, e => { - expect(e.message).toEqual( - 'Permission denied, user needs to be authenticated.' - ); + expect(e.message).toEqual('Permission denied, user needs to be authenticated.'); done(); } ); diff --git a/spec/SchemaCache.spec.js b/spec/SchemaCache.spec.js index 26897e03..5a4a5173 100644 --- a/spec/SchemaCache.spec.js +++ b/spec/SchemaCache.spec.js @@ -1,7 +1,5 @@ -const CacheController = require('../lib/Controllers/CacheController.js') - .default; -const InMemoryCacheAdapter = require('../lib/Adapters/Cache/InMemoryCacheAdapter') - .default; +const CacheController = require('../lib/Controllers/CacheController.js').default; +const InMemoryCacheAdapter = require('../lib/Adapters/Cache/InMemoryCacheAdapter').default; const SchemaCache = require('../lib/Controllers/SchemaCache').default; describe('SchemaCache', () => { diff --git a/spec/SessionTokenCache.spec.js b/spec/SessionTokenCache.spec.js index 990903d3..de1b101c 100644 --- a/spec/SessionTokenCache.spec.js +++ b/spec/SessionTokenCache.spec.js @@ -1,8 +1,7 @@ -const SessionTokenCache = require('../lib/LiveQuery/SessionTokenCache') - .SessionTokenCache; +const SessionTokenCache = require('../lib/LiveQuery/SessionTokenCache').SessionTokenCache; -describe('SessionTokenCache', function() { - beforeEach(function(done) { +describe('SessionTokenCache', function () { + beforeEach(function (done) { const Parse = require('parse/node'); spyOn(Parse, 'Query').and.returnValue({ @@ -13,13 +12,13 @@ describe('SessionTokenCache', function() { }) ) ), - equalTo: function() {}, + equalTo: function () {}, }); done(); }); - it('can get undefined userId', function(done) { + it('can get undefined userId', function (done) { const sessionTokenCache = new SessionTokenCache(); sessionTokenCache.getUserId(undefined).then( @@ -31,7 +30,7 @@ describe('SessionTokenCache', function() { ); }); - it('can get existing userId', function(done) { + it('can get existing userId', function (done) { const sessionTokenCache = new SessionTokenCache(); const sessionToken = 'sessionToken'; const userId = 'userId'; @@ -43,7 +42,7 @@ describe('SessionTokenCache', function() { }); }); - it('can get new userId', function(done) { + it('can get new userId', function (done) { const sessionTokenCache = new SessionTokenCache(); sessionTokenCache.getUserId('sessionToken').then(userIdFromCache => { diff --git a/spec/Subscription.spec.js b/spec/Subscription.spec.js index 368b493f..9c7aa4c5 100644 --- a/spec/Subscription.spec.js +++ b/spec/Subscription.spec.js @@ -1,17 +1,13 @@ const Subscription = require('../lib/LiveQuery/Subscription').Subscription; let logger; -describe('Subscription', function() { - beforeEach(function() { +describe('Subscription', function () { + beforeEach(function () { logger = require('../lib/logger').logger; spyOn(logger, 'error').and.callThrough(); }); - it('can be initialized', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can be initialized', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); expect(subscription.className).toBe('className'); expect(subscription.query).toEqual({ key: 'value' }); @@ -19,45 +15,29 @@ describe('Subscription', function() { expect(subscription.clientRequestIds.size).toBe(0); }); - it('can check it has subscribing clients', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can check it has subscribing clients', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); expect(subscription.hasSubscribingClient()).toBe(false); }); - it('can check it does not have subscribing clients', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can check it does not have subscribing clients', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); expect(subscription.hasSubscribingClient()).toBe(true); }); - it('can add one request for one client', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can add one request for one client', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); expect(subscription.clientRequestIds.size).toBe(1); expect(subscription.clientRequestIds.get(1)).toEqual([1]); }); - it('can add requests for one client', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can add requests for one client', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); @@ -65,12 +45,8 @@ describe('Subscription', function() { expect(subscription.clientRequestIds.get(1)).toEqual([1, 2]); }); - it('can add requests for clients', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can add requests for clients', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.addClientSubscription(2, 2); @@ -81,23 +57,15 @@ describe('Subscription', function() { expect(subscription.clientRequestIds.get(2)).toEqual([2, 3]); }); - it('can delete requests for nonexistent client', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can delete requests for nonexistent client', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.deleteClientSubscription(1, 1); expect(logger.error).toHaveBeenCalled(); }); - it('can delete nonexistent request for one client', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can delete nonexistent request for one client', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.deleteClientSubscription(1, 2); @@ -106,12 +74,8 @@ describe('Subscription', function() { expect(subscription.clientRequestIds.get(1)).toEqual([1]); }); - it('can delete some requests for one client', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can delete some requests for one client', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.deleteClientSubscription(1, 2); @@ -121,12 +85,8 @@ describe('Subscription', function() { expect(subscription.clientRequestIds.get(1)).toEqual([1]); }); - it('can delete all requests for one client', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can delete all requests for one client', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.deleteClientSubscription(1, 1); @@ -136,12 +96,8 @@ describe('Subscription', function() { expect(subscription.clientRequestIds.size).toBe(0); }); - it('can delete requests for multiple clients', function() { - const subscription = new Subscription( - 'className', - { key: 'value' }, - 'hash' - ); + it('can delete requests for multiple clients', function () { + const subscription = new Subscription('className', { key: 'value' }, 'hash'); subscription.addClientSubscription(1, 1); subscription.addClientSubscription(1, 2); subscription.addClientSubscription(2, 1); diff --git a/spec/TwitterAuth.spec.js b/spec/TwitterAuth.spec.js index ce55542a..8f2bc31e 100644 --- a/spec/TwitterAuth.spec.js +++ b/spec/TwitterAuth.spec.js @@ -20,7 +20,7 @@ describe('Twitter Auth', () => { ).toEqual('hello'); // Multiple options, consumer_key not found - expect(function() { + expect(function () { twitter.handleMultipleConfigurations( { consumer_key: 'some', @@ -37,7 +37,7 @@ describe('Twitter Auth', () => { }).toThrow(); // Multiple options, consumer_key not found - expect(function() { + expect(function () { twitter.handleMultipleConfigurations( { auth_token: 'token', diff --git a/spec/Uniqueness.spec.js b/spec/Uniqueness.spec.js index 73dfad34..72ba5b98 100644 --- a/spec/Uniqueness.spec.js +++ b/spec/Uniqueness.spec.js @@ -3,7 +3,7 @@ const Parse = require('parse/node'); const Config = require('../lib/Config'); -describe('Uniqueness', function() { +describe('Uniqueness', function () { it('fail when create duplicate value in unique field', done => { const obj = new Parse.Object('UniqueField'); obj.set('unique', 'value'); diff --git a/spec/UserController.spec.js b/spec/UserController.spec.js index 1e4d5e48..94846c59 100644 --- a/spec/UserController.spec.js +++ b/spec/UserController.spec.js @@ -1,5 +1,4 @@ -const UserController = require('../lib/Controllers/UserController') - .UserController; +const UserController = require('../lib/Controllers/UserController').UserController; const emailAdapter = require('./MockEmailAdapter'); const AppCache = require('../lib/cache').AppCache; diff --git a/spec/UserPII.spec.js b/spec/UserPII.spec.js index 4483f5d8..764c6815 100644 --- a/spec/UserPII.spec.js +++ b/spec/UserPII.spec.js @@ -15,11 +15,7 @@ describe('Personally Identifiable Information', () => { beforeEach(async done => { user = await Parse.User.signUp('tester', 'abc'); user = await Parse.User.logIn(user.get('username'), 'abc'); - await user - .set('email', EMAIL) - .set('zip', ZIP) - .set('ssn', SSN) - .save(); + await user.set('email', EMAIL).set('zip', ZIP).set('ssn', SSN).save(); done(); }); @@ -87,14 +83,12 @@ describe('Personally Identifiable Information', () => { it('should get PII via API with Find using master key', done => { return Parse.User.logOut().then(() => - new Parse.Query(Parse.User) - .first({ useMasterKey: true }) - .then(fetchedUser => { - expect(fetchedUser.get('email')).toBe(EMAIL); - expect(fetchedUser.get('zip')).toBe(ZIP); - expect(fetchedUser.get('ssn')).toBe(SSN); - done(); - }) + new Parse.Query(Parse.User).first({ useMasterKey: true }).then(fetchedUser => { + expect(fetchedUser.get('email')).toBe(EMAIL); + expect(fetchedUser.get('zip')).toBe(ZIP); + expect(fetchedUser.get('ssn')).toBe(SSN); + done(); + }) ); }); @@ -120,14 +114,12 @@ describe('Personally Identifiable Information', () => { it('should get PII via API with Get using master key', done => { return Parse.User.logOut().then(() => - new Parse.Query(Parse.User) - .get(user.id, { useMasterKey: true }) - .then(fetchedUser => { - expect(fetchedUser.get('email')).toBe(EMAIL); - expect(fetchedUser.get('zip')).toBe(ZIP); - expect(fetchedUser.get('ssn')).toBe(SSN); - done(); - }) + new Parse.Query(Parse.User).get(user.id, { useMasterKey: true }).then(fetchedUser => { + expect(fetchedUser.get('email')).toBe(EMAIL); + expect(fetchedUser.get('zip')).toBe(ZIP); + expect(fetchedUser.get('ssn')).toBe(SSN); + done(); + }) ); }); @@ -249,9 +241,7 @@ describe('Personally Identifiable Information', () => { describe('with deprecated configured sensitive fields', () => { beforeEach(done => { - return reconfigureServer({ userSensitiveFields: ['ssn', 'zip'] }).then( - done - ); + return reconfigureServer({ userSensitiveFields: ['ssn', 'zip'] }).then(done); }); it('should be able to get own PII via API with object', done => { @@ -322,14 +312,12 @@ describe('Personally Identifiable Information', () => { it('should get PII via API with Find using master key', done => { Parse.User.logOut().then(() => - new Parse.Query(Parse.User) - .first({ useMasterKey: true }) - .then(fetchedUser => { - expect(fetchedUser.get('email')).toBe(EMAIL); - expect(fetchedUser.get('zip')).toBe(ZIP); - expect(fetchedUser.get('ssn')).toBe(SSN); - done(); - }) + new Parse.Query(Parse.User).first({ useMasterKey: true }).then(fetchedUser => { + expect(fetchedUser.get('email')).toBe(EMAIL); + expect(fetchedUser.get('zip')).toBe(ZIP); + expect(fetchedUser.get('ssn')).toBe(SSN); + done(); + }) ); }); @@ -355,14 +343,12 @@ describe('Personally Identifiable Information', () => { it('should get PII via API with Get using master key', done => { Parse.User.logOut().then(() => - new Parse.Query(Parse.User) - .get(user.id, { useMasterKey: true }) - .then(fetchedUser => { - expect(fetchedUser.get('email')).toBe(EMAIL); - expect(fetchedUser.get('zip')).toBe(ZIP); - expect(fetchedUser.get('ssn')).toBe(SSN); - done(); - }) + new Parse.Query(Parse.User).get(user.id, { useMasterKey: true }).then(fetchedUser => { + expect(fetchedUser.get('email')).toBe(EMAIL); + expect(fetchedUser.get('zip')).toBe(ZIP); + expect(fetchedUser.get('ssn')).toBe(SSN); + done(); + }) ); }); @@ -499,15 +485,11 @@ describe('Personally Identifiable Information', () => { let adminUser; beforeEach(async done => { - const adminRole = await new Parse.Role( - 'Administrator', - new Parse.ACL() - ).save(null, { useMasterKey: true }); + const adminRole = await new Parse.Role('Administrator', new Parse.ACL()).save(null, { + useMasterKey: true, + }); - const managementRole = new Parse.Role( - 'managementOf_user' + user.id, - new Parse.ACL(user) - ); + const managementRole = new Parse.Role('managementOf_user' + user.id, new Parse.ACL(user)); managementRole.getRoles().add(adminRole); await managementRole.save(null, { useMasterKey: true }); @@ -517,10 +499,7 @@ describe('Personally Identifiable Information', () => { adminUser = await Parse.User.signUp('administrator', 'secure'); adminUser = await Parse.User.logIn(adminUser.get('username'), 'secure'); - await adminRole - .getUsers() - .add(adminUser) - .save(null, { useMasterKey: true }); + await adminRole.getUsers().add(adminUser).save(null, { useMasterKey: true }); done(); }); @@ -782,14 +761,12 @@ describe('Personally Identifiable Information', () => { it('should get PII via API with Find using master key', done => { Parse.User.logOut().then(() => - new Parse.Query(Parse.User) - .first({ useMasterKey: true }) - .then(fetchedUser => { - expect(fetchedUser.get('email')).toBe(EMAIL); - expect(fetchedUser.get('zip')).toBe(ZIP); - expect(fetchedUser.get('ssn')).toBe(SSN); - done(); - }) + new Parse.Query(Parse.User).first({ useMasterKey: true }).then(fetchedUser => { + expect(fetchedUser.get('email')).toBe(EMAIL); + expect(fetchedUser.get('zip')).toBe(ZIP); + expect(fetchedUser.get('ssn')).toBe(SSN); + done(); + }) ); }); @@ -815,14 +792,12 @@ describe('Personally Identifiable Information', () => { it('should get PII via API with Get using master key', done => { Parse.User.logOut().then(() => - new Parse.Query(Parse.User) - .get(user.id, { useMasterKey: true }) - .then(fetchedUser => { - expect(fetchedUser.get('email')).toBe(EMAIL); - expect(fetchedUser.get('zip')).toBe(ZIP); - expect(fetchedUser.get('ssn')).toBe(SSN); - done(); - }) + new Parse.Query(Parse.User).get(user.id, { useMasterKey: true }).then(fetchedUser => { + expect(fetchedUser.get('email')).toBe(EMAIL); + expect(fetchedUser.get('zip')).toBe(ZIP); + expect(fetchedUser.get('ssn')).toBe(SSN); + done(); + }) ); }); @@ -962,15 +937,11 @@ describe('Personally Identifiable Information', () => { let adminUser; beforeEach(async done => { - const adminRole = await new Parse.Role( - 'Administrator', - new Parse.ACL() - ).save(null, { useMasterKey: true }); + const adminRole = await new Parse.Role('Administrator', new Parse.ACL()).save(null, { + useMasterKey: true, + }); - const managementRole = new Parse.Role( - 'managementOf_user' + user.id, - new Parse.ACL(user) - ); + const managementRole = new Parse.Role('managementOf_user' + user.id, new Parse.ACL(user)); managementRole.getRoles().add(adminRole); await managementRole.save(null, { useMasterKey: true }); @@ -980,10 +951,7 @@ describe('Personally Identifiable Information', () => { adminUser = await Parse.User.signUp('administrator', 'secure'); adminUser = await Parse.User.logIn(adminUser.get('username'), 'secure'); - await adminRole - .getUsers() - .add(adminUser) - .save(null, { useMasterKey: true }); + await adminRole.getUsers().add(adminUser).save(null, { useMasterKey: true }); done(); }); @@ -1129,11 +1097,7 @@ describe('Personally Identifiable Information', () => { .then(loggedInUser => (anotherUser = loggedInUser)) .then(() => Parse.User.logIn(anotherUser.get('username'), 'abc')) .then(() => - anotherUser - .set('email', ANOTHER_EMAIL) - .set('zip', ZIP) - .set('ssn', SSN) - .save() + anotherUser.set('email', ANOTHER_EMAIL).set('zip', ZIP).set('ssn', SSN).save() ) .then(() => done()); }); @@ -1168,9 +1132,7 @@ describe('Personally Identifiable Information', () => { new Parse.Query(Parse.User) .find() .then(fetchedUsers => { - const notCurrentUser = fetchedUsers.find( - u => u.id !== anotherUser.id - ); + const notCurrentUser = fetchedUsers.find(u => u.id !== anotherUser.id); expect(notCurrentUser.get('email')).toBe(undefined); expect(notCurrentUser.get('zip')).toBe(undefined); expect(notCurrentUser.get('ssn')).toBe(undefined); @@ -1183,9 +1145,7 @@ describe('Personally Identifiable Information', () => { new Parse.Query(Parse.User) .find() .then(fetchedUsers => { - const currentUser = fetchedUsers.find( - u => u.id === anotherUser.id - ); + const currentUser = fetchedUsers.find(u => u.id === anotherUser.id); expect(currentUser.get('email')).toBe(ANOTHER_EMAIL); expect(currentUser.get('zip')).toBe(ZIP); expect(currentUser.get('ssn')).toBe(SSN); diff --git a/spec/ValidationAndPasswordsReset.spec.js b/spec/ValidationAndPasswordsReset.spec.js index 8be07b3f..94d9793a 100644 --- a/spec/ValidationAndPasswordsReset.spec.js +++ b/spec/ValidationAndPasswordsReset.spec.js @@ -22,9 +22,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { expect(config.verifyEmailSuccessURL).toEqual('myVerifyEmailSuccess'); expect(config.choosePasswordURL).toEqual('myChoosePassword'); expect(config.passwordResetSuccessURL).toEqual('myPasswordResetSuccess'); - expect(config.parseFrameURL).toEqual( - 'http://example.com/handle-parse-iframe' - ); + expect(config.parseFrameURL).toEqual('http://example.com/handle-parse-iframe'); expect(config.verifyEmailURL).toEqual( 'https://my.public.server.com/1/apps/test/verify_email' ); @@ -116,7 +114,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { .then(() => { expect(user.get('emailVerified')).toEqual(false); // Wait as on update email, we need to fetch the username - setTimeout(function() { + setTimeout(function () { expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled(); done(); }, 200); @@ -152,7 +150,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { await user.fetch(); expect(user.get('emailVerified')).toEqual(false); // Wait as on update email, we need to fetch the username - setTimeout(function() { + setTimeout(function () { expect(emailAdapter.sendVerificationEmail).toHaveBeenCalled(); done(); }, 200); @@ -161,12 +159,10 @@ describe('Custom Pages, Email Verification, Password Reset', () => { it('does send with a simple adapter', done => { let calls = 0; const emailAdapter = { - sendMail: function(options) { + sendMail: function (options) { expect(options.to).toBe('testSendSimpleAdapter@parse.com'); if (calls == 0) { - expect(options.subject).toEqual( - 'Please verify your e-mail for My Cool App' - ); + expect(options.subject).toEqual('Please verify your e-mail for My Cool App'); expect(options.text.match(/verify_email/)).not.toBe(null); } else if (calls == 1) { expect(options.subject).toEqual('Password Reset for My Cool App'); @@ -194,9 +190,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { return user.save(); }) .then(() => { - return Parse.User.requestPasswordReset( - 'testSendSimpleAdapter@parse.com' - ).catch(() => { + return Parse.User.requestPasswordReset('testSendSimpleAdapter@parse.com').catch(() => { fail('Should not fail requesting a password'); done(); }); @@ -368,9 +362,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { user.set('email', 'testInvalidConfig@parse.com'); user .signUp(null) - .then(() => - Parse.User.requestPasswordReset('testInvalidConfig@parse.com') - ) + .then(() => Parse.User.requestPasswordReset('testInvalidConfig@parse.com')) .then( () => { fail('sending password reset email should not have succeeded'); @@ -406,9 +398,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { user.set('email', 'testInvalidConfig@parse.com'); user .signUp(null) - .then(() => - Parse.User.requestPasswordReset('testInvalidConfig@parse.com') - ) + .then(() => Parse.User.requestPasswordReset('testInvalidConfig@parse.com')) .then( () => { fail('sending password reset email should not have succeeded'); @@ -441,9 +431,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { user.set('email', 'testInvalidConfig@parse.com'); user .signUp(null) - .then(() => - Parse.User.requestPasswordReset('testInvalidConfig@parse.com') - ) + .then(() => Parse.User.requestPasswordReset('testInvalidConfig@parse.com')) .then( () => { fail('sending password reset email should not have succeeded'); @@ -480,9 +468,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { user.set('email', 'testInvalidConfig@parse.com'); user .signUp(null) - .then(() => - Parse.User.requestPasswordReset('testInvalidConfig@parse.com') - ) + .then(() => Parse.User.requestPasswordReset('testInvalidConfig@parse.com')) .then( () => { done(); @@ -503,7 +489,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { fromAddress: 'parse@example.com', apiKey: 'k', domain: 'd', - sendMail: function(options) { + sendMail: function (options) { expect(options.to).toEqual('testValidConfig@parse.com'); return Promise.resolve(); }, @@ -524,9 +510,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { user.setUsername('testValidConfig@parse.com'); user .signUp(null) - .then(() => - Parse.User.requestPasswordReset('testValidConfig@parse.com') - ) + .then(() => Parse.User.requestPasswordReset('testValidConfig@parse.com')) .then( () => { expect(adapter.sendMail).toHaveBeenCalled(); @@ -683,8 +667,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { publicServerURL: 'http://localhost:8378/1', }).then(() => { request({ - url: - 'http://localhost:8378/1/apps/test/verify_email?token=asdfasdf&username=sadfasga', + url: 'http://localhost:8378/1/apps/test/verify_email?token=asdfasdf&username=sadfasga', followRedirects: false, }).then(response => { expect(response.status).toEqual(302); @@ -729,8 +712,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { const emailAdapter = { sendVerificationEmail: () => { request({ - url: - 'http://localhost:8378/1/apps/test/verify_email?token=invalid&username=zxcv', + url: 'http://localhost:8378/1/apps/test/verify_email?token=invalid&username=zxcv', followRedirects: false, }).then(response => { expect(response.status).toEqual(302); @@ -757,7 +739,7 @@ describe('Custom Pages, Email Verification, Password Reset', () => { user.set('email', 'user@parse.com'); user.signUp(null, { success: () => {}, - error: function() { + error: function () { fail('Failed to save user'); done(); }, @@ -862,15 +844,10 @@ describe('Custom Pages, Email Verification, Password Reset', () => { ); Parse.User.logIn('zxcv', 'hello').then( - function() { + function () { const config = Config.get('test'); config.database.adapter - .find( - '_User', - { fields: {} }, - { username: 'zxcv' }, - { limit: 1 } - ) + .find('_User', { fields: {} }, { username: 'zxcv' }, { limit: 1 }) .then(results => { // _perishable_token should be unset after reset password expect(results.length).toEqual(1); diff --git a/spec/VerifyUserPassword.spec.js b/spec/VerifyUserPassword.spec.js index c4098567..e77657b8 100644 --- a/spec/VerifyUserPassword.spec.js +++ b/spec/VerifyUserPassword.spec.js @@ -3,10 +3,8 @@ const request = require('../lib/request'); const MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions'); -const verifyPassword = function(login, password, isEmail = false) { - const body = !isEmail - ? { username: login, password } - : { email: login, password }; +const verifyPassword = function (login, password, isEmail = false) { + const body = !isEmail ? { username: login, password } : { email: login, password }; return request({ url: Parse.serverURL + '/verifyPassword', headers: { @@ -19,7 +17,7 @@ const verifyPassword = function(login, password, isEmail = false) { .catch(err => err); }; -const isAccountLockoutError = function(username, password, duration, waitTime) { +const isAccountLockoutError = function (username, password, duration, waitTime) { return new Promise((resolve, reject) => { setTimeout(() => { Parse.User.logIn(username, password) @@ -81,9 +79,7 @@ describe('Verify User Password', () => { }) .catch(err => { expect(err.status).toBe(404); - expect(err.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(err.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }); }); @@ -114,9 +110,7 @@ describe('Verify User Password', () => { }) .catch(err => { expect(err.status).toBe(400); - expect(err.text).toMatch( - '{"code":200,"error":"username/email is required."}' - ); + expect(err.text).toMatch('{"code":200,"error":"username/email is required."}'); done(); }); }); @@ -147,9 +141,7 @@ describe('Verify User Password', () => { }) .catch(err => { expect(err.status).toBe(400); - expect(err.text).toMatch( - '{"code":200,"error":"username/email is required."}' - ); + expect(err.text).toMatch('{"code":200,"error":"username/email is required."}'); done(); }); }); @@ -166,9 +158,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(400); - expect(res.text).toMatch( - '{"code":200,"error":"username/email is required."}' - ); + expect(res.text).toMatch('{"code":200,"error":"username/email is required."}'); done(); }) .catch(err => { @@ -189,9 +179,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(400); - expect(res.text).toMatch( - '{"code":200,"error":"username/email is required."}' - ); + expect(res.text).toMatch('{"code":200,"error":"username/email is required."}'); done(); }) .catch(err => { @@ -212,9 +200,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(400); - expect(res.text).toMatch( - '{"code":201,"error":"password is required."}' - ); + expect(res.text).toMatch('{"code":201,"error":"password is required."}'); done(); }) .catch(err => { @@ -235,9 +221,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(404); - expect(res.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(res.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }) .catch(err => { @@ -258,9 +242,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(404); - expect(res.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(res.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }) .catch(err => { @@ -281,9 +263,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(404); - expect(res.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(res.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }) .catch(err => { @@ -304,9 +284,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(404); - expect(res.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(res.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }) .catch(err => { @@ -327,9 +305,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(404); - expect(res.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(res.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }) .catch(err => { @@ -341,9 +317,7 @@ describe('Verify User Password', () => { verifyPassword('mytestuser', 'mypass') .then(res => { expect(res.status).toBe(404); - expect(res.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(res.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }) .catch(err => { @@ -355,9 +329,7 @@ describe('Verify User Password', () => { verifyPassword('my@user.com', 'mypass', true) .then(res => { expect(res.status).toBe(404); - expect(res.text).toMatch( - '{"code":101,"error":"Invalid username/password."}' - ); + expect(res.text).toMatch('{"code":101,"error":"Invalid username/password."}'); done(); }) .catch(err => { @@ -390,9 +362,7 @@ describe('Verify User Password', () => { }) .then(res => { expect(res.status).toBe(400); - expect(res.text).toMatch( - '{"code":205,"error":"User email is not verified."}' - ); + expect(res.text).toMatch('{"code":205,"error":"User email is not verified."}'); done(); }) .catch(err => { @@ -433,10 +403,7 @@ describe('Verify User Password', () => { done(); }) .catch(err => { - fail( - 'lock account after failed login attempts test failed: ' + - JSON.stringify(err) - ); + fail('lock account after failed login attempts test failed: ' + JSON.stringify(err)); done(); }); }); @@ -469,12 +436,8 @@ describe('Verify User Password', () => { const res = response.data; expect(typeof res).toBe('object'); expect(typeof res['objectId']).toEqual('string'); - expect( - Object.prototype.hasOwnProperty.call(res, 'sessionToken') - ).toEqual(false); - expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual( - false - ); + expect(Object.prototype.hasOwnProperty.call(res, 'sessionToken')).toEqual(false); + expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual(false); done(); }) .catch(err => { @@ -497,12 +460,8 @@ describe('Verify User Password', () => { const res = response.data; expect(typeof res).toBe('object'); expect(typeof res['objectId']).toEqual('string'); - expect( - Object.prototype.hasOwnProperty.call(res, 'sessionToken') - ).toEqual(false); - expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual( - false - ); + expect(Object.prototype.hasOwnProperty.call(res, 'sessionToken')).toEqual(false); + expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual(false); done(); }); }); @@ -521,12 +480,8 @@ describe('Verify User Password', () => { const res = response.data; expect(typeof res).toBe('object'); expect(typeof res['objectId']).toEqual('string'); - expect( - Object.prototype.hasOwnProperty.call(res, 'sessionToken') - ).toEqual(false); - expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual( - false - ); + expect(Object.prototype.hasOwnProperty.call(res, 'sessionToken')).toEqual(false); + expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual(false); done(); }); }); @@ -556,12 +511,8 @@ describe('Verify User Password', () => { expect(typeof res).toBe('string'); const body = JSON.parse(res); expect(typeof body['objectId']).toEqual('string'); - expect( - Object.prototype.hasOwnProperty.call(body, 'sessionToken') - ).toEqual(false); - expect(Object.prototype.hasOwnProperty.call(body, 'password')).toEqual( - false - ); + expect(Object.prototype.hasOwnProperty.call(body, 'sessionToken')).toEqual(false); + expect(Object.prototype.hasOwnProperty.call(body, 'password')).toEqual(false); done(); }); }); @@ -591,12 +542,8 @@ describe('Verify User Password', () => { expect(typeof res).toBe('string'); const body = JSON.parse(res); expect(typeof body['objectId']).toEqual('string'); - expect( - Object.prototype.hasOwnProperty.call(body, 'sessionToken') - ).toEqual(false); - expect(Object.prototype.hasOwnProperty.call(body, 'password')).toEqual( - false - ); + expect(Object.prototype.hasOwnProperty.call(body, 'sessionToken')).toEqual(false); + expect(Object.prototype.hasOwnProperty.call(body, 'password')).toEqual(false); done(); }); }); @@ -623,12 +570,8 @@ describe('Verify User Password', () => { const res = response.data; expect(typeof res).toBe('object'); expect(typeof res['objectId']).toEqual('string'); - expect( - Object.prototype.hasOwnProperty.call(res, 'sessionToken') - ).toEqual(false); - expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual( - false - ); + expect(Object.prototype.hasOwnProperty.call(res, 'sessionToken')).toEqual(false); + expect(Object.prototype.hasOwnProperty.call(res, 'password')).toEqual(false); done(); }); }); diff --git a/spec/WinstonLoggerAdapter.spec.js b/spec/WinstonLoggerAdapter.spec.js index c0eddf30..7f69660e 100644 --- a/spec/WinstonLoggerAdapter.spec.js +++ b/spec/WinstonLoggerAdapter.spec.js @@ -19,9 +19,7 @@ describe('info logs', () => { if (results.length == 0) { fail('The adapter should return non-empty results'); } else { - const log = results.find( - x => x.message === 'testing info logs with 1234' - ); + const log = results.find(x => x.message === 'testing info logs with 1234'); expect(log.level).toEqual('info'); } // Check the error log @@ -33,9 +31,7 @@ describe('info logs', () => { level: 'error', }, errors => { - const log = errors.find( - x => x.message === 'testing info logs with 1234' - ); + const log = errors.find(x => x.message === 'testing info logs with 1234'); expect(log).toBeUndefined(); done(); } @@ -54,15 +50,15 @@ describe('info logs', () => { order: 'desc', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing info logs with replace' - ); + const log = results.find(x => x.message === 'testing info logs with replace'); expect(log); }); it('info logs should interpolate json', async () => { const winstonLoggerAdapter = new WinstonLoggerAdapter(); - winstonLoggerAdapter.log('info', 'testing info logs with %j', { hello: 'world' }); + winstonLoggerAdapter.log('info', 'testing info logs with %j', { + hello: 'world', + }); const results = await winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), size: 100, @@ -70,9 +66,7 @@ describe('info logs', () => { order: 'desc', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing info logs with {"hello":"world"}' - ); + const log = results.find(x => x.message === 'testing info logs with {"hello":"world"}'); expect(log); }); @@ -86,9 +80,7 @@ describe('info logs', () => { order: 'desc', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing info logs with 123' - ); + const log = results.find(x => x.message === 'testing info logs with 123'); expect(log); }); }); @@ -140,15 +132,15 @@ describe('error logs', () => { level: 'error', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing error logs with replace' - ); + const log = results.find(x => x.message === 'testing error logs with replace'); expect(log); }); it('error logs should interpolate json', async () => { const winstonLoggerAdapter = new WinstonLoggerAdapter(); - winstonLoggerAdapter.log('error', 'testing error logs with %j', { hello: 'world' }); + winstonLoggerAdapter.log('error', 'testing error logs with %j', { + hello: 'world', + }); const results = await winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), size: 100, @@ -156,9 +148,7 @@ describe('error logs', () => { order: 'desc', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing error logs with {"hello":"world"}' - ); + const log = results.find(x => x.message === 'testing error logs with {"hello":"world"}'); expect(log); }); @@ -172,9 +162,7 @@ describe('error logs', () => { order: 'desc', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing error logs with 123' - ); + const log = results.find(x => x.message === 'testing error logs with 123'); expect(log); }); }); @@ -228,27 +216,23 @@ describe('verbose logs', () => { it('verbose logs should interpolate string', async () => { await reconfigureServer({ verbose: true }); const winstonLoggerAdapter = new WinstonLoggerAdapter(); - winstonLoggerAdapter.log( - 'verbose', - 'testing verbose logs with %s', - 'replace' - ); + winstonLoggerAdapter.log('verbose', 'testing verbose logs with %s', 'replace'); const results = await winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), size: 100, level: 'verbose', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing verbose logs with replace' - ); + const log = results.find(x => x.message === 'testing verbose logs with replace'); expect(log); }); it('verbose logs should interpolate json', async () => { await reconfigureServer({ verbose: true }); const winstonLoggerAdapter = new WinstonLoggerAdapter(); - winstonLoggerAdapter.log('verbose', 'testing verbose logs with %j', { hello: 'world' }); + winstonLoggerAdapter.log('verbose', 'testing verbose logs with %j', { + hello: 'world', + }); const results = await winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), size: 100, @@ -256,9 +240,7 @@ describe('verbose logs', () => { order: 'desc', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing verbose logs with {"hello":"world"}' - ); + const log = results.find(x => x.message === 'testing verbose logs with {"hello":"world"}'); expect(log); }); @@ -273,9 +255,7 @@ describe('verbose logs', () => { order: 'desc', }); expect(results.length > 0).toBeTruthy(); - const log = results.find( - x => x.message === 'testing verbose logs with 123' - ); + const log = results.find(x => x.message === 'testing verbose logs with 123'); expect(log); }); }); diff --git a/spec/batch.spec.js b/spec/batch.spec.js index 9d88902d..d12eb481 100644 --- a/spec/batch.spec.js +++ b/spec/batch.spec.js @@ -19,9 +19,7 @@ const headers = { describe('batch', () => { it('should return the proper url', () => { - const internalURL = batch.makeBatchRoutingPathFunction(originalURL)( - '/parse/classes/Object' - ); + const internalURL = batch.makeBatchRoutingPathFunction(originalURL)('/parse/classes/Object'); expect(internalURL).toEqual('/classes/Object'); }); @@ -102,10 +100,7 @@ describe('batch', () => { expect(databaseAdapter.createObject.calls.count()).toBe(2); expect(databaseAdapter.createObject.calls.argsFor(0)[3]).toEqual(null); expect(databaseAdapter.createObject.calls.argsFor(1)[3]).toEqual(null); - expect(results.map(result => result.get('key')).sort()).toEqual([ - 'value1', - 'value2', - ]); + expect(results.map(result => result.get('key')).sort()).toEqual(['value1', 'value2']); done(); }); }); @@ -144,10 +139,7 @@ describe('batch', () => { expect(databaseAdapter.createObject.calls.count()).toBe(2); expect(databaseAdapter.createObject.calls.argsFor(0)[3]).toEqual(null); expect(databaseAdapter.createObject.calls.argsFor(1)[3]).toEqual(null); - expect(results.map(result => result.get('key')).sort()).toEqual([ - 'value1', - 'value2', - ]); + expect(results.map(result => result.get('key')).sort()).toEqual(['value1', 'value2']); done(); }); }); @@ -219,9 +211,10 @@ describe('batch', () => { expect(databaseAdapter.createObject.calls.argsFor(0)[3]).toBe( databaseAdapter.createObject.calls.argsFor(1)[3] ); - expect( - results.map(result => result.get('key')).sort() - ).toEqual(['value1', 'value2']); + expect(results.map(result => result.get('key')).sort()).toEqual([ + 'value1', + 'value2', + ]); done(); }); }); @@ -518,10 +511,7 @@ describe('batch', () => { const query = new Parse.Query('MyObject'); const results = await query.find(); - expect(results.map(result => result.get('key')).sort()).toEqual([ - 'value1', - 'value2', - ]); + expect(results.map(result => result.get('key')).sort()).toEqual(['value1', 'value2']); const query2 = new Parse.Query('MyObject2'); const results2 = await query2.find(); @@ -529,10 +519,7 @@ describe('batch', () => { const query3 = new Parse.Query('MyObject3'); const results3 = await query3.find(); - expect(results3.map(result => result.get('key')).sort()).toEqual([ - 'value1', - 'value2', - ]); + expect(results3.map(result => result.get('key')).sort()).toEqual(['value1', 'value2']); expect(databaseAdapter.createObject.calls.count()).toBe(13); let transactionalSession; diff --git a/spec/cryptoUtils.spec.js b/spec/cryptoUtils.spec.js index a3b1c697..8270e052 100644 --- a/spec/cryptoUtils.spec.js +++ b/spec/cryptoUtils.spec.js @@ -27,9 +27,7 @@ describe('randomString', () => { }); it('returns unique results', () => { - expect(givesUniqueResults(() => cryptoUtils.randomString(10), 100)).toBe( - true - ); + expect(givesUniqueResults(() => cryptoUtils.randomString(10), 100)).toBe(true); }); }); @@ -52,9 +50,7 @@ describe('randomHexString', () => { }); it('returns unique results', () => { - expect(givesUniqueResults(() => cryptoUtils.randomHexString(20), 100)).toBe( - true - ); + expect(givesUniqueResults(() => cryptoUtils.randomHexString(20), 100)).toBe(true); }); }); diff --git a/spec/defaultGraphQLTypes.spec.js b/spec/defaultGraphQLTypes.spec.js index e702ae0b..4e3e3114 100644 --- a/spec/defaultGraphQLTypes.spec.js +++ b/spec/defaultGraphQLTypes.spec.js @@ -35,14 +35,9 @@ function createObjectField(name, value) { describe('defaultGraphQLTypes', () => { describe('TypeValidationError', () => { it('should be an error with specific message', () => { - const typeValidationError = new TypeValidationError( - 'somevalue', - 'sometype' - ); + const typeValidationError = new TypeValidationError('somevalue', 'sometype'); expect(typeValidationError).toEqual(jasmine.any(Error)); - expect(typeValidationError.message).toEqual( - 'somevalue is not a valid sometype' - ); + expect(typeValidationError.message).toEqual('somevalue is not a valid sometype'); }); }); @@ -53,18 +48,10 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not a string', () => { - expect(() => parseStringValue()).toThrow( - jasmine.stringMatching('is not a valid String') - ); - expect(() => parseStringValue({})).toThrow( - jasmine.stringMatching('is not a valid String') - ); - expect(() => parseStringValue([])).toThrow( - jasmine.stringMatching('is not a valid String') - ); - expect(() => parseStringValue(123)).toThrow( - jasmine.stringMatching('is not a valid String') - ); + expect(() => parseStringValue()).toThrow(jasmine.stringMatching('is not a valid String')); + expect(() => parseStringValue({})).toThrow(jasmine.stringMatching('is not a valid String')); + expect(() => parseStringValue([])).toThrow(jasmine.stringMatching('is not a valid String')); + expect(() => parseStringValue(123)).toThrow(jasmine.stringMatching('is not a valid String')); }); }); @@ -75,27 +62,15 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not a string', () => { - expect(() => parseIntValue()).toThrow( - jasmine.stringMatching('is not a valid Int') - ); - expect(() => parseIntValue({})).toThrow( - jasmine.stringMatching('is not a valid Int') - ); - expect(() => parseIntValue([])).toThrow( - jasmine.stringMatching('is not a valid Int') - ); - expect(() => parseIntValue(123)).toThrow( - jasmine.stringMatching('is not a valid Int') - ); + expect(() => parseIntValue()).toThrow(jasmine.stringMatching('is not a valid Int')); + expect(() => parseIntValue({})).toThrow(jasmine.stringMatching('is not a valid Int')); + expect(() => parseIntValue([])).toThrow(jasmine.stringMatching('is not a valid Int')); + expect(() => parseIntValue(123)).toThrow(jasmine.stringMatching('is not a valid Int')); }); it('should fail if not an integer string', () => { - expect(() => parseIntValue('a123')).toThrow( - jasmine.stringMatching('is not a valid Int') - ); - expect(() => parseIntValue('123.4')).toThrow( - jasmine.stringMatching('is not a valid Int') - ); + expect(() => parseIntValue('a123')).toThrow(jasmine.stringMatching('is not a valid Int')); + expect(() => parseIntValue('123.4')).toThrow(jasmine.stringMatching('is not a valid Int')); }); }); @@ -106,21 +81,13 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not a string', () => { - expect(() => parseFloatValue()).toThrow( - jasmine.stringMatching('is not a valid Float') - ); - expect(() => parseFloatValue({})).toThrow( - jasmine.stringMatching('is not a valid Float') - ); - expect(() => parseFloatValue([])).toThrow( - jasmine.stringMatching('is not a valid Float') - ); + expect(() => parseFloatValue()).toThrow(jasmine.stringMatching('is not a valid Float')); + expect(() => parseFloatValue({})).toThrow(jasmine.stringMatching('is not a valid Float')); + expect(() => parseFloatValue([])).toThrow(jasmine.stringMatching('is not a valid Float')); }); it('should fail if not a float string', () => { - expect(() => parseIntValue('a123')).toThrow( - jasmine.stringMatching('is not a valid Int') - ); + expect(() => parseIntValue('a123')).toThrow(jasmine.stringMatching('is not a valid Int')); }); }); @@ -133,15 +100,9 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not a boolean', () => { - expect(() => parseBooleanValue()).toThrow( - jasmine.stringMatching('is not a valid Boolean') - ); - expect(() => parseBooleanValue({})).toThrow( - jasmine.stringMatching('is not a valid Boolean') - ); - expect(() => parseBooleanValue([])).toThrow( - jasmine.stringMatching('is not a valid Boolean') - ); + expect(() => parseBooleanValue()).toThrow(jasmine.stringMatching('is not a valid Boolean')); + expect(() => parseBooleanValue({})).toThrow(jasmine.stringMatching('is not a valid Boolean')); + expect(() => parseBooleanValue([])).toThrow(jasmine.stringMatching('is not a valid Boolean')); expect(() => parseBooleanValue(123)).toThrow( jasmine.stringMatching('is not a valid Boolean') ); @@ -159,18 +120,10 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not a string', () => { - expect(() => parseDateIsoValue()).toThrow( - jasmine.stringMatching('is not a valid Date') - ); - expect(() => parseDateIsoValue({})).toThrow( - jasmine.stringMatching('is not a valid Date') - ); - expect(() => parseDateIsoValue([])).toThrow( - jasmine.stringMatching('is not a valid Date') - ); - expect(() => parseDateIsoValue(123)).toThrow( - jasmine.stringMatching('is not a valid Date') - ); + expect(() => parseDateIsoValue()).toThrow(jasmine.stringMatching('is not a valid Date')); + expect(() => parseDateIsoValue({})).toThrow(jasmine.stringMatching('is not a valid Date')); + expect(() => parseDateIsoValue([])).toThrow(jasmine.stringMatching('is not a valid Date')); + expect(() => parseDateIsoValue(123)).toThrow(jasmine.stringMatching('is not a valid Date')); }); it('should fail if not a date string', () => { @@ -321,18 +274,12 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an array', () => { - expect(() => parseListValues()).toThrow( - jasmine.stringMatching('is not a valid List') - ); - expect(() => parseListValues({})).toThrow( - jasmine.stringMatching('is not a valid List') - ); + expect(() => parseListValues()).toThrow(jasmine.stringMatching('is not a valid List')); + expect(() => parseListValues({})).toThrow(jasmine.stringMatching('is not a valid List')); expect(() => parseListValues('some string')).toThrow( jasmine.stringMatching('is not a valid List') ); - expect(() => parseListValues(123)).toThrow( - jasmine.stringMatching('is not a valid List') - ); + expect(() => parseListValues(123)).toThrow(jasmine.stringMatching('is not a valid List')); }); }); @@ -356,18 +303,12 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an array', () => { - expect(() => parseObjectFields()).toThrow( - jasmine.stringMatching('is not a valid Object') - ); - expect(() => parseObjectFields({})).toThrow( - jasmine.stringMatching('is not a valid Object') - ); + expect(() => parseObjectFields()).toThrow(jasmine.stringMatching('is not a valid Object')); + expect(() => parseObjectFields({})).toThrow(jasmine.stringMatching('is not a valid Object')); expect(() => parseObjectFields('some string')).toThrow( jasmine.stringMatching('is not a valid Object') ); - expect(() => parseObjectFields(123)).toThrow( - jasmine.stringMatching('is not a valid Object') - ); + expect(() => parseObjectFields(123)).toThrow(jasmine.stringMatching('is not a valid Object')); }); }); @@ -399,9 +340,7 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => parseLiteral({})).toThrow( - jasmine.stringMatching('is not a valid Date') - ); + expect(() => parseLiteral({})).toThrow(jasmine.stringMatching('is not a valid Date')); expect(() => parseLiteral( createValue(Kind.OBJECT, undefined, undefined, [ @@ -410,12 +349,8 @@ describe('defaultGraphQLTypes', () => { ]) ) ).toThrow(jasmine.stringMatching('is not a valid Date')); - expect(() => parseLiteral([])).toThrow( - jasmine.stringMatching('is not a valid Date') - ); - expect(() => parseLiteral(123)).toThrow( - jasmine.stringMatching('is not a valid Date') - ); + expect(() => parseLiteral([])).toThrow(jasmine.stringMatching('is not a valid Date')); + expect(() => parseLiteral(123)).toThrow(jasmine.stringMatching('is not a valid Date')); }); }); @@ -439,9 +374,7 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => parseValue({})).toThrow( - jasmine.stringMatching('is not a valid Date') - ); + expect(() => parseValue({})).toThrow(jasmine.stringMatching('is not a valid Date')); expect(() => parseValue({ __type: 'Foo', @@ -454,12 +387,8 @@ describe('defaultGraphQLTypes', () => { iso: 'foo', }) ).toThrow(jasmine.stringMatching('is not a valid Date')); - expect(() => parseValue([])).toThrow( - jasmine.stringMatching('is not a valid Date') - ); - expect(() => parseValue(123)).toThrow( - jasmine.stringMatching('is not a valid Date') - ); + expect(() => parseValue([])).toThrow(jasmine.stringMatching('is not a valid Date')); + expect(() => parseValue(123)).toThrow(jasmine.stringMatching('is not a valid Date')); }); }); @@ -486,21 +415,15 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => serialize({})).toThrow( - jasmine.stringMatching('is not a valid Date') - ); + expect(() => serialize({})).toThrow(jasmine.stringMatching('is not a valid Date')); expect(() => serialize({ __type: 'Foo', iso: '2019-05-09T23:12:00.000Z', }) ).toThrow(jasmine.stringMatching('is not a valid Date')); - expect(() => serialize([])).toThrow( - jasmine.stringMatching('is not a valid Date') - ); - expect(() => serialize(123)).toThrow( - jasmine.stringMatching('is not a valid Date') - ); + expect(() => serialize([])).toThrow(jasmine.stringMatching('is not a valid Date')); + expect(() => serialize(123)).toThrow(jasmine.stringMatching('is not a valid Date')); }); }); }); @@ -531,9 +454,7 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => parseLiteral({})).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); + expect(() => parseLiteral({})).toThrow(jasmine.stringMatching('is not a valid Bytes')); expect(() => parseLiteral( createValue(Kind.OBJECT, undefined, undefined, [ @@ -542,12 +463,8 @@ describe('defaultGraphQLTypes', () => { ]) ) ).toThrow(jasmine.stringMatching('is not a valid Bytes')); - expect(() => parseLiteral([])).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); - expect(() => parseLiteral(123)).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); + expect(() => parseLiteral([])).toThrow(jasmine.stringMatching('is not a valid Bytes')); + expect(() => parseLiteral(123)).toThrow(jasmine.stringMatching('is not a valid Bytes')); }); }); @@ -570,21 +487,15 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => parseValue({})).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); + expect(() => parseValue({})).toThrow(jasmine.stringMatching('is not a valid Bytes')); expect(() => parseValue({ __type: 'Foo', base64: 'bytesContent', }) ).toThrow(jasmine.stringMatching('is not a valid Bytes')); - expect(() => parseValue([])).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); - expect(() => parseValue(123)).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); + expect(() => parseValue([])).toThrow(jasmine.stringMatching('is not a valid Bytes')); + expect(() => parseValue(123)).toThrow(jasmine.stringMatching('is not a valid Bytes')); }); }); @@ -606,21 +517,15 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => serialize({})).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); + expect(() => serialize({})).toThrow(jasmine.stringMatching('is not a valid Bytes')); expect(() => serialize({ __type: 'Foo', base64: 'bytesContent', }) ).toThrow(jasmine.stringMatching('is not a valid Bytes')); - expect(() => serialize([])).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); - expect(() => serialize(123)).toThrow( - jasmine.stringMatching('is not a valid Bytes') - ); + expect(() => serialize([])).toThrow(jasmine.stringMatching('is not a valid Bytes')); + expect(() => serialize(123)).toThrow(jasmine.stringMatching('is not a valid Bytes')); }); }); }); @@ -653,9 +558,7 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => parseLiteral({})).toThrow( - jasmine.stringMatching('is not a valid File') - ); + expect(() => parseLiteral({})).toThrow(jasmine.stringMatching('is not a valid File')); expect(() => parseLiteral( createValue(Kind.OBJECT, undefined, undefined, [ @@ -665,12 +568,8 @@ describe('defaultGraphQLTypes', () => { ]) ) ).toThrow(jasmine.stringMatching('is not a valid File')); - expect(() => parseLiteral([])).toThrow( - jasmine.stringMatching('is not a valid File') - ); - expect(() => parseLiteral(123)).toThrow( - jasmine.stringMatching('is not a valid File') - ); + expect(() => parseLiteral([])).toThrow(jasmine.stringMatching('is not a valid File')); + expect(() => parseLiteral(123)).toThrow(jasmine.stringMatching('is not a valid File')); }); }); @@ -693,9 +592,7 @@ describe('defaultGraphQLTypes', () => { }); it('should fail if not an valid object or string', () => { - expect(() => serialize({})).toThrow( - jasmine.stringMatching('is not a valid File') - ); + expect(() => serialize({})).toThrow(jasmine.stringMatching('is not a valid File')); expect(() => serialize({ __type: 'Foo', @@ -703,12 +600,8 @@ describe('defaultGraphQLTypes', () => { url: 'myurl', }) ).toThrow(jasmine.stringMatching('is not a valid File')); - expect(() => serialize([])).toThrow( - jasmine.stringMatching('is not a valid File') - ); - expect(() => serialize(123)).toThrow( - jasmine.stringMatching('is not a valid File') - ); + expect(() => serialize([])).toThrow(jasmine.stringMatching('is not a valid File')); + expect(() => serialize(123)).toThrow(jasmine.stringMatching('is not a valid File')); }); }); }); diff --git a/spec/dev.js b/spec/dev.js index 31425dec..c58879a5 100644 --- a/spec/dev.js +++ b/spec/dev.js @@ -35,10 +35,7 @@ module.exports = { * @param {string} [password='password'] - optional, defaults to "password" if not set; */ logIn: async (userObject, password) => { - return await Parse.User.logIn( - userObject.getUsername(), - password || 'password' - ); + return await Parse.User.logIn(userObject.getUsername(), password || 'password'); }, /** diff --git a/spec/features.spec.js b/spec/features.spec.js index 23b43c0b..f138fe4c 100644 --- a/spec/features.spec.js +++ b/spec/features.spec.js @@ -29,9 +29,7 @@ describe('features', () => { 'X-Parse-REST-API-Key': 'rest', }, }); - done.fail( - 'The serverInfo request should be rejected without the master key' - ); + done.fail('The serverInfo request should be rejected without the master key'); } catch (error) { expect(error.status).toEqual(403); expect(error.data.error).toEqual('unauthorized: master key is required'); diff --git a/spec/graphQLObjectsQueries.js b/spec/graphQLObjectsQueries.js index 40bdca8b..f8783c67 100644 --- a/spec/graphQLObjectsQueries.js +++ b/spec/graphQLObjectsQueries.js @@ -1,7 +1,5 @@ const { offsetToCursor } = require('graphql-relay'); -const { - calculateSkipAndLimit, -} = require('../lib/GraphQL/helpers/objectsQueries'); +const { calculateSkipAndLimit } = require('../lib/GraphQL/helpers/objectsQueries'); describe('GraphQL objectsQueries', () => { describe('calculateSkipAndLimit', () => { @@ -18,9 +16,9 @@ describe('GraphQL objectsQueries', () => { expect(() => calculateSkipAndLimit(1, 1, offsetToCursor(1), -1)).toThrow( jasmine.stringMatching('Last should be a positive number') ); - expect(() => - calculateSkipAndLimit(1, 1, offsetToCursor(1), 1, offsetToCursor(-1)) - ).toThrow(jasmine.stringMatching('Before is not a valid curso')); + expect(() => calculateSkipAndLimit(1, 1, offsetToCursor(1), 1, offsetToCursor(-1))).toThrow( + jasmine.stringMatching('Before is not a valid curso') + ); }); it('should work only with skip', () => { @@ -32,9 +30,7 @@ describe('GraphQL objectsQueries', () => { }); it('should work only with after', () => { - expect( - calculateSkipAndLimit(undefined, undefined, offsetToCursor(9)) - ).toEqual({ + expect(calculateSkipAndLimit(undefined, undefined, offsetToCursor(9))).toEqual({ skip: 10, limit: undefined, needToPreCount: false, @@ -59,13 +55,7 @@ describe('GraphQL objectsQueries', () => { it('if before cursor is less than skipped items, no objects will be returned', () => { expect( - calculateSkipAndLimit( - 10, - 30, - offsetToCursor(9), - undefined, - offsetToCursor(5) - ) + calculateSkipAndLimit(10, 30, offsetToCursor(9), undefined, offsetToCursor(5)) ).toEqual({ skip: 20, limit: 0, @@ -75,13 +65,7 @@ describe('GraphQL objectsQueries', () => { it('if before cursor is greater than returned objects set by limit, nothing is changed', () => { expect( - calculateSkipAndLimit( - 10, - 30, - offsetToCursor(9), - undefined, - offsetToCursor(100) - ) + calculateSkipAndLimit(10, 30, offsetToCursor(9), undefined, offsetToCursor(100)) ).toEqual({ skip: 20, limit: 30, @@ -91,13 +75,7 @@ describe('GraphQL objectsQueries', () => { it('if before cursor is less than returned objects set by limit, limit is adjusted', () => { expect( - calculateSkipAndLimit( - 10, - 30, - offsetToCursor(9), - undefined, - offsetToCursor(40) - ) + calculateSkipAndLimit(10, 30, offsetToCursor(9), undefined, offsetToCursor(40)) ).toEqual({ skip: 20, limit: 20, @@ -106,9 +84,7 @@ describe('GraphQL objectsQueries', () => { }); it('last should work alone but requires pre count', () => { - expect( - calculateSkipAndLimit(undefined, undefined, undefined, 10) - ).toEqual({ + expect(calculateSkipAndLimit(undefined, undefined, undefined, 10)).toEqual({ skip: undefined, limit: 10, needToPreCount: true, @@ -116,9 +92,7 @@ describe('GraphQL objectsQueries', () => { }); it('last should be adjusted to max limit', () => { - expect( - calculateSkipAndLimit(undefined, undefined, undefined, 10, undefined, 5) - ).toEqual({ + expect(calculateSkipAndLimit(undefined, undefined, undefined, 10, undefined, 5)).toEqual({ skip: undefined, limit: 5, needToPreCount: true, @@ -126,19 +100,15 @@ describe('GraphQL objectsQueries', () => { }); it('no objects will be returned if last is equal to 0', () => { - expect(calculateSkipAndLimit(undefined, undefined, undefined, 0)).toEqual( - { - skip: undefined, - limit: 0, - needToPreCount: false, - } - ); + expect(calculateSkipAndLimit(undefined, undefined, undefined, 0)).toEqual({ + skip: undefined, + limit: 0, + needToPreCount: false, + }); }); it('nothing changes if last is bigger than the calculared limit', () => { - expect( - calculateSkipAndLimit(10, 30, offsetToCursor(9), 30, offsetToCursor(40)) - ).toEqual({ + expect(calculateSkipAndLimit(10, 30, offsetToCursor(9), 30, offsetToCursor(40))).toEqual({ skip: 20, limit: 20, needToPreCount: false, @@ -146,9 +116,7 @@ describe('GraphQL objectsQueries', () => { }); it('If last is small than limit, new limit is calculated', () => { - expect( - calculateSkipAndLimit(10, 30, offsetToCursor(9), 10, offsetToCursor(40)) - ).toEqual({ + expect(calculateSkipAndLimit(10, 30, offsetToCursor(9), 10, offsetToCursor(40))).toEqual({ skip: 30, limit: 10, needToPreCount: false, diff --git a/spec/helper.js b/spec/helper.js index 393921c9..a7f6cf22 100644 --- a/spec/helper.js +++ b/spec/helper.js @@ -1,7 +1,6 @@ 'use strict'; // Sets up a Parse API server for testing. -jasmine.DEFAULT_TIMEOUT_INTERVAL = - process.env.PARSE_SERVER_TEST_TIMEOUT || 5000; +jasmine.DEFAULT_TIMEOUT_INTERVAL = process.env.PARSE_SERVER_TEST_TIMEOUT || 5000; global.on_db = (db, callback, elseCallback) => { if (process.env.PARSE_SERVER_TEST_DB == db) { @@ -29,15 +28,11 @@ const GridFSBucketAdapter = require('../lib/Adapters/Files/GridFSBucketAdapter') const FSAdapter = require('@parse/fs-files-adapter'); const PostgresStorageAdapter = require('../lib/Adapters/Storage/Postgres/PostgresStorageAdapter') .default; -const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter') - .default; -const RedisCacheAdapter = require('../lib/Adapters/Cache/RedisCacheAdapter') - .default; +const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; +const RedisCacheAdapter = require('../lib/Adapters/Cache/RedisCacheAdapter').default; -const mongoURI = - 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; -const postgresURI = - 'postgres://localhost:5432/parse_server_postgres_adapter_test_database'; +const mongoURI = 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase'; +const postgresURI = 'postgres://localhost:5432/parse_server_postgres_adapter_test_database'; let databaseAdapter; // need to bind for mocking mocha @@ -129,22 +124,17 @@ const reconfigureServer = changedConfiguration => { } try { let parseServer = undefined; - const newConfiguration = Object.assign( - {}, - defaultConfiguration, - changedConfiguration, - { - serverStartComplete: error => { - if (error) { - reject(error); - } else { - resolve(parseServer); - } - }, - mountPath: '/1', - port, - } - ); + const newConfiguration = Object.assign({}, defaultConfiguration, changedConfiguration, { + serverStartComplete: error => { + if (error) { + reject(error); + } else { + resolve(parseServer); + } + }, + mountPath: '/1', + port, + }); cache.clear(); parseServer = ParseServer.start(newConfiguration); parseServer.app.use(require('./testing-routes').router); @@ -181,10 +171,7 @@ beforeEach(done => { TestUtils.destroyAllDataPermanently(true) .catch(error => { // For tests that connect to their own mongo, there won't be any data to delete. - if ( - error.message === 'ns not found' || - error.message.startsWith('connect ECONNREFUSED') - ) { + if (error.message === 'ns not found' || error.message.startsWith('connect ECONNREFUSED')) { return; } else { fail(error); @@ -203,9 +190,7 @@ beforeEach(done => { afterEach(function (done) { const afterLogOut = () => { 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'); } TestUtils.destroyAllDataPermanently(true).then(done, done); }; diff --git a/spec/index.spec.js b/spec/index.spec.js index f0f4e9e2..1b542926 100644 --- a/spec/index.spec.js +++ b/spec/index.spec.js @@ -6,8 +6,7 @@ const ParseServer = require('../lib/index'); const Config = require('../lib/Config'); const express = require('express'); -const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter') - .default; +const MongoStorageAdapter = require('../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; describe('server', () => { it('requires a master key and app id', done => { @@ -39,8 +38,7 @@ describe('server', () => { request({ url: 'http://localhost:8378/1/classes/TestObject', headers: { - Authorization: - 'Basic ' + Buffer.from('test:' + 'test').toString('base64'), + Authorization: 'Basic ' + Buffer.from('test:' + 'test').toString('base64'), }, }).then(response => { expect(response.status).toEqual(200); @@ -54,9 +52,7 @@ describe('server', () => { request({ url: 'http://localhost:8378/1/classes/TestObject', headers: { - Authorization: - 'Basic ' + - Buffer.from('test:javascript-key=' + 'test').toString('base64'), + Authorization: 'Basic ' + Buffer.from('test:javascript-key=' + 'test').toString('base64'), }, }).then(response => { expect(response.status).toEqual(200); @@ -145,9 +141,7 @@ describe('server', () => { emailAdapter: '@parse/simple-mailgun-adapter', publicServerURL: 'http://localhost:8378/1', }).catch(error => { - expect(error).toEqual( - 'SimpleMailgunAdapter requires an API Key, domain, and fromAddress.' - ); + expect(error).toEqual('SimpleMailgunAdapter requires an API Key, domain, and fromAddress.'); done(); }); }); @@ -164,9 +158,7 @@ describe('server', () => { }, publicServerURL: 'http://localhost:8378/1', }).catch(error => { - expect(error).toEqual( - 'SimpleMailgunAdapter requires an API Key, domain, and fromAddress.' - ); + expect(error).toEqual('SimpleMailgunAdapter requires an API Key, domain, and fromAddress.'); done(); }); }); @@ -377,13 +369,9 @@ describe('server', () => { it('has createLiveQueryServer', done => { // original implementation through the factory - expect(typeof ParseServer.ParseServer.createLiveQueryServer).toEqual( - 'function' - ); + expect(typeof ParseServer.ParseServer.createLiveQueryServer).toEqual('function'); // For import calls - expect(typeof ParseServer.default.createLiveQueryServer).toEqual( - 'function' - ); + expect(typeof ParseServer.default.createLiveQueryServer).toEqual('function'); done(); }); @@ -399,13 +387,11 @@ describe('server', () => { }); it('properly gives publicServerURL when set', done => { - reconfigureServer({ publicServerURL: 'https://myserver.com/1' }).then( - () => { - const config = Config.get('test', 'http://localhost:8378/1'); - expect(config.mount).toEqual('https://myserver.com/1'); - done(); - } - ); + reconfigureServer({ publicServerURL: 'https://myserver.com/1' }).then(() => { + const config = Config.get('test', 'http://localhost:8378/1'); + expect(config.mount).toEqual('https://myserver.com/1'); + done(); + }); }); it('properly removes trailing slash in mount', done => { @@ -418,9 +404,7 @@ describe('server', () => { it('should throw when getting invalid mount', done => { reconfigureServer({ publicServerURL: 'blabla:/some' }).catch(error => { - expect(error).toEqual( - 'publicServerURL should be a valid HTTPS URL starting with https://' - ); + expect(error).toEqual('publicServerURL should be a valid HTTPS URL starting with https://'); done(); }); }); @@ -473,12 +457,10 @@ describe('server', () => { }); it('fails if you provides invalid ip in masterKeyIps', done => { - reconfigureServer({ masterKeyIps: ['invalidIp', '1.2.3.4'] }).catch( - error => { - expect(error).toEqual('Invalid ip in masterKeyIps: invalidIp'); - done(); - } - ); + reconfigureServer({ masterKeyIps: ['invalidIp', '1.2.3.4'] }).catch(error => { + expect(error).toEqual('Invalid ip in masterKeyIps: invalidIp'); + done(); + }); }); it('should succeed if you provide valid ip in masterKeyIps', done => { @@ -489,7 +471,7 @@ describe('server', () => { it('should load a middleware', done => { const obj = { - middleware: function(req, res, next) { + middleware: function (req, res, next) { next(); }, }; @@ -536,7 +518,7 @@ describe('server', () => { const jwt = require('jsonwebtoken'); reconfigureServer({ - auth: { google: {} } + auth: { google: {} }, }) .then(() => { const fakeClaim = { @@ -549,7 +531,10 @@ describe('server', () => { spyOn(jwt, 'decode').and.callFake(() => fakeDecodedToken); spyOn(jwt, 'verify').and.callFake(() => fakeClaim); const user = new Parse.User(); - user.linkWith('google', { authData: { id: 'the_user_id', id_token: 'the_token' }}) + user + .linkWith('google', { + authData: { id: 'the_user_id', id_token: 'the_token' }, + }) .then(done); }) .catch(done.fail); diff --git a/spec/rest.spec.js b/spec/rest.spec.js index 3dd8e1c1..56e406fa 100644 --- a/spec/rest.spec.js +++ b/spec/rest.spec.js @@ -16,11 +16,11 @@ describe('rest create', () => { database = config.database; }); - it('handles _id', (done) => { + it('handles _id', done => { rest .create(config, auth.nobody(config), 'Foo', {}) .then(() => database.adapter.find('Foo', { fields: {} }, {}, {})) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); const obj = results[0]; expect(typeof obj.objectId).toEqual('string'); @@ -30,12 +30,12 @@ describe('rest create', () => { }); }); - it('can use custom _id size', (done) => { + it('can use custom _id size', done => { config.objectIdSize = 20; rest .create(config, auth.nobody(config), 'Foo', {}) .then(() => database.adapter.find('Foo', { fields: {} }, {}, {})) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); const obj = results[0]; expect(typeof obj.objectId).toEqual('string'); @@ -79,17 +79,11 @@ describe('rest create', () => { const err = 'objectId must not be empty, null or undefined'; - expect(() => - rest.create(config, auth.nobody(config), 'MyClass', objIdEmpty) - ).toThrowError(err); + expect(() => rest.create(config, auth.nobody(config), 'MyClass', objIdEmpty)).toThrowError(err); - expect(() => - rest.create(config, auth.nobody(config), 'MyClass', objIdNull) - ).toThrowError(err); + expect(() => rest.create(config, auth.nobody(config), 'MyClass', objIdNull)).toThrowError(err); - expect(() => - rest.create(config, auth.nobody(config), 'MyClass', objIdUndef) - ).toThrowError(err); + expect(() => rest.create(config, auth.nobody(config), 'MyClass', objIdUndef)).toThrowError(err); }); it('should generate objectId when not set by client with allowCustomObjectId true', async () => { @@ -104,14 +98,14 @@ describe('rest create', () => { expect(objectId).toBeDefined(); }); - it('is backwards compatible when _id size changes', (done) => { + it('is backwards compatible when _id size changes', done => { rest .create(config, auth.nobody(config), 'Foo', { size: 10 }) .then(() => { config.objectIdSize = 20; return rest.find(config, auth.nobody(config), 'Foo', { size: 10 }); }) - .then((response) => { + .then(response => { expect(response.results.length).toEqual(1); expect(response.results[0].objectId.length).toEqual(10); return rest.update( @@ -125,7 +119,7 @@ describe('rest create', () => { .then(() => { return rest.find(config, auth.nobody(config), 'Foo', { size: 10 }); }) - .then((response) => { + .then(response => { expect(response.results.length).toEqual(1); expect(response.results[0].objectId.length).toEqual(10); expect(response.results[0].update).toEqual(20); @@ -135,14 +129,14 @@ describe('rest create', () => { config.objectIdSize = 10; return rest.find(config, auth.nobody(config), 'Foo', { size: 20 }); }) - .then((response) => { + .then(response => { expect(response.results.length).toEqual(1); expect(response.results[0].objectId.length).toEqual(20); done(); }); }); - it('handles array, object, date', (done) => { + it('handles array, object, date', done => { const now = new Date(); const obj = { array: [1, 2, 3], @@ -165,7 +159,7 @@ describe('rest create', () => { {} ) ) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); const mob = results[0]; expect(mob.array instanceof Array).toBe(true); @@ -176,7 +170,7 @@ describe('rest create', () => { }); }); - it('handles object and subdocument', (done) => { + it('handles object and subdocument', done => { const obj = { subdoc: { foo: 'bar', wu: 'tan' } }; Parse.Cloud.beforeSave('MyClass', function () { @@ -186,7 +180,7 @@ describe('rest create', () => { rest .create(config, auth.nobody(config), 'MyClass', obj) .then(() => database.adapter.find('MyClass', { fields: {} }, {}, {})) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); const mob = results[0]; expect(typeof mob.subdoc).toBe('object'); @@ -194,16 +188,10 @@ describe('rest create', () => { expect(mob.subdoc.wu).toBe('tan'); expect(typeof mob.objectId).toEqual('string'); const obj = { 'subdoc.wu': 'clan' }; - return rest.update( - config, - auth.nobody(config), - 'MyClass', - { objectId: mob.objectId }, - obj - ); + return rest.update(config, auth.nobody(config), 'MyClass', { objectId: mob.objectId }, obj); }) .then(() => database.adapter.find('MyClass', { fields: {} }, {}, {})) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); const mob = results[0]; expect(typeof mob.subdoc).toBe('object'); @@ -214,31 +202,23 @@ describe('rest create', () => { .catch(done.fail); }); - it('handles create on non-existent class when disabled client class creation', (done) => { + it('handles create on non-existent class when disabled client class creation', done => { const customConfig = Object.assign({}, config, { allowClientClassCreation: false, }); - rest - .create( - customConfig, - auth.nobody(customConfig), - 'ClientClassCreation', - {} - ) - .then( - () => { - fail('Should throw an error'); - done(); - }, - (err) => { - expect(err.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); - expect(err.message).toEqual( - 'This user is not allowed to access ' + - 'non-existent class: ClientClassCreation' - ); - done(); - } - ); + rest.create(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}).then( + () => { + fail('Should throw an error'); + done(); + }, + err => { + expect(err.code).toEqual(Parse.Error.OPERATION_FORBIDDEN); + expect(err.message).toEqual( + 'This user is not allowed to access ' + 'non-existent class: ClientClassCreation' + ); + done(); + } + ); }); it('handles create on existent class when disabled client class creation', async () => { @@ -246,29 +226,21 @@ describe('rest create', () => { allowClientClassCreation: false, }); const schema = await config.database.loadSchema(); - const actualSchema = await schema.addClassIfNotExists( - 'ClientClassCreation', - {} - ); + const actualSchema = await schema.addClassIfNotExists('ClientClassCreation', {}); expect(actualSchema.className).toEqual('ClientClassCreation'); await schema.reloadData({ clearCache: true }); // Should not throw - await rest.create( - customConfig, - auth.nobody(customConfig), - 'ClientClassCreation', - {} - ); + await rest.create(customConfig, auth.nobody(customConfig), 'ClientClassCreation', {}); }); - it('handles user signup', (done) => { + it('handles user signup', done => { const user = { username: 'asdf', password: 'zxcv', foo: 'bar', }; - rest.create(config, auth.nobody(config), '_User', user).then((r) => { + rest.create(config, auth.nobody(config), '_User', user).then(r => { expect(Object.keys(r.response).length).toEqual(3); expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); @@ -277,7 +249,7 @@ describe('rest create', () => { }); }); - it('handles anonymous user signup', (done) => { + it('handles anonymous user signup', done => { const data1 = { authData: { anonymous: { @@ -295,14 +267,14 @@ describe('rest create', () => { let username1; rest .create(config, auth.nobody(config), '_User', data1) - .then((r) => { + .then(r => { expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); expect(typeof r.response.sessionToken).toEqual('string'); expect(typeof r.response.username).toEqual('string'); return rest.create(config, auth.nobody(config), '_User', data1); }) - .then((r) => { + .then(r => { expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); expect(typeof r.response.username).toEqual('string'); @@ -310,13 +282,13 @@ describe('rest create', () => { username1 = r.response.username; return rest.create(config, auth.nobody(config), '_User', data2); }) - .then((r) => { + .then(r => { expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); expect(typeof r.response.sessionToken).toEqual('string'); return rest.create(config, auth.nobody(config), '_User', data2); }) - .then((r) => { + .then(r => { expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); expect(typeof r.response.username).toEqual('string'); @@ -326,7 +298,7 @@ describe('rest create', () => { }); }); - it('handles anonymous user signup and upgrade to new user', (done) => { + it('handles anonymous user signup and upgrade to new user', done => { const data1 = { authData: { anonymous: { @@ -343,7 +315,7 @@ describe('rest create', () => { let objectId; rest .create(config, auth.nobody(config), '_User', data1) - .then((r) => { + .then(r => { expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); expect(typeof r.response.sessionToken).toEqual('string'); @@ -353,32 +325,26 @@ describe('rest create', () => { sessionToken: r.response.sessionToken, }); }) - .then((sessionAuth) => { - return rest.update( - config, - sessionAuth, - '_User', - { objectId }, - updatedData - ); + .then(sessionAuth => { + return rest.update(config, sessionAuth, '_User', { objectId }, updatedData); }) .then(() => { return Parse.User.logOut().then(() => { return Parse.User.logIn('hello', 'world'); }); }) - .then((r) => { + .then(r => { expect(r.id).toEqual(objectId); expect(r.get('username')).toEqual('hello'); done(); }) - .catch((err) => { + .catch(err => { jfail(err); done(); }); }); - it('handles no anonymous users config', (done) => { + it('handles no anonymous users config', done => { const NoAnnonConfig = Object.assign({}, config); NoAnnonConfig.authDataManager.setEnableAnonymousUsers(false); const data1 = { @@ -393,18 +359,16 @@ describe('rest create', () => { fail('Should throw an error'); done(); }, - (err) => { + err => { expect(err.code).toEqual(Parse.Error.UNSUPPORTED_SERVICE); - expect(err.message).toEqual( - 'This authentication method is unsupported.' - ); + expect(err.message).toEqual('This authentication method is unsupported.'); NoAnnonConfig.authDataManager.setEnableAnonymousUsers(true); done(); } ); }); - it('test facebook signup and login', (done) => { + it('test facebook signup and login', done => { const data = { authData: { facebook: { @@ -416,14 +380,14 @@ describe('rest create', () => { let newUserSignedUpByFacebookObjectId; rest .create(config, auth.nobody(config), '_User', data) - .then((r) => { + .then(r => { expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); expect(typeof r.response.sessionToken).toEqual('string'); newUserSignedUpByFacebookObjectId = r.response.objectId; return rest.create(config, auth.nobody(config), '_User', data); }) - .then((r) => { + .then(r => { expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); expect(typeof r.response.username).toEqual('string'); @@ -433,19 +397,19 @@ describe('rest create', () => { sessionToken: r.response.sessionToken, }); }) - .then((response) => { + .then(response => { expect(response.results.length).toEqual(1); const output = response.results[0]; expect(output.user.objectId).toEqual(newUserSignedUpByFacebookObjectId); done(); }) - .catch((err) => { + .catch(err => { jfail(err); done(); }); }); - it('stores pointers', (done) => { + it('stores pointers', done => { const obj = { foo: 'bar', aPointer: { @@ -469,7 +433,7 @@ describe('rest create', () => { {} ) ) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); const output = results[0]; expect(typeof output.foo).toEqual('string'); @@ -484,7 +448,7 @@ describe('rest create', () => { }); }); - it('stores pointers to objectIds larger than 10 characters', (done) => { + it('stores pointers to objectIds larger than 10 characters', done => { const obj = { foo: 'bar', aPointer: { @@ -508,7 +472,7 @@ describe('rest create', () => { {} ) ) - .then((results) => { + .then(results => { expect(results.length).toEqual(1); const output = results[0]; expect(typeof output.foo).toEqual('string'); @@ -523,7 +487,7 @@ describe('rest create', () => { }); }); - it('cannot set objectId', (done) => { + it('cannot set objectId', done => { const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', @@ -537,7 +501,7 @@ describe('rest create', () => { foo: 'bar', objectId: 'hello', }), - }).then(fail, (response) => { + }).then(fail, response => { const b = response.data; expect(b.code).toEqual(105); expect(b.error).toEqual('objectId is an invalid field name.'); @@ -545,7 +509,7 @@ describe('rest create', () => { }); }); - it('cannot set id', (done) => { + it('cannot set id', done => { const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', @@ -559,7 +523,7 @@ describe('rest create', () => { foo: 'bar', id: 'hello', }), - }).then(fail, (response) => { + }).then(fail, response => { const b = response.data; expect(b.code).toEqual(105); expect(b.error).toEqual('id is an invalid field name.'); @@ -567,7 +531,7 @@ describe('rest create', () => { }); }); - it('test default session length', (done) => { + it('test default session length', done => { const user = { username: 'asdf', password: 'zxcv', @@ -577,7 +541,7 @@ describe('rest create', () => { rest .create(config, auth.nobody(config), '_User', user) - .then((r) => { + .then(r => { expect(Object.keys(r.response).length).toEqual(3); expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); @@ -586,7 +550,7 @@ describe('rest create', () => { sessionToken: r.response.sessionToken, }); }) - .then((r) => { + .then(r => { expect(r.results.length).toEqual(1); const session = r.results[0]; @@ -603,7 +567,7 @@ describe('rest create', () => { }); }); - it('test specified session length', (done) => { + it('test specified session length', done => { const user = { username: 'asdf', password: 'zxcv', @@ -615,7 +579,7 @@ describe('rest create', () => { rest .create(config, auth.nobody(config), '_User', user) - .then((r) => { + .then(r => { expect(Object.keys(r.response).length).toEqual(3); expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); @@ -624,7 +588,7 @@ describe('rest create', () => { sessionToken: r.response.sessionToken, }); }) - .then((r) => { + .then(r => { expect(r.results.length).toEqual(1); const session = r.results[0]; @@ -639,13 +603,13 @@ describe('rest create', () => { done(); }) - .catch((err) => { + .catch(err => { jfail(err); done(); }); }); - it('can create a session with no expiration', (done) => { + it('can create a session with no expiration', done => { const user = { username: 'asdf', password: 'zxcv', @@ -655,7 +619,7 @@ describe('rest create', () => { rest .create(config, auth.nobody(config), '_User', user) - .then((r) => { + .then(r => { expect(Object.keys(r.response).length).toEqual(3); expect(typeof r.response.objectId).toEqual('string'); expect(typeof r.response.createdAt).toEqual('string'); @@ -664,7 +628,7 @@ describe('rest create', () => { sessionToken: r.response.sessionToken, }); }) - .then((r) => { + .then(r => { expect(r.results.length).toEqual(1); const session = r.results[0]; @@ -672,42 +636,42 @@ describe('rest create', () => { done(); }) - .catch((err) => { + .catch(err => { console.error(err); fail(err); done(); }); }); - it('can create object in volatileClasses if masterKey', (done) => { + it('can create object in volatileClasses if masterKey', done => { rest .create(config, auth.master(config), '_PushStatus', {}) - .then((r) => { + .then(r => { expect(r.response.objectId.length).toBe(10); }) .then(() => { - rest.create(config, auth.master(config), '_JobStatus', {}).then((r) => { + rest.create(config, auth.master(config), '_JobStatus', {}).then(r => { expect(r.response.objectId.length).toBe(10); done(); }); }); }); - it('cannot create object in volatileClasses if not masterKey', (done) => { + it('cannot create object in volatileClasses if not masterKey', done => { Promise.resolve() .then(() => { return rest.create(config, auth.nobody(config), '_PushStatus', {}); }) - .catch((error) => { + .catch(error => { expect(error.code).toEqual(119); done(); }); }); - it('locks down session', (done) => { + it('locks down session', done => { let currentUser; Parse.User.signUp('foo', 'bar') - .then((user) => { + .then(user => { currentUser = user; const sessionToken = user.getSessionToken(); const headers = { @@ -721,7 +685,7 @@ describe('rest create', () => { headers: headers, url: 'http://localhost:8378/1/sessions/me', }) - .then((response) => { + .then(response => { sessionId = response.data.objectId; return request({ headers, @@ -732,7 +696,7 @@ describe('rest create', () => { }, }); }) - .then(done.fail, (res) => { + .then(done.fail, res => { expect(res.status).toBe(400); expect(res.data.code).toBe(105); return request({ @@ -744,12 +708,12 @@ describe('rest create', () => { }, }); }) - .then(done.fail, (res) => { + .then(done.fail, res => { expect(res.status).toBe(400); expect(res.data.code).toBe(105); return Parse.User.signUp('other', 'user'); }) - .then((otherUser) => { + .then(otherUser => { const user = new Parse.User(); user.id = otherUser.id; return request({ @@ -761,7 +725,7 @@ describe('rest create', () => { }, }); }) - .then(done.fail, (res) => { + .then(done.fail, res => { expect(res.status).toBe(400); expect(res.data.code).toBe(105); const user = new Parse.User(); @@ -781,10 +745,10 @@ describe('rest create', () => { .catch(done.fail); }); - it('sets current user in new sessions', (done) => { + it('sets current user in new sessions', done => { let currentUser; Parse.User.signUp('foo', 'bar') - .then((user) => { + .then(user => { currentUser = user; const sessionToken = user.getSessionToken(); const headers = { @@ -802,7 +766,7 @@ describe('rest create', () => { }, }); }) - .then((response) => { + .then(response => { if (response.data.user.objectId === currentUser.id) { return done(); } else { @@ -814,7 +778,7 @@ describe('rest create', () => { }); describe('rest update', () => { - it('ignores createdAt', (done) => { + it('ignores createdAt', done => { const config = Config.get('test'); const nobody = auth.nobody(config); const className = 'Foo'; @@ -822,22 +786,20 @@ describe('rest update', () => { rest .create(config, nobody, className, {}) - .then((res) => { + .then(res => { const objectId = res.response.objectId; const restObject = { createdAt: { __type: 'Date', iso: newCreatedAt }, // should be ignored }; - return rest - .update(config, nobody, className, { objectId }, restObject) - .then(() => { - const restWhere = { - objectId: objectId, - }; - return rest.find(config, nobody, className, restWhere, {}); - }); + return rest.update(config, nobody, className, { objectId }, restObject).then(() => { + const restWhere = { + objectId: objectId, + }; + return rest.find(config, nobody, className, restWhere, {}); + }); }) - .then((res2) => { + .then(res2 => { const updatedObject = res2.results[0]; expect(new Date(updatedObject.createdAt)).not.toEqual(newCreatedAt); done(); @@ -867,7 +829,7 @@ describe('read-only masterKey', () => { }).toThrow(); }); - it('properly blocks writes', (done) => { + it('properly blocks writes', done => { reconfigureServer({ readOnlyMasterKey: 'yolo-read-only', }) @@ -884,7 +846,7 @@ describe('read-only masterKey', () => { }); }) .then(done.fail) - .catch((res) => { + .catch(res => { expect(res.data.code).toBe(Parse.Error.OPERATION_FORBIDDEN); expect(res.data.error).toBe( "read-only masterKey isn't allowed to perform the create operation." @@ -893,16 +855,14 @@ describe('read-only masterKey', () => { }); }); - it('should throw when masterKey and readOnlyMasterKey are the same', (done) => { + it('should throw when masterKey and readOnlyMasterKey are the same', done => { reconfigureServer({ masterKey: 'yolo', readOnlyMasterKey: 'yolo', }) .then(done.fail) - .catch((err) => { - expect(err).toEqual( - new Error('masterKey and readOnlyMasterKey should be different') - ); + .catch(err => { + expect(err).toEqual(new Error('masterKey and readOnlyMasterKey should be different')); done(); }); }); @@ -919,7 +879,7 @@ describe('read-only masterKey', () => { ); }); - it('should throw when trying to create schema', (done) => { + it('should throw when trying to create schema', done => { return request({ method: 'POST', url: `${Parse.serverURL}/schemas`, @@ -931,16 +891,14 @@ describe('read-only masterKey', () => { json: {}, }) .then(done.fail) - .catch((res) => { + .catch(res => { expect(res.data.code).toBe(Parse.Error.OPERATION_FORBIDDEN); - expect(res.data.error).toBe( - "read-only masterKey isn't allowed to create a schema." - ); + expect(res.data.error).toBe("read-only masterKey isn't allowed to create a schema."); done(); }); }); - it('should throw when trying to create schema with a name', (done) => { + it('should throw when trying to create schema with a name', done => { return request({ url: `${Parse.serverURL}/schemas/MyClass`, method: 'POST', @@ -952,16 +910,14 @@ describe('read-only masterKey', () => { json: {}, }) .then(done.fail) - .catch((res) => { + .catch(res => { expect(res.data.code).toBe(Parse.Error.OPERATION_FORBIDDEN); - expect(res.data.error).toBe( - "read-only masterKey isn't allowed to create a schema." - ); + expect(res.data.error).toBe("read-only masterKey isn't allowed to create a schema."); done(); }); }); - it('should throw when trying to update schema', (done) => { + it('should throw when trying to update schema', done => { return request({ url: `${Parse.serverURL}/schemas/MyClass`, method: 'PUT', @@ -973,16 +929,14 @@ describe('read-only masterKey', () => { json: {}, }) .then(done.fail) - .catch((res) => { + .catch(res => { expect(res.data.code).toBe(Parse.Error.OPERATION_FORBIDDEN); - expect(res.data.error).toBe( - "read-only masterKey isn't allowed to update a schema." - ); + expect(res.data.error).toBe("read-only masterKey isn't allowed to update a schema."); done(); }); }); - it('should throw when trying to delete schema', (done) => { + it('should throw when trying to delete schema', done => { return request({ url: `${Parse.serverURL}/schemas/MyClass`, method: 'DELETE', @@ -994,16 +948,14 @@ describe('read-only masterKey', () => { json: {}, }) .then(done.fail) - .catch((res) => { + .catch(res => { expect(res.data.code).toBe(Parse.Error.OPERATION_FORBIDDEN); - expect(res.data.error).toBe( - "read-only masterKey isn't allowed to delete a schema." - ); + expect(res.data.error).toBe("read-only masterKey isn't allowed to delete a schema."); done(); }); }); - it('should throw when trying to update the global config', (done) => { + it('should throw when trying to update the global config', done => { return request({ url: `${Parse.serverURL}/config`, method: 'PUT', @@ -1015,16 +967,14 @@ describe('read-only masterKey', () => { json: {}, }) .then(done.fail) - .catch((res) => { + .catch(res => { expect(res.data.code).toBe(Parse.Error.OPERATION_FORBIDDEN); - expect(res.data.error).toBe( - "read-only masterKey isn't allowed to update the config." - ); + expect(res.data.error).toBe("read-only masterKey isn't allowed to update the config."); done(); }); }); - it('should throw when trying to send push', (done) => { + it('should throw when trying to send push', done => { return request({ url: `${Parse.serverURL}/push`, method: 'POST', @@ -1036,7 +986,7 @@ describe('read-only masterKey', () => { json: {}, }) .then(done.fail) - .catch((res) => { + .catch(res => { expect(res.data.code).toBe(Parse.Error.OPERATION_FORBIDDEN); expect(res.data.error).toBe( "read-only masterKey isn't allowed to send push notifications." diff --git a/spec/schemas.spec.js b/spec/schemas.spec.js index adb82526..6cdb610e 100644 --- a/spec/schemas.spec.js +++ b/spec/schemas.spec.js @@ -17,10 +17,7 @@ const hasAllPODobject = () => { obj.set('aObject', { k1: 'value', k2: true, k3: 5 }); obj.set('aArray', ['contents', true, 5]); obj.set('aGeoPoint', new Parse.GeoPoint({ latitude: 0, longitude: 0 })); - obj.set( - 'aFile', - new Parse.File('f.txt', { base64: 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=' }) - ); + obj.set('aFile', new Parse.File('f.txt', { base64: 'V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=' })); const objACL = new Parse.ACL(); objACL.setPublicWriteAccess(false); obj.setACL(objACL); @@ -173,9 +170,7 @@ describe('schemas', () => { headers: restKeyHeaders, }).then(fail, response => { expect(response.status).toEqual(403); - expect(response.data.error).toEqual( - 'unauthorized: master key is required' - ); + expect(response.data.error).toEqual('unauthorized: master key is required'); done(); }); }); @@ -187,9 +182,7 @@ describe('schemas', () => { headers: restKeyHeaders, }).then(fail, response => { expect(response.status).toEqual(403); - expect(response.data.error).toEqual( - 'unauthorized: master key is required' - ); + expect(response.data.error).toEqual('unauthorized: master key is required'); done(); }); }); @@ -211,11 +204,7 @@ describe('schemas', () => { delete withoutIndexes.indexes; return withoutIndexes; }) - ).toEqual( - expected.results.sort((s1, s2) => - s1.className.localeCompare(s2.className) - ) - ); + ).toEqual(expected.results.sort((s1, s2) => s1.className.localeCompare(s2.className))); done(); }); }); @@ -238,12 +227,7 @@ describe('schemas', () => { headers: masterKeyHeaders, }).then(response => { const expected = { - results: [ - userSchema, - roleSchema, - plainOldDataSchema, - pointersAndRelationsSchema, - ], + results: [userSchema, roleSchema, plainOldDataSchema, pointersAndRelationsSchema], }; expect( response.data.results @@ -253,11 +237,7 @@ describe('schemas', () => { delete withoutIndexes.indexes; return withoutIndexes; }) - ).toEqual( - expected.results.sort((s1, s2) => - s1.className.localeCompare(s2.className) - ) - ); + ).toEqual(expected.results.sort((s1, s2) => s1.className.localeCompare(s2.className))); done(); }); }); @@ -659,11 +639,7 @@ describe('schemas', () => { config.database .loadSchema() .then(schemaController => - schemaController.addClassIfNotExists( - '_Installation', - {}, - defaultClassLevelPermissions - ) + schemaController.addClassIfNotExists('_Installation', {}, defaultClassLevelPermissions) ) .then(() => { request({ @@ -803,9 +779,7 @@ describe('schemas', () => { }).then(fail, response => { expect(response.status).toEqual(400); expect(response.data.code).toEqual(255); - expect(response.data.error).toEqual( - 'Field aString exists, cannot update.' - ); + expect(response.data.error).toEqual('Field aString exists, cannot update.'); done(); }); }); @@ -827,9 +801,7 @@ describe('schemas', () => { }).then(fail, response => { expect(response.status).toEqual(400); expect(response.data.code).toEqual(255); - expect(response.data.error).toEqual( - 'Field nonExistentKey does not exist, cannot delete.' - ); + expect(response.data.error).toEqual('Field nonExistentKey does not exist, cannot delete.'); done(); }); }); @@ -1109,13 +1081,9 @@ describe('schemas', () => { obj.set('newRequiredField', 'some value'); await obj.save(); expect(obj.get('newRequiredField')).toEqual('some value'); - expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual( - 'some value' - ); + expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual('some value'); expect(obj.get('newNotRequiredField')).toEqual(undefined); - expect(obj.get('newNotRequiredFieldWithDefaultValue')).toEqual( - 'some value' - ); + expect(obj.get('newNotRequiredFieldWithDefaultValue')).toEqual('some value'); expect(obj.get('newRegularField')).toEqual(undefined); obj.set('newRequiredField', null); try { @@ -1136,13 +1104,9 @@ describe('schemas', () => { obj.set('newRequiredField', 'some value2'); await obj.save(); expect(obj.get('newRequiredField')).toEqual('some value2'); - expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual( - 'some value' - ); + expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual('some value'); expect(obj.get('newNotRequiredField')).toEqual(undefined); - expect(obj.get('newNotRequiredFieldWithDefaultValue')).toEqual( - 'some value' - ); + expect(obj.get('newNotRequiredFieldWithDefaultValue')).toEqual('some value'); expect(obj.get('newRegularField')).toEqual(undefined); obj.unset('newRequiredFieldWithDefaultValue'); try { @@ -1150,9 +1114,7 @@ describe('schemas', () => { fail('Should fail'); } catch (e) { expect(e.code).toEqual(142); - expect(e.message).toEqual( - 'newRequiredFieldWithDefaultValue is required' - ); + expect(e.message).toEqual('newRequiredFieldWithDefaultValue is required'); } obj.set('newRequiredFieldWithDefaultValue', ''); try { @@ -1160,9 +1122,7 @@ describe('schemas', () => { fail('Should fail'); } catch (e) { expect(e.code).toEqual(142); - expect(e.message).toEqual( - 'newRequiredFieldWithDefaultValue is required' - ); + expect(e.message).toEqual('newRequiredFieldWithDefaultValue is required'); } obj.set('newRequiredFieldWithDefaultValue', 'some value2'); obj.set('newNotRequiredField', ''); @@ -1170,9 +1130,7 @@ describe('schemas', () => { obj.unset('newRegularField'); await obj.save(); expect(obj.get('newRequiredField')).toEqual('some value2'); - expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual( - 'some value2' - ); + expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual('some value2'); expect(obj.get('newNotRequiredField')).toEqual(''); expect(obj.get('newNotRequiredFieldWithDefaultValue')).toEqual(null); expect(obj.get('newRegularField')).toEqual(undefined); @@ -1184,13 +1142,9 @@ describe('schemas', () => { obj.set('newRegularField', 'some value3'); await obj.save(); expect(obj.get('newRequiredField')).toEqual('some value3'); - expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual( - 'some value3' - ); + expect(obj.get('newRequiredFieldWithDefaultValue')).toEqual('some value3'); expect(obj.get('newNotRequiredField')).toEqual('some value3'); - expect(obj.get('newNotRequiredFieldWithDefaultValue')).toEqual( - 'some value3' - ); + expect(obj.get('newNotRequiredFieldWithDefaultValue')).toEqual('some value3'); expect(obj.get('newRegularField')).toEqual('some value3'); done(); }); @@ -1599,12 +1553,8 @@ describe('schemas', () => { }).then(fail, response => { //Expect _SCHEMA entry to be gone. expect(response.status).toEqual(400); - expect(response.data.code).toEqual( - Parse.Error.INVALID_CLASS_NAME - ); - expect(response.data.error).toEqual( - 'Class MyOtherClass does not exist.' - ); + expect(response.data.code).toEqual(Parse.Error.INVALID_CLASS_NAME); + expect(response.data.error).toEqual('Class MyOtherClass does not exist.'); done(); }); }); @@ -1668,9 +1618,7 @@ describe('schemas', () => { expect(typeof response.data.objectId).toEqual('string'); request({ method: 'DELETE', - url: - 'http://localhost:8378/1/classes/NewClassForDelete/' + - response.data.objectId, + url: 'http://localhost:8378/1/classes/NewClassForDelete/' + response.data.objectId, headers: restKeyHeaders, json: true, }).then(() => { @@ -1795,9 +1743,7 @@ describe('schemas', () => { done(); }, err => { - expect(err.message).toEqual( - 'Permission denied for action addField on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action addField on class AClass.'); done(); } ); @@ -1960,9 +1906,7 @@ describe('schemas', () => { }, }, }).then(fail, response => { - expect(response.data.error).toEqual( - "' *' is not a valid key for class level permissions" - ); + expect(response.data.error).toEqual("' *' is not a valid key for class level permissions"); done(); }); }); @@ -1981,9 +1925,7 @@ describe('schemas', () => { }, }, }).then(fail, response => { - expect(response.data.error).toEqual( - "'* ' is not a valid key for class level permissions" - ); + expect(response.data.error).toEqual("'* ' is not a valid key for class level permissions"); done(); }); }); @@ -2085,9 +2027,7 @@ describe('schemas', () => { fail('Use should hot be able to find!'); }, err => { - expect(err.message).toEqual( - 'Permission denied for action find on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action find on class AClass.'); return Promise.resolve(); } ); @@ -2147,9 +2087,7 @@ describe('schemas', () => { fail('User should not be able to find!'); }, err => { - expect(err.message).toEqual( - 'Permission denied for action find on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action find on class AClass.'); return Promise.resolve(); } ); @@ -2234,9 +2172,7 @@ describe('schemas', () => { fail('User should not be able to find!'); }, err => { - expect(err.message).toEqual( - 'Permission denied for action find on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action find on class AClass.'); return Promise.resolve(); } ); @@ -2312,9 +2248,7 @@ describe('schemas', () => { fail('User should not be able to find!'); }, err => { - expect(err.message).toEqual( - 'Permission denied for action find on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action find on class AClass.'); return Promise.resolve(); } ); @@ -2345,9 +2279,7 @@ describe('schemas', () => { fail('User should not be able to find!'); }, err => { - expect(err.message).toEqual( - 'Permission denied for action find on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action find on class AClass.'); return Promise.resolve(); } ); @@ -2431,9 +2363,7 @@ describe('schemas', () => { return Promise.resolve(); }, err => { - expect(err.message).toEqual( - 'Permission denied for action create on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action create on class AClass.'); return Promise.resolve(); } ) @@ -2450,9 +2380,7 @@ describe('schemas', () => { return Promise.resolve(); }, err => { - expect(err.message).toEqual( - 'Permission denied for action find on class AClass.' - ); + expect(err.message).toEqual('Permission denied for action find on class AClass.'); return Promise.resolve(); } ) @@ -2764,10 +2692,7 @@ describe('schemas', () => { }); await expectAsync(schemaCreation()).toBeRejectedWith( - new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `invalid field name: ${fieldName}` - ) + new Parse.Error(Parse.Error.INVALID_KEY_NAME, `invalid field name: ${fieldName}`) ); done(); }); @@ -2912,9 +2837,7 @@ describe('schemas', () => { }, }).then(fail, response => { expect(response.data.code).toBe(Parse.Error.INVALID_QUERY); - expect(response.data.error).toBe( - 'Field aString does not exist, cannot add index.' - ); + expect(response.data.error).toBe('Field aString does not exist, cannot add index.'); done(); }); }); @@ -2968,9 +2891,7 @@ describe('schemas', () => { }, }).then(fail, response => { expect(response.data.code).toBe(Parse.Error.INVALID_QUERY); - expect(response.data.error).toBe( - 'Field bString does not exist, cannot add index.' - ); + expect(response.data.error).toBe('Field bString does not exist, cannot add index.'); done(); }); }); @@ -3110,76 +3031,73 @@ describe('schemas', () => { }); }); - it_only_db('mongo')( - 'lets you add index with with pointer like structure', - done => { + it_only_db('mongo')('lets you add index with with pointer like structure', done => { + request({ + url: 'http://localhost:8378/1/schemas/NewClass', + method: 'POST', + headers: masterKeyHeaders, + json: true, + body: {}, + }).then(() => { request({ url: 'http://localhost:8378/1/schemas/NewClass', - method: 'POST', + method: 'PUT', headers: masterKeyHeaders, json: true, - body: {}, - }).then(() => { - request({ - url: 'http://localhost:8378/1/schemas/NewClass', - method: 'PUT', - headers: masterKeyHeaders, - json: true, - body: { + body: { + fields: { + aPointer: { type: 'Pointer', targetClass: 'NewClass' }, + }, + indexes: { + pointer: { _p_aPointer: 1 }, + }, + }, + }).then(response => { + expect( + dd(response.data, { + className: 'NewClass', fields: { + ACL: { type: 'ACL' }, + createdAt: { type: 'Date' }, + updatedAt: { type: 'Date' }, + objectId: { type: 'String' }, aPointer: { type: 'Pointer', targetClass: 'NewClass' }, }, + classLevelPermissions: defaultClassLevelPermissions, indexes: { + _id_: { _id: 1 }, pointer: { _p_aPointer: 1 }, }, - }, + }) + ).toEqual(undefined); + request({ + url: 'http://localhost:8378/1/schemas/NewClass', + headers: masterKeyHeaders, + json: true, }).then(response => { - expect( - dd(response.data, { - className: 'NewClass', - fields: { - ACL: { type: 'ACL' }, - createdAt: { type: 'Date' }, - updatedAt: { type: 'Date' }, - objectId: { type: 'String' }, - aPointer: { type: 'Pointer', targetClass: 'NewClass' }, - }, - classLevelPermissions: defaultClassLevelPermissions, - indexes: { - _id_: { _id: 1 }, - pointer: { _p_aPointer: 1 }, - }, - }) - ).toEqual(undefined); - request({ - url: 'http://localhost:8378/1/schemas/NewClass', - headers: masterKeyHeaders, - json: true, - }).then(response => { - expect(response.data).toEqual({ - className: 'NewClass', - fields: { - ACL: { type: 'ACL' }, - createdAt: { type: 'Date' }, - updatedAt: { type: 'Date' }, - objectId: { type: 'String' }, - aPointer: { type: 'Pointer', targetClass: 'NewClass' }, - }, - classLevelPermissions: defaultClassLevelPermissions, - indexes: { - _id_: { _id: 1 }, - pointer: { _p_aPointer: 1 }, - }, - }); - config.database.adapter.getIndexes('NewClass').then(indexes => { - expect(indexes.length).toEqual(2); - done(); - }); + expect(response.data).toEqual({ + className: 'NewClass', + fields: { + ACL: { type: 'ACL' }, + createdAt: { type: 'Date' }, + updatedAt: { type: 'Date' }, + objectId: { type: 'String' }, + aPointer: { type: 'Pointer', targetClass: 'NewClass' }, + }, + classLevelPermissions: defaultClassLevelPermissions, + indexes: { + _id_: { _id: 1 }, + pointer: { _p_aPointer: 1 }, + }, + }); + config.database.adapter.getIndexes('NewClass').then(indexes => { + expect(indexes.length).toEqual(2); + done(); }); }); }); - } - ); + }); + }); it('lets you add multiple indexes', done => { request({ @@ -3532,9 +3450,7 @@ describe('schemas', () => { }, }).then(fail, response => { expect(response.data.code).toBe(Parse.Error.INVALID_QUERY); - expect(response.data.error).toBe( - 'Index unknownIndex does not exist, cannot delete.' - ); + expect(response.data.error).toBe('Index unknownIndex does not exist, cannot delete.'); done(); }); }); @@ -3574,9 +3490,7 @@ describe('schemas', () => { }, }).then(fail, response => { expect(response.data.code).toBe(Parse.Error.INVALID_QUERY); - expect(response.data.error).toBe( - 'Index name1 exists, cannot update.' - ); + expect(response.data.error).toBe('Index name1 exists, cannot update.'); done(); }); }); @@ -3633,52 +3547,43 @@ describe('schemas', () => { }).then(response => { expect(response.data.indexes._id_).toBeDefined(); expect(response.data.indexes._id_._id).toEqual(1); - expect( - response.data.indexes.subject_text_comment_text - ).toBeDefined(); - expect( - response.data.indexes.subject_text_comment_text.subject - ).toEqual('text'); - expect( - response.data.indexes.subject_text_comment_text.comment - ).toEqual('text'); + expect(response.data.indexes.subject_text_comment_text).toBeDefined(); + expect(response.data.indexes.subject_text_comment_text.subject).toEqual('text'); + expect(response.data.indexes.subject_text_comment_text.comment).toEqual('text'); done(); }); }); }); - it_exclude_dbs(['postgres'])( - 'cannot update to duplicate value on unique index', - done => { - const index = { - code: 1, - }; - const obj1 = new Parse.Object('UniqueIndexClass'); - obj1.set('code', 1); - const obj2 = new Parse.Object('UniqueIndexClass'); - obj2.set('code', 2); - const adapter = config.database.adapter; - adapter - ._adaptiveCollection('UniqueIndexClass') - .then(collection => { - return collection._ensureSparseUniqueIndexInBackground(index); - }) - .then(() => { - return obj1.save(); - }) - .then(() => { - return obj2.save(); - }) - .then(() => { - obj1.set('code', 2); - return obj1.save(); - }) - .then(done.fail) - .catch(error => { - expect(error.code).toEqual(Parse.Error.DUPLICATE_VALUE); - done(); - }); - } - ); + it_exclude_dbs(['postgres'])('cannot update to duplicate value on unique index', done => { + const index = { + code: 1, + }; + const obj1 = new Parse.Object('UniqueIndexClass'); + obj1.set('code', 1); + const obj2 = new Parse.Object('UniqueIndexClass'); + obj2.set('code', 2); + const adapter = config.database.adapter; + adapter + ._adaptiveCollection('UniqueIndexClass') + .then(collection => { + return collection._ensureSparseUniqueIndexInBackground(index); + }) + .then(() => { + return obj1.save(); + }) + .then(() => { + return obj2.save(); + }) + .then(() => { + obj1.set('code', 2); + return obj1.save(); + }) + .then(done.fail) + .catch(error => { + expect(error.code).toEqual(Parse.Error.DUPLICATE_VALUE); + done(); + }); + }); }); }); diff --git a/spec/support/FailingServer.js b/spec/support/FailingServer.js index 6467cef9..2123961f 100755 --- a/spec/support/FailingServer.js +++ b/spec/support/FailingServer.js @@ -1,14 +1,10 @@ #!/usr/bin/env node -const MongoStorageAdapter = require('../../lib/Adapters/Storage/Mongo/MongoStorageAdapter') - .default; -const { - GridFSBucketAdapter, -} = require('../../lib/Adapters/Files/GridFSBucketAdapter'); +const MongoStorageAdapter = require('../../lib/Adapters/Storage/Mongo/MongoStorageAdapter').default; +const { GridFSBucketAdapter } = require('../../lib/Adapters/Files/GridFSBucketAdapter'); const ParseServer = require('../../lib/index').ParseServer; -const databaseURI = - 'mongodb://doesnotexist:27017/parseServerMongoAdapterTestDatabase'; +const databaseURI = 'mongodb://doesnotexist:27017/parseServerMongoAdapterTestDatabase'; ParseServer.start({ appId: 'test', diff --git a/spec/testing-routes.js b/spec/testing-routes.js index 8ba0287a..4cf626bc 100644 --- a/spec/testing-routes.js +++ b/spec/testing-routes.js @@ -14,8 +14,7 @@ function createApp(req, res) { const appId = cryptoUtils.randomHexString(32); ParseServer({ - databaseURI: - 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase', + databaseURI: 'mongodb://localhost:27017/parseServerMongoAdapterTestDatabase', appId: appId, masterKey: 'master', serverURL: Parse.serverURL, @@ -61,28 +60,12 @@ function notImplementedYet(req, res) { router.post('/rest_clear_app', middlewares.handleParseHeaders, clearApp); router.post('/rest_block', middlewares.handleParseHeaders, notImplementedYet); -router.post( - '/rest_mock_v8_client', - middlewares.handleParseHeaders, - notImplementedYet -); -router.post( - '/rest_unmock_v8_client', - middlewares.handleParseHeaders, - notImplementedYet -); -router.post( - '/rest_verify_analytics', - middlewares.handleParseHeaders, - notImplementedYet -); +router.post('/rest_mock_v8_client', middlewares.handleParseHeaders, notImplementedYet); +router.post('/rest_unmock_v8_client', middlewares.handleParseHeaders, notImplementedYet); +router.post('/rest_verify_analytics', middlewares.handleParseHeaders, notImplementedYet); router.post('/rest_create_app', createApp); router.post('/rest_drop_app', middlewares.handleParseHeaders, dropApp); -router.post( - '/rest_configure_app', - middlewares.handleParseHeaders, - notImplementedYet -); +router.post('/rest_configure_app', middlewares.handleParseHeaders, notImplementedYet); module.exports = { router: router, diff --git a/src/AccountLockout.js b/src/AccountLockout.js index da3049cd..183c7959 100644 --- a/src/AccountLockout.js +++ b/src/AccountLockout.js @@ -82,27 +82,23 @@ export class AccountLockout { const updateFields = { _account_lockout_expires_at: Parse._encode( - new Date( - now.getTime() + this._config.accountLockout.duration * 60 * 1000 - ) + new Date(now.getTime() + this._config.accountLockout.duration * 60 * 1000) ), }; - return this._config.database - .update('_User', query, updateFields) - .catch(err => { - if ( - err && - err.code && - err.message && - err.code === 101 && - err.message === 'Object not found.' - ) { - return; // nothing to update so we are good - } else { - throw err; // unknown error - } - }); + return this._config.database.update('_User', query, updateFields).catch(err => { + if ( + err && + err.code && + err.message && + err.code === 101 && + err.message === 'Object not found.' + ) { + return; // nothing to update so we are good + } else { + throw err; // unknown error + } + }); } /** diff --git a/src/Auth.js b/src/Auth.js index ebb5debf..2d63e785 100644 --- a/src/Auth.js +++ b/src/Auth.js @@ -29,7 +29,7 @@ function Auth({ // Whether this auth could possibly modify the given user id. // It still could be forbidden via ACLs even if this returns true. -Auth.prototype.isUnauthenticated = function() { +Auth.prototype.isUnauthenticated = function () { if (this.isMaster) { return false; } @@ -55,7 +55,7 @@ function nobody(config) { } // Returns a promise that resolves to an Auth object -const getAuthForSessionToken = async function({ +const getAuthForSessionToken = async function ({ config, cacheController, sessionToken, @@ -85,37 +85,25 @@ const getAuthForSessionToken = async function({ include: 'user', }; - const query = new RestQuery( - config, - master(config), - '_Session', - { sessionToken }, - restOptions - ); + const query = new RestQuery(config, master(config), '_Session', { sessionToken }, restOptions); results = (await query.execute()).results; } else { - results = (await new Parse.Query(Parse.Session) - .limit(1) - .include('user') - .equalTo('sessionToken', sessionToken) - .find({ useMasterKey: true })).map(obj => obj.toJSON()); + results = ( + await new Parse.Query(Parse.Session) + .limit(1) + .include('user') + .equalTo('sessionToken', sessionToken) + .find({ useMasterKey: true }) + ).map(obj => obj.toJSON()); } if (results.length !== 1 || !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'); } const now = new Date(), - expiresAt = results[0].expiresAt - ? new Date(results[0].expiresAt.iso) - : undefined; + expiresAt = results[0].expiresAt ? new Date(results[0].expiresAt.iso) : undefined; if (expiresAt < now) { - throw new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'Session token is expired.' - ); + throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token is expired.'); } const obj = results[0]['user']; delete obj.password; @@ -134,28 +122,15 @@ const getAuthForSessionToken = async function({ }); }; -var getAuthForLegacySessionToken = function({ - config, - sessionToken, - installationId, -}) { +var getAuthForLegacySessionToken = function ({ config, sessionToken, installationId }) { var restOptions = { limit: 1, }; - var query = new RestQuery( - config, - master(config), - '_User', - { sessionToken }, - restOptions - ); + var query = new RestQuery(config, master(config), '_User', { sessionToken }, restOptions); return query.execute().then(response => { var results = response.results; 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'); } const obj = results[0]; obj.className = '_User'; @@ -170,7 +145,7 @@ var getAuthForLegacySessionToken = function({ }; // Returns a promise that resolves to an array of role names -Auth.prototype.getUserRoles = function() { +Auth.prototype.getUserRoles = function () { if (this.isMaster || !this.user) { return Promise.resolve([]); } @@ -184,7 +159,7 @@ Auth.prototype.getUserRoles = function() { return this.rolePromise; }; -Auth.prototype.getRolesForUser = async function() { +Auth.prototype.getRolesForUser = async function () { //Stack all Parse.Role const results = []; if (this.config) { @@ -195,13 +170,9 @@ Auth.prototype.getRolesForUser = async function() { objectId: this.user.id, }, }; - await new RestQuery( - this.config, - master(this.config), - '_Role', - restWhere, - {} - ).each(result => results.push(result)); + await new RestQuery(this.config, master(this.config), '_Role', restWhere, {}).each(result => + results.push(result) + ); } else { await new Parse.Query(Parse.Role) .equalTo('users', this.user) @@ -211,7 +182,7 @@ Auth.prototype.getRolesForUser = async function() { }; // Iterates through the role tree and compiles a user's roles -Auth.prototype._loadRoles = async function() { +Auth.prototype._loadRoles = async function () { if (this.cacheController) { const cachedRoles = await this.cacheController.role.get(this.user.id); if (cachedRoles != null) { @@ -242,10 +213,7 @@ Auth.prototype._loadRoles = async function() { ); // run the recursive finding - const roleNames = await this._getAllRolesNamesForRoleIds( - rolesMap.ids, - rolesMap.names - ); + const roleNames = await this._getAllRolesNamesForRoleIds(rolesMap.ids, rolesMap.names); this.userRoles = roleNames.map(r => { return 'role:' + r; }); @@ -255,7 +223,7 @@ Auth.prototype._loadRoles = async function() { return this.userRoles; }; -Auth.prototype.cacheRoles = function() { +Auth.prototype.cacheRoles = function () { if (!this.cacheController) { return false; } @@ -263,7 +231,7 @@ Auth.prototype.cacheRoles = function() { return true; }; -Auth.prototype.getRolesByIds = async function(ins) { +Auth.prototype.getRolesByIds = async function (ins) { const results = []; // Build an OR query across all parentRoles if (!this.config) { @@ -286,23 +254,15 @@ Auth.prototype.getRolesByIds = async function(ins) { }; }); const restWhere = { roles: { $in: roles } }; - await new RestQuery( - this.config, - master(this.config), - '_Role', - restWhere, - {} - ).each(result => results.push(result)); + await new RestQuery(this.config, master(this.config), '_Role', restWhere, {}).each(result => + results.push(result) + ); } return results; }; // 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 = {}) { const ins = roleIDs.filter(roleID => { const wasQueried = queriedRoles[roleID] !== true; queriedRoles[roleID] = true; @@ -332,18 +292,14 @@ Auth.prototype._getAllRolesNamesForRoleIds = function( // store the new found names names = names.concat(resultMap.names); // find the next ones, circular roles will be cut - return this._getAllRolesNamesForRoleIds( - resultMap.ids, - names, - queriedRoles - ); + return this._getAllRolesNamesForRoleIds(resultMap.ids, names, queriedRoles); }) .then(names => { return Promise.resolve([...new Set(names)]); }); }; -const createSession = function( +const createSession = function ( config, { userId, createdWith, installationId, additionalSessionData } ) { @@ -372,13 +328,7 @@ const createSession = function( return { sessionData, createSession: () => - new RestWrite( - config, - master(config), - '_Session', - null, - sessionData - ).execute(), + new RestWrite(config, master(config), '_Session', null, sessionData).execute(), }; }; diff --git a/src/ClientSDK.js b/src/ClientSDK.js index e4a716ab..698729fc 100644 --- a/src/ClientSDK.js +++ b/src/ClientSDK.js @@ -1,7 +1,7 @@ var semver = require('semver'); function compatible(compatibleSDK) { - return function(clientSDK) { + return function (clientSDK) { if (typeof clientSDK === 'string') { clientSDK = fromString(clientSDK); } diff --git a/src/Config.js b/src/Config.js index 925cbb79..87081af4 100644 --- a/src/Config.js +++ b/src/Config.js @@ -33,18 +33,13 @@ export class Config { cacheInfo.schemaCacheTTL, cacheInfo.enableSingleSchemaCache ); - config.database = new DatabaseController( - cacheInfo.databaseController.adapter, - schemaCache - ); + config.database = new DatabaseController(cacheInfo.databaseController.adapter, schemaCache); } else { config[key] = cacheInfo[key]; } }); config.mount = removeTrailingSlash(mount); - config.generateSessionExpiresAt = config.generateSessionExpiresAt.bind( - config - ); + config.generateSessionExpiresAt = config.generateSessionExpiresAt.bind(config); config.generateEmailVerifyTokenExpiresAt = config.generateEmailVerifyTokenExpiresAt.bind( config ); @@ -99,10 +94,7 @@ export class Config { } if (publicServerURL) { - if ( - !publicServerURL.startsWith('http://') && - !publicServerURL.startsWith('https://') - ) { + if (!publicServerURL.startsWith('http://') && !publicServerURL.startsWith('https://')) { throw 'publicServerURL should be a valid HTTPS URL starting with https://'; } } @@ -155,8 +147,7 @@ export class Config { if (passwordPolicy) { if ( passwordPolicy.maxPasswordAge !== undefined && - (typeof passwordPolicy.maxPasswordAge !== 'number' || - passwordPolicy.maxPasswordAge < 0) + (typeof passwordPolicy.maxPasswordAge !== 'number' || passwordPolicy.maxPasswordAge < 0) ) { throw 'passwordPolicy.maxPasswordAge must be a positive number'; } @@ -171,9 +162,7 @@ export class Config { if (passwordPolicy.validatorPattern) { if (typeof passwordPolicy.validatorPattern === 'string') { - passwordPolicy.validatorPattern = new RegExp( - passwordPolicy.validatorPattern - ); + passwordPolicy.validatorPattern = new RegExp(passwordPolicy.validatorPattern); } else if (!(passwordPolicy.validatorPattern instanceof RegExp)) { throw 'passwordPolicy.validatorPattern must be a regex string or RegExp object.'; } @@ -294,22 +283,15 @@ export class Config { return undefined; } var now = new Date(); - return new Date( - now.getTime() + this.emailVerifyTokenValidityDuration * 1000 - ); + return new Date(now.getTime() + this.emailVerifyTokenValidityDuration * 1000); } generatePasswordResetTokenExpiresAt() { - if ( - !this.passwordPolicy || - !this.passwordPolicy.resetTokenValidityDuration - ) { + if (!this.passwordPolicy || !this.passwordPolicy.resetTokenValidityDuration) { return undefined; } const now = new Date(); - return new Date( - now.getTime() + this.passwordPolicy.resetTokenValidityDuration * 1000 - ); + return new Date(now.getTime() + this.passwordPolicy.resetTokenValidityDuration * 1000); } generateSessionExpiresAt() { @@ -321,10 +303,7 @@ export class Config { } get invalidLinkURL() { - return ( - this.customPages.invalidLink || - `${this.publicServerURL}/apps/invalid_link.html` - ); + return this.customPages.invalidLink || `${this.publicServerURL}/apps/invalid_link.html`; } get invalidVerificationLinkURL() { @@ -336,16 +315,12 @@ export class Config { get linkSendSuccessURL() { return ( - this.customPages.linkSendSuccess || - `${this.publicServerURL}/apps/link_send_success.html` + this.customPages.linkSendSuccess || `${this.publicServerURL}/apps/link_send_success.html` ); } get linkSendFailURL() { - return ( - this.customPages.linkSendFail || - `${this.publicServerURL}/apps/link_send_fail.html` - ); + return this.customPages.linkSendFail || `${this.publicServerURL}/apps/link_send_fail.html`; } get verifyEmailSuccessURL() { @@ -356,10 +331,7 @@ export class Config { } get choosePasswordURL() { - return ( - this.customPages.choosePassword || - `${this.publicServerURL}/apps/choose_password` - ); + return this.customPages.choosePassword || `${this.publicServerURL}/apps/choose_password`; } get requestResetPasswordURL() { diff --git a/src/Controllers/AdaptableController.js b/src/Controllers/AdaptableController.js index da74c63b..e078f333 100644 --- a/src/Controllers/AdaptableController.js +++ b/src/Controllers/AdaptableController.js @@ -52,27 +52,20 @@ export class AdaptableController { } // Makes sure the prototype matches - const mismatches = Object.getOwnPropertyNames(Type.prototype).reduce( - (obj, key) => { - const adapterType = typeof adapter[key]; - const expectedType = typeof Type.prototype[key]; - if (adapterType !== expectedType) { - obj[key] = { - expected: expectedType, - actual: adapterType, - }; - } - return obj; - }, - {} - ); + const mismatches = Object.getOwnPropertyNames(Type.prototype).reduce((obj, key) => { + const adapterType = typeof adapter[key]; + const expectedType = typeof Type.prototype[key]; + if (adapterType !== expectedType) { + obj[key] = { + expected: expectedType, + actual: adapterType, + }; + } + return obj; + }, {}); if (Object.keys(mismatches).length > 0) { - throw new Error( - "Adapter prototype don't match expected prototype", - adapter, - mismatches - ); + throw new Error("Adapter prototype don't match expected prototype", adapter, mismatches); } } } diff --git a/src/Controllers/DatabaseController.js b/src/Controllers/DatabaseController.js index 334494b1..5b6bfc08 100644 --- a/src/Controllers/DatabaseController.js +++ b/src/Controllers/DatabaseController.js @@ -13,10 +13,7 @@ import deepcopy from 'deepcopy'; import logger from '../logger'; import * as SchemaController from './SchemaController'; import { StorageAdapter } from '../Adapters/Storage/StorageAdapter'; -import type { - QueryOptions, - FullQueryOptions, -} from '../Adapters/Storage/StorageAdapter'; +import type { QueryOptions, FullQueryOptions } from '../Adapters/Storage/StorageAdapter'; function addWriteACL(query, acl) { const newQuery = _.cloneDeep(query); @@ -78,10 +75,7 @@ const validateQuery = (query: any): void => { if (query.$or instanceof Array) { query.$or.forEach(validateQuery); } else { - throw new Parse.Error( - Parse.Error.INVALID_QUERY, - 'Bad $or format - use an array value.' - ); + throw new Parse.Error(Parse.Error.INVALID_QUERY, 'Bad $or format - use an array value.'); } } @@ -89,10 +83,7 @@ const validateQuery = (query: any): void => { if (query.$and instanceof Array) { query.$and.forEach(validateQuery); } else { - throw new Parse.Error( - Parse.Error.INVALID_QUERY, - 'Bad $and format - use an array value.' - ); + throw new Parse.Error(Parse.Error.INVALID_QUERY, 'Bad $and format - use an array value.'); } } @@ -119,10 +110,7 @@ const validateQuery = (query: any): void => { } } if (!isSpecialQueryKey(key) && !key.match(/^[a-zA-Z][a-zA-Z0-9_\.]*$/)) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `Invalid key name: ${key}` - ); + throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid key name: ${key}`); } }); }; @@ -168,8 +156,7 @@ const filterSensitiveData = ( ); } else { pointerPermIncludesUser = - readUserFieldValue.objectId && - readUserFieldValue.objectId === userId; + readUserFieldValue.objectId && readUserFieldValue.objectId === userId; } } @@ -278,11 +265,7 @@ function expandResultOnKeyPath(object, key, value) { const path = key.split('.'); const firstKey = path[0]; const nextPath = path.slice(1).join('.'); - object[firstKey] = expandResultOnKeyPath( - object[firstKey] || {}, - nextPath, - value[firstKey] - ); + object[firstKey] = expandResultOnKeyPath(object[firstKey] || {}, nextPath, value[firstKey]); delete object[key]; return object; } @@ -319,37 +302,25 @@ const flattenUpdateOperatorsForCreate = object => { switch (object[key].__op) { case 'Increment': if (typeof object[key].amount !== 'number') { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'objects to add must be an array' - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'objects to add must be an array'); } object[key] = object[key].amount; break; case 'Add': if (!(object[key].objects instanceof Array)) { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'objects to add must be an array' - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'objects to add must be an array'); } object[key] = object[key].objects; break; case 'AddUnique': if (!(object[key].objects instanceof Array)) { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'objects to add must be an array' - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'objects to add must be an array'); } object[key] = object[key].objects; break; case 'Remove': if (!(object[key].objects instanceof Array)) { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'objects to add must be an array' - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'objects to add must be an array'); } object[key] = []; break; @@ -450,10 +421,7 @@ class DatabaseController { validateClassName(className: string): Promise { if (!SchemaController.classNameIsValid(className)) { return Promise.reject( - new Parse.Error( - Parse.Error.INVALID_CLASS_NAME, - 'invalid className: ' + className - ) + new Parse.Error(Parse.Error.INVALID_CLASS_NAME, 'invalid className: ' + className) ); } return Promise.resolve(); @@ -466,11 +434,7 @@ class DatabaseController { if (this.schemaPromise != null) { return this.schemaPromise; } - this.schemaPromise = SchemaController.load( - this.adapter, - this.schemaCache, - options - ); + this.schemaPromise = SchemaController.load(this.adapter, this.schemaCache, options); this.schemaPromise.then( () => delete this.schemaPromise, () => delete this.schemaPromise @@ -482,9 +446,7 @@ class DatabaseController { schemaController: SchemaController.SchemaController, options: LoadSchemaOptions = { clearCache: false } ): Promise { - return schemaController - ? Promise.resolve(schemaController) - : this.loadSchema(options); + return schemaController ? Promise.resolve(schemaController) : this.loadSchema(options); } // Returns a promise for the classname that is related to the given @@ -520,13 +482,7 @@ class DatabaseController { if (isMaster) { return Promise.resolve(); } - return this.canAddField( - schema, - className, - object, - aclGroup, - runOptions - ); + return this.canAddField(schema, className, object, aclGroup, runOptions); }) .then(() => { return schema.validateObject(className, object, query); @@ -550,162 +506,147 @@ class DatabaseController { var isMaster = acl === undefined; var aclGroup = acl || []; - return this.loadSchemaIfNeeded(validSchemaController).then( - schemaController => { - return (isMaster - ? Promise.resolve() - : schemaController.validatePermission(className, aclGroup, 'update') - ) - .then(() => { - relationUpdates = this.collectRelationUpdates( + return this.loadSchemaIfNeeded(validSchemaController).then(schemaController => { + return (isMaster + ? Promise.resolve() + : schemaController.validatePermission(className, aclGroup, 'update') + ) + .then(() => { + relationUpdates = this.collectRelationUpdates(className, originalQuery.objectId, update); + if (!isMaster) { + query = this.addPointerPermissions( + schemaController, className, - originalQuery.objectId, - update + 'update', + query, + aclGroup ); - if (!isMaster) { - query = this.addPointerPermissions( - schemaController, - className, - 'update', - query, - aclGroup - ); - if (addsField) { - query = { - $and: [ + if (addsField) { + query = { + $and: [ + query, + this.addPointerPermissions( + schemaController, + className, + 'addField', query, - this.addPointerPermissions( - schemaController, - className, - 'addField', - query, - aclGroup - ), - ], - }; + aclGroup + ), + ], + }; + } + } + if (!query) { + return Promise.resolve(); + } + if (acl) { + query = addWriteACL(query, acl); + } + validateQuery(query); + return schemaController + .getOneSchema(className, true) + .catch(error => { + // If the schema doesn't exist, pretend it exists with no fields. This behavior + // will likely need revisiting. + if (error === undefined) { + return { fields: {} }; } - } - if (!query) { - return Promise.resolve(); - } - if (acl) { - query = addWriteACL(query, acl); - } - validateQuery(query); - return schemaController - .getOneSchema(className, true) - .catch(error => { - // If the schema doesn't exist, pretend it exists with no fields. This behavior - // will likely need revisiting. - if (error === undefined) { - return { fields: {} }; - } - throw error; - }) - .then(schema => { - Object.keys(update).forEach(fieldName => { - if (fieldName.match(/^authData\.([a-zA-Z0-9_]+)\.id$/)) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `Invalid field name for update: ${fieldName}` - ); - } - const rootFieldName = getRootFieldName(fieldName); - if ( - !SchemaController.fieldNameIsValid(rootFieldName) && - !isSpecialUpdateKey(rootFieldName) - ) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `Invalid field name for update: ${fieldName}` - ); - } - }); - for (const updateOperation in update) { - if ( - update[updateOperation] && - typeof update[updateOperation] === 'object' && - Object.keys(update[updateOperation]).some( - innerKey => - innerKey.includes('$') || innerKey.includes('.') - ) - ) { - throw new Parse.Error( - Parse.Error.INVALID_NESTED_KEY, - "Nested keys should not contain the '$' or '.' characters" - ); - } - } - update = transformObjectACL(update); - transformAuthData(className, update, schema); - if (validateOnly) { - return this.adapter - .find(className, schema, query, {}) - .then(result => { - if (!result || !result.length) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); - } - return {}; - }); - } - if (many) { - return this.adapter.updateObjectsByQuery( - className, - schema, - query, - update, - this._transactionalSession + throw error; + }) + .then(schema => { + Object.keys(update).forEach(fieldName => { + if (fieldName.match(/^authData\.([a-zA-Z0-9_]+)\.id$/)) { + throw new Parse.Error( + Parse.Error.INVALID_KEY_NAME, + `Invalid field name for update: ${fieldName}` ); - } else if (upsert) { - return this.adapter.upsertOneObject( - className, - schema, - query, - update, - this._transactionalSession - ); - } else { - return this.adapter.findOneAndUpdate( - className, - schema, - query, - update, - this._transactionalSession + } + const rootFieldName = getRootFieldName(fieldName); + if ( + !SchemaController.fieldNameIsValid(rootFieldName) && + !isSpecialUpdateKey(rootFieldName) + ) { + throw new Parse.Error( + Parse.Error.INVALID_KEY_NAME, + `Invalid field name for update: ${fieldName}` ); } }); - }) - .then((result: any) => { - if (!result) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); - } - if (validateOnly) { - return result; - } - return this.handleRelationUpdates( - className, - originalQuery.objectId, - update, - relationUpdates - ).then(() => { - return result; + for (const updateOperation in update) { + if ( + update[updateOperation] && + typeof update[updateOperation] === 'object' && + Object.keys(update[updateOperation]).some( + innerKey => innerKey.includes('$') || innerKey.includes('.') + ) + ) { + throw new Parse.Error( + Parse.Error.INVALID_NESTED_KEY, + "Nested keys should not contain the '$' or '.' characters" + ); + } + } + update = transformObjectACL(update); + transformAuthData(className, update, schema); + if (validateOnly) { + return this.adapter.find(className, schema, query, {}).then(result => { + if (!result || !result.length) { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); + } + return {}; + }); + } + if (many) { + return this.adapter.updateObjectsByQuery( + className, + schema, + query, + update, + this._transactionalSession + ); + } else if (upsert) { + return this.adapter.upsertOneObject( + className, + schema, + query, + update, + this._transactionalSession + ); + } else { + return this.adapter.findOneAndUpdate( + className, + schema, + query, + update, + this._transactionalSession + ); + } }); - }) - .then(result => { - if (skipSanitization) { - return Promise.resolve(result); - } - return sanitizeDatabaseResult(originalUpdate, result); + }) + .then((result: any) => { + if (!result) { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); + } + if (validateOnly) { + return result; + } + return this.handleRelationUpdates( + className, + originalQuery.objectId, + update, + relationUpdates + ).then(() => { + return result; }); - } - ); + }) + .then(result => { + if (skipSanitization) { + return Promise.resolve(result); + } + return sanitizeDatabaseResult(originalUpdate, result); + }); + }); } // Collect all relation-updating operations from a REST-format update. @@ -748,12 +689,7 @@ class DatabaseController { // Processes relation-updating operations from a REST-format update. // Returns a promise that resolves when all updates have been performed - handleRelationUpdates( - className: string, - objectId: string, - update: any, - ops: any - ) { + handleRelationUpdates(className: string, objectId: string, update: any, ops: any) { var pending = []; objectId = update.objectId || objectId; ops.forEach(({ key, op }) => { @@ -762,17 +698,13 @@ class DatabaseController { } if (op.__op == 'AddRelation') { for (const object of op.objects) { - pending.push( - this.addRelation(key, className, objectId, object.objectId) - ); + pending.push(this.addRelation(key, className, objectId, object.objectId)); } } if (op.__op == 'RemoveRelation') { for (const object of op.objects) { - pending.push( - this.removeRelation(key, className, objectId, object.objectId) - ); + pending.push(this.removeRelation(key, className, objectId, object.objectId)); } } }); @@ -782,12 +714,7 @@ class DatabaseController { // Adds a relation. // Returns a promise that resolves successfully iff the add was successful. - addRelation( - key: string, - fromClassName: string, - fromId: string, - toId: string - ) { + addRelation(key: string, fromClassName: string, fromId: string, toId: string) { const doc = { relatedId: toId, owningId: fromId, @@ -804,12 +731,7 @@ class DatabaseController { // Removes a relation. // Returns a promise that resolves successfully iff the remove was // successful. - removeRelation( - key: string, - fromClassName: string, - fromId: string, - toId: string - ) { + removeRelation(key: string, fromClassName: string, fromId: string, toId: string) { var doc = { relatedId: toId, owningId: fromId, @@ -846,63 +768,55 @@ class DatabaseController { const isMaster = acl === undefined; const aclGroup = acl || []; - return this.loadSchemaIfNeeded(validSchemaController).then( - schemaController => { - return (isMaster - ? Promise.resolve() - : schemaController.validatePermission(className, aclGroup, 'delete') - ).then(() => { - if (!isMaster) { - query = this.addPointerPermissions( - schemaController, - className, - 'delete', - query, - aclGroup - ); - if (!query) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); + return this.loadSchemaIfNeeded(validSchemaController).then(schemaController => { + return (isMaster + ? Promise.resolve() + : schemaController.validatePermission(className, aclGroup, 'delete') + ).then(() => { + if (!isMaster) { + query = this.addPointerPermissions( + schemaController, + className, + 'delete', + query, + aclGroup + ); + if (!query) { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); + } + } + // delete by query + if (acl) { + query = addWriteACL(query, acl); + } + validateQuery(query); + return schemaController + .getOneSchema(className) + .catch(error => { + // If the schema doesn't exist, pretend it exists with no fields. This behavior + // will likely need revisiting. + if (error === undefined) { + return { fields: {} }; } - } - // delete by query - if (acl) { - query = addWriteACL(query, acl); - } - validateQuery(query); - return schemaController - .getOneSchema(className) - .catch(error => { - // If the schema doesn't exist, pretend it exists with no fields. This behavior - // will likely need revisiting. - if (error === undefined) { - return { fields: {} }; - } - throw error; - }) - .then(parseFormatSchema => - this.adapter.deleteObjectsByQuery( - className, - parseFormatSchema, - query, - this._transactionalSession - ) + throw error; + }) + .then(parseFormatSchema => + this.adapter.deleteObjectsByQuery( + className, + parseFormatSchema, + query, + this._transactionalSession ) - .catch(error => { - // When deleting sessions while changing passwords, don't throw an error if they don't have any sessions. - if ( - className === '_Session' && - error.code === Parse.Error.OBJECT_NOT_FOUND - ) { - return Promise.resolve({}); - } - throw error; - }); - }); - } - ); + ) + .catch(error => { + // When deleting sessions while changing passwords, don't throw an error if they don't have any sessions. + if (className === '_Session' && error.code === Parse.Error.OBJECT_NOT_FOUND) { + return Promise.resolve({}); + } + throw error; + }); + }); + }); } // Inserts an object into the database. @@ -923,11 +837,7 @@ class DatabaseController { var isMaster = acl === undefined; var aclGroup = acl || []; - const relationUpdates = this.collectRelationUpdates( - className, - null, - object - ); + const relationUpdates = this.collectRelationUpdates(className, null, object); return this.validateClassName(className) .then(() => this.loadSchemaIfNeeded(validSchemaController)) @@ -982,11 +892,7 @@ class DatabaseController { const schemaFields = Object.keys(classSchema.fields); const newKeys = fields.filter(field => { // Skip fields that are unset - if ( - object[field] && - object[field].__op && - object[field].__op === 'Delete' - ) { + if (object[field] && object[field].__op && object[field].__op === 'Delete') { return false; } return schemaFields.indexOf(field) < 0; @@ -1010,10 +916,7 @@ class DatabaseController { */ deleteEverything(fast: boolean = false): Promise { this.schemaPromise = null; - return Promise.all([ - this.adapter.deleteAllClasses(fast), - this.schemaCache.clear(), - ]); + return Promise.all([this.adapter.deleteAllClasses(fast), this.schemaCache.clear()]); } // Returns a promise for a list of related ids given an owning id. @@ -1033,22 +936,13 @@ class DatabaseController { queryOptions.skip = 0; } return this.adapter - .find( - joinTableName(className, key), - relationSchema, - { owningId }, - findOptions - ) + .find(joinTableName(className, key), relationSchema, { owningId }, findOptions) .then(results => results.map(result => result.relatedId)); } // Returns a promise for a list of owning ids given some related ids. // className here is the owning className. - owningIds( - className: string, - key: string, - relatedIds: string[] - ): Promise { + owningIds(className: string, key: string, relatedIds: string[]): Promise { return this.adapter .find( joinTableName(className, key), @@ -1069,11 +963,9 @@ class DatabaseController { const ors = query['$or']; return Promise.all( ors.map((aQuery, index) => { - return this.reduceInRelation(className, aQuery, schema).then( - aQuery => { - query['$or'][index] = aQuery; - } - ); + return this.reduceInRelation(className, aQuery, schema).then(aQuery => { + query['$or'][index] = aQuery; + }); }) ).then(() => { return Promise.resolve(query); @@ -1149,11 +1041,7 @@ class DatabaseController { // Modifies query so that it no longer has $relatedTo // Returns a promise that resolves when query is mutated - reduceRelationKeys( - className: string, - query: any, - queryOptions: any - ): ?Promise { + reduceRelationKeys(className: string, query: any, queryOptions: any): ?Promise { if (query['$or']) { return Promise.all( query['$or'].map(aQuery => { @@ -1188,12 +1076,9 @@ class DatabaseController { query.objectId && query.objectId['$in'] ? query.objectId['$in'] : null; // @flow-disable-next - const allIds: Array> = [ - idsFromString, - idsFromEq, - idsFromIn, - ids, - ].filter(list => list !== null); + const allIds: Array> = [idsFromString, idsFromEq, idsFromIn, ids].filter( + list => list !== null + ); const totalLength = allIds.reduce((memo, list) => memo + list.length, 0); let idsIntersection = []; @@ -1220,8 +1105,7 @@ class DatabaseController { } addNotInObjectIdsIds(ids: string[] = [], query: any) { - const 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); // make a set and spread to remove duplicates @@ -1282,190 +1166,162 @@ class DatabaseController { const isMaster = acl === undefined; const aclGroup = acl || []; op = - op || - (typeof query.objectId == 'string' && Object.keys(query).length === 1 - ? 'get' - : 'find'); + op || (typeof query.objectId == 'string' && Object.keys(query).length === 1 ? 'get' : 'find'); // Count operation if counting op = count === true ? 'count' : op; let classExists = true; - return this.loadSchemaIfNeeded(validSchemaController).then( - schemaController => { - //Allow volatile classes if querying with Master (for _PushStatus) - //TODO: Move volatile classes concept into mongo adapter, postgres adapter shouldn't care - //that api.parse.com breaks when _PushStatus exists in mongo. - return schemaController - .getOneSchema(className, isMaster) - .catch(error => { - // Behavior for non-existent classes is kinda weird on Parse.com. Probably doesn't matter too much. - // For now, pretend the class exists but has no objects, - if (error === undefined) { - classExists = false; - return { fields: {} }; + return this.loadSchemaIfNeeded(validSchemaController).then(schemaController => { + //Allow volatile classes if querying with Master (for _PushStatus) + //TODO: Move volatile classes concept into mongo adapter, postgres adapter shouldn't care + //that api.parse.com breaks when _PushStatus exists in mongo. + return schemaController + .getOneSchema(className, isMaster) + .catch(error => { + // Behavior for non-existent classes is kinda weird on Parse.com. Probably doesn't matter too much. + // For now, pretend the class exists but has no objects, + if (error === undefined) { + classExists = false; + return { fields: {} }; + } + throw error; + }) + .then(schema => { + // Parse.com treats queries on _created_at and _updated_at as if they were queries on createdAt and updatedAt, + // so duplicate that behavior here. If both are specified, the correct behavior to match Parse.com is to + // use the one that appears first in the sort list. + if (sort._created_at) { + sort.createdAt = sort._created_at; + delete sort._created_at; + } + if (sort._updated_at) { + sort.updatedAt = sort._updated_at; + delete sort._updated_at; + } + const queryOptions = { + skip, + limit, + sort, + keys, + readPreference, + hint, + caseInsensitive, + explain, + }; + Object.keys(sort).forEach(fieldName => { + if (fieldName.match(/^authData\.([a-zA-Z0-9_]+)\.id$/)) { + throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Cannot sort by ${fieldName}`); } - throw error; - }) - .then(schema => { - // Parse.com treats queries on _created_at and _updated_at as if they were queries on createdAt and updatedAt, - // so duplicate that behavior here. If both are specified, the correct behavior to match Parse.com is to - // use the one that appears first in the sort list. - if (sort._created_at) { - sort.createdAt = sort._created_at; - delete sort._created_at; + const rootFieldName = getRootFieldName(fieldName); + if (!SchemaController.fieldNameIsValid(rootFieldName)) { + throw new Parse.Error( + Parse.Error.INVALID_KEY_NAME, + `Invalid field name: ${fieldName}.` + ); } - if (sort._updated_at) { - sort.updatedAt = sort._updated_at; - delete sort._updated_at; - } - const queryOptions = { - skip, - limit, - sort, - keys, - readPreference, - hint, - caseInsensitive, - explain, - }; - Object.keys(sort).forEach(fieldName => { - if (fieldName.match(/^authData\.([a-zA-Z0-9_]+)\.id$/)) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `Cannot sort by ${fieldName}` + }); + return (isMaster + ? Promise.resolve() + : schemaController.validatePermission(className, aclGroup, op) + ) + .then(() => this.reduceRelationKeys(className, query, queryOptions)) + .then(() => this.reduceInRelation(className, query, schemaController)) + .then(() => { + let protectedFields; + if (!isMaster) { + query = this.addPointerPermissions( + schemaController, + className, + op, + query, + aclGroup ); - } - const rootFieldName = getRootFieldName(fieldName); - if (!SchemaController.fieldNameIsValid(rootFieldName)) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `Invalid field name: ${fieldName}.` - ); - } - }); - return (isMaster - ? Promise.resolve() - : schemaController.validatePermission(className, aclGroup, op) - ) - .then(() => - this.reduceRelationKeys(className, query, queryOptions) - ) - .then(() => - this.reduceInRelation(className, query, schemaController) - ) - .then(() => { - let protectedFields; - if (!isMaster) { - query = this.addPointerPermissions( - schemaController, - className, - op, - query, - aclGroup - ); - /* Don't use projections to optimize the protectedFields since the protectedFields + /* Don't use projections to optimize the protectedFields since the protectedFields based on pointer-permissions are determined after querying. The filtering can overwrite the protected fields. */ - protectedFields = this.addProtectedFields( - schemaController, - className, - query, - aclGroup, - auth, - queryOptions - ); + protectedFields = this.addProtectedFields( + schemaController, + className, + query, + aclGroup, + auth, + queryOptions + ); + } + if (!query) { + if (op === 'get') { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); + } else { + return []; } - if (!query) { - if (op === 'get') { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); - } else { - return []; - } + } + if (!isMaster) { + if (op === 'update' || op === 'delete') { + query = addWriteACL(query, aclGroup); + } else { + query = addReadACL(query, aclGroup); } - if (!isMaster) { - if (op === 'update' || op === 'delete') { - query = addWriteACL(query, aclGroup); - } else { - query = addReadACL(query, aclGroup); - } - } - validateQuery(query); - if (count) { - if (!classExists) { - return 0; - } else { - return this.adapter.count( - className, - schema, - query, - readPreference, - undefined, - hint - ); - } - } else if (distinct) { - if (!classExists) { - return []; - } else { - return this.adapter.distinct( - className, - schema, - query, - distinct - ); - } - } else if (pipeline) { - if (!classExists) { - return []; - } else { - return this.adapter.aggregate( - className, - schema, - pipeline, - readPreference, - hint, - explain - ); - } - } else if (explain) { - return this.adapter.find( + } + validateQuery(query); + if (count) { + if (!classExists) { + return 0; + } else { + return this.adapter.count( className, schema, query, - queryOptions + readPreference, + undefined, + hint ); - } else { - return this.adapter - .find(className, schema, query, queryOptions) - .then(objects => - objects.map(object => { - object = untransformObjectACL(object); - return filterSensitiveData( - isMaster, - aclGroup, - auth, - op, - schemaController, - className, - protectedFields, - object - ); - }) - ) - .catch(error => { - throw new Parse.Error( - Parse.Error.INTERNAL_SERVER_ERROR, - error - ); - }); } - }); - }); - } - ); + } else if (distinct) { + if (!classExists) { + return []; + } else { + return this.adapter.distinct(className, schema, query, distinct); + } + } else if (pipeline) { + if (!classExists) { + return []; + } else { + return this.adapter.aggregate( + className, + schema, + pipeline, + readPreference, + hint, + explain + ); + } + } else if (explain) { + return this.adapter.find(className, schema, query, queryOptions); + } else { + return this.adapter + .find(className, schema, query, queryOptions) + .then(objects => + objects.map(object => { + object = untransformObjectACL(object); + return filterSensitiveData( + isMaster, + aclGroup, + auth, + op, + schemaController, + className, + protectedFields, + object + ); + }) + ) + .catch(error => { + throw new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, error); + }); + } + }); + }); + }); } deleteSchema(className: string): Promise { @@ -1480,9 +1336,7 @@ class DatabaseController { }) .then((schema: any) => { return this.collectionExists(className) - .then(() => - this.adapter.count(className, { fields: {} }, null, '', false) - ) + .then(() => this.adapter.count(className, { fields: {} }, null, '', false)) .then(count => { if (count > 0) { throw new Parse.Error( @@ -1535,9 +1389,7 @@ class DatabaseController { }); const groupKey = - ['get', 'find', 'count'].indexOf(operation) > -1 - ? 'readUserFields' - : 'writeUserFields'; + ['get', 'find', 'count'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields'; const permFields = []; @@ -1712,33 +1564,27 @@ class DatabaseController { } createTransactionalSession() { - return this.adapter - .createTransactionalSession() - .then(transactionalSession => { - this._transactionalSession = transactionalSession; - }); + return this.adapter.createTransactionalSession().then(transactionalSession => { + this._transactionalSession = transactionalSession; + }); } commitTransactionalSession() { if (!this._transactionalSession) { throw new Error('There is no transactional session to commit'); } - return this.adapter - .commitTransactionalSession(this._transactionalSession) - .then(() => { - this._transactionalSession = null; - }); + return this.adapter.commitTransactionalSession(this._transactionalSession).then(() => { + this._transactionalSession = null; + }); } abortTransactionalSession() { if (!this._transactionalSession) { throw new Error('There is no transactional session to abort'); } - return this.adapter - .abortTransactionalSession(this._transactionalSession) - .then(() => { - this._transactionalSession = null; - }); + return this.adapter.abortTransactionalSession(this._transactionalSession).then(() => { + this._transactionalSession = null; + }); } // TODO: create indexes on first creation of a _User object. Otherwise it's impossible to @@ -1763,23 +1609,15 @@ class DatabaseController { }, }; - const userClassPromise = this.loadSchema().then(schema => - schema.enforceClassExists('_User') - ); - const roleClassPromise = this.loadSchema().then(schema => - schema.enforceClassExists('_Role') - ); + const userClassPromise = this.loadSchema().then(schema => schema.enforceClassExists('_User')); + const roleClassPromise = this.loadSchema().then(schema => schema.enforceClassExists('_Role')); const idempotencyClassPromise = this.adapter instanceof MongoStorageAdapter - ? this.loadSchema().then(schema => - schema.enforceClassExists('_Idempotency') - ) + ? this.loadSchema().then(schema => schema.enforceClassExists('_Idempotency')) : Promise.resolve(); const usernameUniqueness = userClassPromise - .then(() => - this.adapter.ensureUniqueness('_User', requiredUserFields, ['username']) - ) + .then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['username'])) .catch(error => { logger.warn('Unable to ensure uniqueness for usernames: ', error); throw error; @@ -1796,22 +1634,14 @@ class DatabaseController { ) ) .catch(error => { - logger.warn( - 'Unable to create case insensitive username index: ', - error - ); + logger.warn('Unable to create case insensitive username index: ', error); throw error; }); const emailUniqueness = userClassPromise - .then(() => - this.adapter.ensureUniqueness('_User', requiredUserFields, ['email']) - ) + .then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['email'])) .catch(error => { - logger.warn( - 'Unable to ensure uniqueness for user email addresses: ', - error - ); + logger.warn('Unable to ensure uniqueness for user email addresses: ', error); throw error; }); @@ -1831,9 +1661,7 @@ class DatabaseController { }); const roleUniqueness = roleClassPromise - .then(() => - this.adapter.ensureUniqueness('_Role', requiredRoleFields, ['name']) - ) + .then(() => this.adapter.ensureUniqueness('_Role', requiredRoleFields, ['name'])) .catch(error => { logger.warn('Unable to ensure uniqueness for role name: ', error); throw error; @@ -1843,17 +1671,10 @@ class DatabaseController { this.adapter instanceof MongoStorageAdapter ? idempotencyClassPromise .then(() => - this.adapter.ensureUniqueness( - '_Idempotency', - requiredIdempotencyFields, - ['reqId'] - ) + this.adapter.ensureUniqueness('_Idempotency', requiredIdempotencyFields, ['reqId']) ) .catch(error => { - logger.warn( - 'Unable to ensure uniqueness for idempotency request ID: ', - error - ); + logger.warn('Unable to ensure uniqueness for idempotency request ID: ', error); throw error; }) : Promise.resolve(); @@ -1872,10 +1693,7 @@ class DatabaseController { ) ) .catch(error => { - logger.warn( - 'Unable to create TTL index for idempotency expire date: ', - error - ); + logger.warn('Unable to create TTL index for idempotency expire date: ', error); throw error; }) : Promise.resolve(); diff --git a/src/Controllers/FilesController.js b/src/Controllers/FilesController.js index 579570ec..aaff8511 100644 --- a/src/Controllers/FilesController.js +++ b/src/Controllers/FilesController.js @@ -31,14 +31,12 @@ export class FilesController extends AdaptableController { } const location = this.adapter.getFileLocation(config, filename); - return this.adapter - .createFile(filename, data, contentType, options) - .then(() => { - return Promise.resolve({ - url: location, - name: filename, - }); + return this.adapter.createFile(filename, data, contentType, options).then(() => { + return Promise.resolve({ + url: location, + name: filename, }); + }); } deleteFile(config, filename) { @@ -80,16 +78,10 @@ export class FilesController extends AdaptableController { } else { if (filename.indexOf('tfss-') === 0) { fileObject['url'] = - 'http://files.parsetfss.com/' + - config.fileKey + - '/' + - encodeURIComponent(filename); + 'http://files.parsetfss.com/' + config.fileKey + '/' + encodeURIComponent(filename); } else if (legacyFilesRegex.test(filename)) { fileObject['url'] = - 'http://files.parse.com/' + - config.fileKey + - '/' + - encodeURIComponent(filename); + 'http://files.parse.com/' + config.fileKey + '/' + encodeURIComponent(filename); } else { fileObject['url'] = this.adapter.getFileLocation(config, filename); } diff --git a/src/Controllers/HooksController.js b/src/Controllers/HooksController.js index f7fa0375..692b2c32 100644 --- a/src/Controllers/HooksController.js +++ b/src/Controllers/HooksController.js @@ -36,9 +36,7 @@ export class HooksController { } getFunction(functionName) { - return this._getHooks({ functionName: functionName }).then( - results => results[0] - ); + return this._getHooks({ functionName: functionName }).then(results => results[0]); } getFunctions() { @@ -73,14 +71,12 @@ export class HooksController { } _getHooks(query = {}) { - return this.database - .find(DefaultHooksCollectionName, query) - .then(results => { - return results.map(result => { - delete result.objectId; - return result; - }); + return this.database.find(DefaultHooksCollectionName, query).then(results => { + return results.map(result => { + delete result.objectId; + return result; }); + }); } _removeHooks(query) { @@ -109,19 +105,9 @@ export class HooksController { var wrappedFunction = wrapToHTTPRequest(hook, this._webhookKey); wrappedFunction.url = hook.url; if (hook.className) { - triggers.addTrigger( - hook.triggerName, - hook.className, - wrappedFunction, - this._applicationId - ); + triggers.addTrigger(hook.triggerName, hook.className, wrappedFunction, this._applicationId); } else { - triggers.addFunction( - hook.functionName, - wrappedFunction, - null, - this._applicationId - ); + triggers.addFunction(hook.functionName, wrappedFunction, null, this._applicationId); } } @@ -158,26 +144,21 @@ export class HooksController { if (aHook.functionName) { return this.getFunction(aHook.functionName).then(result => { if (result) { - throw new Parse.Error( - 143, - `function name: ${aHook.functionName} already exits` - ); + throw new Parse.Error(143, `function name: ${aHook.functionName} already exits`); } else { return this.createOrUpdateHook(aHook); } }); } else if (aHook.className && aHook.triggerName) { - return this.getTrigger(aHook.className, aHook.triggerName).then( - result => { - if (result) { - throw new Parse.Error( - 143, - `class ${aHook.className} already has trigger ${aHook.triggerName}` - ); - } - return this.createOrUpdateHook(aHook); + return this.getTrigger(aHook.className, aHook.triggerName).then(result => { + if (result) { + throw new Parse.Error( + 143, + `class ${aHook.className} already has trigger ${aHook.triggerName}` + ); } - ); + return this.createOrUpdateHook(aHook); + }); } throw new Parse.Error(143, 'invalid hook declaration'); @@ -189,20 +170,15 @@ export class HooksController { if (result) { return this.createOrUpdateHook(aHook); } - throw new Parse.Error( - 143, - `no function named: ${aHook.functionName} is defined` - ); + throw new Parse.Error(143, `no function named: ${aHook.functionName} is defined`); }); } else if (aHook.className && aHook.triggerName) { - return this.getTrigger(aHook.className, aHook.triggerName).then( - result => { - if (result) { - return this.createOrUpdateHook(aHook); - } - throw new Parse.Error(143, `class ${aHook.className} does not exist`); + return this.getTrigger(aHook.className, aHook.triggerName).then(result => { + if (result) { + return this.createOrUpdateHook(aHook); } - ); + throw new Parse.Error(143, `class ${aHook.className} does not exist`); + }); } throw new Parse.Error(143, 'invalid hook declaration'); } @@ -231,17 +207,13 @@ function wrapToHTTPRequest(hook, key) { method: 'POST', }; - const agent = hook.url.startsWith('https') - ? HTTPAgents['https'] - : HTTPAgents['http']; + const agent = hook.url.startsWith('https') ? HTTPAgents['https'] : HTTPAgents['http']; jsonRequest.agent = agent; if (key) { jsonRequest.headers['X-Parse-Webhook-Key'] = key; } else { - logger.warn( - 'Making outgoing webhook request without webhookKey being set!' - ); + logger.warn('Making outgoing webhook request without webhookKey being set!'); } return request(jsonRequest).then(response => { let err; diff --git a/src/Controllers/LiveQueryController.js b/src/Controllers/LiveQueryController.js index 7ad6d977..3b239a8c 100644 --- a/src/Controllers/LiveQueryController.js +++ b/src/Controllers/LiveQueryController.js @@ -25,11 +25,7 @@ export class LiveQueryController { if (!this.hasLiveQuery(className)) { return; } - const req = this._makePublisherRequest( - currentObject, - originalObject, - classLevelPermissions - ); + const req = this._makePublisherRequest(currentObject, originalObject, classLevelPermissions); this.liveQueryPublisher.onCloudCodeAfterSave(req); } @@ -42,11 +38,7 @@ export class LiveQueryController { if (!this.hasLiveQuery(className)) { return; } - const req = this._makePublisherRequest( - currentObject, - originalObject, - classLevelPermissions - ); + const req = this._makePublisherRequest(currentObject, originalObject, classLevelPermissions); this.liveQueryPublisher.onCloudCodeAfterDelete(req); } @@ -54,11 +46,7 @@ export class LiveQueryController { return this.classNames.has(className); } - _makePublisherRequest( - currentObject: any, - originalObject: any, - classLevelPermissions: ?any - ): any { + _makePublisherRequest(currentObject: any, originalObject: any, classLevelPermissions: ?any): any { const req = { object: currentObject, }; diff --git a/src/Controllers/LoggerController.js b/src/Controllers/LoggerController.js index 54effc3d..04d3a6d7 100644 --- a/src/Controllers/LoggerController.js +++ b/src/Controllers/LoggerController.js @@ -189,8 +189,7 @@ export class LoggerController extends AdaptableController { truncateLogMessage(string) { if (string && string.length > LOG_STRING_TRUNCATE_LENGTH) { - const truncated = - string.substring(0, LOG_STRING_TRUNCATE_LENGTH) + truncationMarker; + const truncated = string.substring(0, LOG_STRING_TRUNCATE_LENGTH) + truncationMarker; return truncated; } @@ -224,10 +223,7 @@ export class LoggerController extends AdaptableController { // size (optional) Number of rows returned by search. Defaults to 10 getLogs(options = {}) { if (!this.adapter) { - throw new Parse.Error( - Parse.Error.PUSH_MISCONFIGURED, - 'Logger adapter is not available' - ); + throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Logger adapter is not available'); } if (typeof this.adapter.query !== 'function') { throw new Parse.Error( diff --git a/src/Controllers/ParseGraphQLController.js b/src/Controllers/ParseGraphQLController.js index ec23b7fd..78a5bea5 100644 --- a/src/Controllers/ParseGraphQLController.js +++ b/src/Controllers/ParseGraphQLController.js @@ -57,9 +57,7 @@ class ParseGraphQLController { return graphQLConfig; } - async updateGraphQLConfig( - graphQLConfig: ParseGraphQLConfig - ): Promise { + async updateGraphQLConfig(graphQLConfig: ParseGraphQLConfig): Promise { // throws if invalid this._validateGraphQLConfig( graphQLConfig || requiredParameter('You must provide a graphQLConfig!') @@ -97,11 +95,7 @@ class ParseGraphQLController { } _putCachedGraphQLConfig(graphQLConfig: ParseGraphQLConfig) { - return this.cacheController.graphQL.put( - this.configCacheKey, - graphQLConfig, - 60000 - ); + return this.cacheController.graphQL.put(this.configCacheKey, graphQLConfig, 60000); } _validateGraphQLConfig(graphQLConfig: ?ParseGraphQLConfig): void { @@ -119,20 +113,12 @@ class ParseGraphQLController { } = graphQLConfig; if (Object.keys(invalidKeys).length) { - errorMessages.push( - `encountered invalid keys: [${Object.keys(invalidKeys)}]` - ); + errorMessages.push(`encountered invalid keys: [${Object.keys(invalidKeys)}]`); } - if ( - enabledForClasses !== null && - !isValidStringArray(enabledForClasses) - ) { + if (enabledForClasses !== null && !isValidStringArray(enabledForClasses)) { errorMessages.push(`"enabledForClasses" is not a valid array`); } - if ( - disabledForClasses !== null && - !isValidStringArray(disabledForClasses) - ) { + if (disabledForClasses !== null && !isValidStringArray(disabledForClasses)) { errorMessages.push(`"disabledForClasses" is not a valid array`); } if (classConfigs !== null) { @@ -159,17 +145,9 @@ class ParseGraphQLController { if (!isValidSimpleObject(classConfig)) { return 'it must be a valid object'; } else { - const { - className, - type = null, - query = null, - mutation = null, - ...invalidKeys - } = classConfig; + const { className, type = null, query = null, mutation = null, ...invalidKeys } = classConfig; if (Object.keys(invalidKeys).length) { - return `"invalidKeys" [${Object.keys( - invalidKeys - )}] should not be present`; + return `"invalidKeys" [${Object.keys(invalidKeys)}] should not be present`; } if (typeof className !== 'string' || !className.trim().length) { // TODO consider checking class exists in schema? @@ -190,10 +168,7 @@ class ParseGraphQLController { return `"type" contains invalid keys, [${Object.keys(invalidKeys)}]`; } else if (outputFields !== null && !isValidStringArray(outputFields)) { return `"outputFields" must be a valid string array`; - } else if ( - constraintFields !== null && - !isValidStringArray(constraintFields) - ) { + } else if (constraintFields !== null && !isValidStringArray(constraintFields)) { return `"constraintFields" must be a valid string array`; } if (sortFields !== null) { @@ -214,10 +189,7 @@ class ParseGraphQLController { if (typeof field !== 'string' || field.trim().length === 0) { errorMessage = `"sortField" at index ${index} did not provide the "field" as a string`; return false; - } else if ( - typeof asc !== 'boolean' || - typeof desc !== 'boolean' - ) { + } else if (typeof asc !== 'boolean' || typeof desc !== 'boolean') { errorMessage = `"sortField" at index ${index} did not provide "asc" or "desc" as booleans`; return false; } @@ -234,15 +206,9 @@ class ParseGraphQLController { } if (inputFields !== null) { if (isValidSimpleObject(inputFields)) { - const { - create = null, - update = null, - ...invalidKeys - } = inputFields; + const { create = null, update = null, ...invalidKeys } = inputFields; if (Object.keys(invalidKeys).length) { - return `"inputFields" contains invalid keys: [${Object.keys( - invalidKeys - )}]`; + return `"inputFields" contains invalid keys: [${Object.keys(invalidKeys)}]`; } else { if (update !== null && !isValidStringArray(update)) { return `"inputFields.update" must be a valid string array`; @@ -250,10 +216,7 @@ class ParseGraphQLController { if (!isValidStringArray(create)) { return `"inputFields.create" must be a valid string array`; } else if (className === '_User') { - if ( - !create.includes('username') || - !create.includes('password') - ) { + if (!create.includes('username') || !create.includes('password')) { return `"inputFields.create" must include required fields, username and password`; } } @@ -274,9 +237,7 @@ class ParseGraphQLController { ...invalidKeys } = query; if (Object.keys(invalidKeys).length) { - return `"query" contains invalid keys, [${Object.keys( - invalidKeys - )}]`; + return `"query" contains invalid keys, [${Object.keys(invalidKeys)}]`; } else if (find !== null && typeof find !== 'boolean') { return `"query.find" must be a boolean`; } else if (get !== null && typeof get !== 'boolean') { @@ -302,9 +263,7 @@ class ParseGraphQLController { ...invalidKeys } = mutation; if (Object.keys(invalidKeys).length) { - return `"mutation" contains invalid keys, [${Object.keys( - invalidKeys - )}]`; + return `"mutation" contains invalid keys, [${Object.keys(invalidKeys)}]`; } if (create !== null && typeof create !== 'boolean') { return `"mutation.create" must be a boolean`; diff --git a/src/Controllers/PushController.js b/src/Controllers/PushController.js index 47392358..1a5b9bf4 100644 --- a/src/Controllers/PushController.js +++ b/src/Controllers/PushController.js @@ -6,19 +6,9 @@ import { pushStatusHandler } from '../StatusHandler'; import { applyDeviceTokenExists } from '../Push/utils'; export class PushController { - sendPush( - body = {}, - where = {}, - config, - auth, - onPushStatusSaved = () => {}, - now = new Date() - ) { + sendPush(body = {}, where = {}, config, auth, onPushStatusSaved = () => {}, now = new Date()) { if (!config.hasPushSupport) { - throw new Parse.Error( - Parse.Error.PUSH_MISCONFIGURED, - 'Missing push configuration' - ); + throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Missing push configuration'); } // Replace the expiration_time and push_time with a valid Unix epoch milliseconds time @@ -32,10 +22,7 @@ export class PushController { } // Immediate push - if ( - body.expiration_interval && - !Object.prototype.hasOwnProperty.call(body, 'push_time') - ) { + if (body.expiration_interval && !Object.prototype.hasOwnProperty.call(body, 'push_time')) { const ttlMs = body.expiration_interval * 1000; body.expiration_time = new Date(now.valueOf() + ttlMs).valueOf(); } @@ -73,12 +60,7 @@ export class PushController { const updateWhere = applyDeviceTokenExists(where); badgeUpdate = () => { // Build a real RestQuery so we can use it in RestWrite - const restQuery = new RestQuery( - config, - master(config), - '_Installation', - updateWhere - ); + const restQuery = new RestQuery(config, master(config), '_Installation', updateWhere); return restQuery.buildRestWhere().then(() => { const write = new RestWrite( config, @@ -129,13 +111,7 @@ export class PushController { ) { return Promise.resolve(); } - return config.pushControllerQueue.enqueue( - body, - where, - config, - auth, - pushStatus - ); + return config.pushControllerQueue.enqueue(body, where, config, auth, pushStatus); }) .catch(err => { return pushStatus.fail(err).then(() => { @@ -150,10 +126,7 @@ export class PushController { * @returns {Number|undefined} The expiration time if it exists in the request */ static getExpirationTime(body = {}) { - var hasExpirationTime = Object.prototype.hasOwnProperty.call( - body, - 'expiration_time' - ); + var hasExpirationTime = Object.prototype.hasOwnProperty.call(body, 'expiration_time'); if (!hasExpirationTime) { return; } @@ -180,19 +153,13 @@ export class PushController { } static getExpirationInterval(body = {}) { - const hasExpirationInterval = Object.prototype.hasOwnProperty.call( - body, - 'expiration_interval' - ); + const hasExpirationInterval = Object.prototype.hasOwnProperty.call(body, 'expiration_interval'); if (!hasExpirationInterval) { return; } var expirationIntervalParam = body['expiration_interval']; - if ( - typeof expirationIntervalParam !== 'number' || - expirationIntervalParam <= 0 - ) { + if (typeof expirationIntervalParam !== 'number' || expirationIntervalParam <= 0) { throw new Parse.Error( Parse.Error.PUSH_MISCONFIGURED, `expiration_interval must be a number greater than 0` @@ -248,8 +215,7 @@ export class PushController { static pushTimeHasTimezoneComponent(pushTimeParam: string): boolean { const offsetPattern = /(.+)([+-])\d\d:\d\d$/; return ( - pushTimeParam.indexOf('Z') === pushTimeParam.length - 1 || // 2007-04-05T12:30Z - offsetPattern.test(pushTimeParam) + pushTimeParam.indexOf('Z') === pushTimeParam.length - 1 || offsetPattern.test(pushTimeParam) // 2007-04-05T12:30Z ); // 2007-04-05T12:30.000+02:00, 2007-04-05T12:30.000-02:00 } @@ -259,13 +225,7 @@ export class PushController { * @param isLocalTime {boolean} * @returns {string} */ - static formatPushTime({ - date, - isLocalTime, - }: { - date: Date, - isLocalTime: boolean, - }) { + static formatPushTime({ date, isLocalTime }: { date: Date, isLocalTime: boolean }) { if (isLocalTime) { // Strip 'Z' const isoString = date.toISOString(); diff --git a/src/Controllers/SchemaCache.js b/src/Controllers/SchemaCache.js index 55d70eab..9fe79daa 100644 --- a/src/Controllers/SchemaCache.js +++ b/src/Controllers/SchemaCache.js @@ -7,11 +7,7 @@ import defaults from '../defaults'; export default class SchemaCache { cache: Object; - constructor( - cacheController, - ttl = defaults.schemaCacheTTL, - singleCache = false - ) { + constructor(cacheController, ttl = defaults.schemaCacheTTL, singleCache = false) { this.ttl = ttl; if (typeof ttl == 'string') { this.ttl = parseInt(ttl); diff --git a/src/Controllers/SchemaController.js b/src/Controllers/SchemaController.js index fb559dfb..a35126f3 100644 --- a/src/Controllers/SchemaController.js +++ b/src/Controllers/SchemaController.js @@ -260,11 +260,7 @@ const CLPValidKeys = Object.freeze([ ]); // validation before setting class-level permissions on collection -function validateCLP( - perms: ClassLevelPermissions, - fields: SchemaFields, - userIdRegExp: RegExp -) { +function validateCLP(perms: ClassLevelPermissions, fields: SchemaFields, userIdRegExp: RegExp) { if (!perms) { return; } @@ -282,10 +278,7 @@ function validateCLP( // throws when root fields are of wrong type validateCLPjson(operation, operationKey); - if ( - operationKey === 'readUserFields' || - operationKey === 'writeUserFields' - ) { + if (operationKey === 'readUserFields' || operationKey === 'writeUserFields') { // validate grouped pointer permissions // must be an array with field names for (const fieldName of operation) { @@ -397,11 +390,7 @@ function validateCLPjson(operation: any, operationKey: string) { } } -function validatePointerPermission( - fieldName: string, - fields: Object, - operation: string -) { +function validatePointerPermission(fieldName: string, fields: Object, operation: string) { // Uses collection schema to ensure the field is of type: // - Pointer<_User> (pointers) // - Array @@ -412,8 +401,7 @@ function validatePointerPermission( if ( !( fields[fieldName] && - ((fields[fieldName].type == 'Pointer' && - fields[fieldName].targetClass == '_User') || + ((fields[fieldName].type == 'Pointer' && fields[fieldName].targetClass == '_User') || fields[fieldName].type == 'Array') ) ) { @@ -444,10 +432,7 @@ function fieldNameIsValid(fieldName: string): boolean { } // Checks that it's not trying to clobber one of the default fields of the class. -function fieldNameIsValidForClass( - fieldName: string, - className: string -): boolean { +function fieldNameIsValidForClass(fieldName: string, className: string): boolean { if (!fieldNameIsValid(fieldName)) { return false; } @@ -468,10 +453,7 @@ function invalidClassNameMessage(className: string): string { ); } -const invalidJsonError = new Parse.Error( - Parse.Error.INVALID_JSON, - 'invalid JSON' -); +const invalidJsonError = new Parse.Error(Parse.Error.INVALID_JSON, 'invalid JSON'); const validNonRelationOrPointerTypes = [ 'Number', 'String', @@ -492,10 +474,7 @@ const fieldTypeIsInvalid = ({ type, targetClass }) => { } else if (typeof targetClass !== 'string') { return invalidJsonError; } else if (!classNameIsValid(targetClass)) { - return new Parse.Error( - Parse.Error.INVALID_CLASS_NAME, - invalidClassNameMessage(targetClass) - ); + return new Parse.Error(Parse.Error.INVALID_CLASS_NAME, invalidClassNameMessage(targetClass)); } else { return undefined; } @@ -504,10 +483,7 @@ const fieldTypeIsInvalid = ({ type, targetClass }) => { return invalidJsonError; } if (validNonRelationOrPointerTypes.indexOf(type) < 0) { - return new Parse.Error( - Parse.Error.INCORRECT_TYPE, - `invalid field type: ${type}` - ); + return new Parse.Error(Parse.Error.INCORRECT_TYPE, `invalid field type: ${type}`); } return undefined; }; @@ -563,18 +539,14 @@ class SchemaData { data.classLevelPermissions = deepcopy(schema.classLevelPermissions); data.indexes = schema.indexes; - const classProtectedFields = this.__protectedFields[ - schema.className - ]; + const classProtectedFields = this.__protectedFields[schema.className]; if (classProtectedFields) { for (const key in classProtectedFields) { const unq = new Set([ ...(data.classLevelPermissions.protectedFields[key] || []), ...classProtectedFields[key], ]); - data.classLevelPermissions.protectedFields[key] = Array.from( - unq - ); + data.classLevelPermissions.protectedFields[key] = Array.from(unq); } } @@ -608,12 +580,7 @@ class SchemaData { } } -const injectDefaultSchema = ({ - className, - fields, - classLevelPermissions, - indexes, -}: Schema) => { +const injectDefaultSchema = ({ className, fields, classLevelPermissions, indexes }: Schema) => { const defaultSchema: Schema = { className, fields: { @@ -684,10 +651,7 @@ const VolatileClassesSchemas = [ _IdempotencySchema, ]; -const dbTypeMatchesObjectType = ( - dbType: SchemaField | string, - objectType: SchemaField -) => { +const dbTypeMatchesObjectType = (dbType: SchemaField | string, objectType: SchemaField) => { if (dbType.type !== objectType.type) return false; if (dbType.targetClass !== objectType.targetClass) return false; if (dbType === objectType.type) return true; @@ -749,9 +713,7 @@ export default class SchemaController { return this.reloadDataPromise; } - getAllClasses( - options: LoadSchemaOptions = { clearCache: false } - ): Promise> { + getAllClasses(options: LoadSchemaOptions = { clearCache: false }): Promise> { if (options.clearCache) { return this.setAllClasses(); } @@ -771,9 +733,7 @@ export default class SchemaController { /* eslint-disable no-console */ this._cache .setAllClasses(allSchemas) - .catch(error => - console.error('Error saving schema to cache:', error) - ); + .catch(error => console.error('Error saving schema to cache:', error)); /* eslint-enable no-console */ return allSchemas; }); @@ -803,9 +763,7 @@ export default class SchemaController { return Promise.resolve(cached); } return this.setAllClasses().then(allSchemas => { - const oneSchema = allSchemas.find( - schema => schema.className === className - ); + const oneSchema = allSchemas.find(schema => schema.className === className); if (!oneSchema) { return Promise.reject(undefined); } @@ -828,18 +786,12 @@ export default class SchemaController { classLevelPermissions: any, indexes: any = {} ): Promise { - var validationError = this.validateNewClass( - className, - fields, - classLevelPermissions - ); + var validationError = this.validateNewClass(className, fields, classLevelPermissions); if (validationError) { if (validationError instanceof Parse.Error) { return Promise.reject(validationError); } else if (validationError.code && validationError.error) { - return Promise.reject( - new Parse.Error(validationError.code, validationError.error) - ); + return Promise.reject(new Parse.Error(validationError.code, validationError.error)); } return Promise.reject(validationError); } @@ -883,21 +835,14 @@ export default class SchemaController { throw new Parse.Error(255, `Field ${name} exists, cannot update.`); } if (!existingFields[name] && field.__op === 'Delete') { - throw new Parse.Error( - 255, - `Field ${name} does not exist, cannot delete.` - ); + throw new Parse.Error(255, `Field ${name} does not exist, cannot delete.`); } }); delete existingFields._rperm; delete existingFields._wperm; - const newSchema = buildMergedSchemaObject( - existingFields, - submittedFields - ); - const defaultFields = - defaultColumns[className] || defaultColumns._Default; + const newSchema = buildMergedSchemaObject(existingFields, submittedFields); + const defaultFields = defaultColumns[className] || defaultColumns._Default; const fullNewSchema = Object.assign({}, newSchema, defaultFields); const validationError = this.validateSchemaData( className, @@ -938,11 +883,7 @@ export default class SchemaController { }) .then(results => { enforceFields = results.filter(result => !!result); - return this.setPermissions( - className, - classLevelPermissions, - newSchema - ); + return this.setPermissions(className, classLevelPermissions, newSchema); }) .then(() => this._dbAdapter.setIndexesWithSchemaFormat( @@ -1004,32 +945,19 @@ export default class SchemaController { if (this.schemaData[className]) { return this; } else { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - `Failed to add ${className}` - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, `Failed to add ${className}`); } }) .catch(() => { // The schema still doesn't validate. Give up - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'schema class name does not revalidate' - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'schema class name does not revalidate'); }) ); } - validateNewClass( - className: string, - fields: SchemaFields = {}, - classLevelPermissions: any - ): any { + validateNewClass(className: string, fields: SchemaFields = {}, classLevelPermissions: any): any { if (this.schemaData[className]) { - throw new Parse.Error( - Parse.Error.INVALID_CLASS_NAME, - `Class ${className} already exists.` - ); + throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} already exists.`); } if (!classNameIsValid(className)) { return { @@ -1037,12 +965,7 @@ export default class SchemaController { error: invalidClassNameMessage(className), }; } - return this.validateSchemaData( - className, - fields, - classLevelPermissions, - [] - ); + return this.validateSchemaData(className, fields, classLevelPermissions, []); } validateSchemaData( @@ -1072,15 +995,10 @@ export default class SchemaController { let defaultValueType = getType(fieldType.defaultValue); if (typeof defaultValueType === 'string') { defaultValueType = { type: defaultValueType }; - } else if ( - typeof defaultValueType === 'object' && - fieldType.type === 'Relation' - ) { + } else if (typeof defaultValueType === 'object' && fieldType.type === 'Relation') { return { code: Parse.Error.INCORRECT_TYPE, - error: `The 'default value' option is not applicable for ${typeToString( - fieldType - )}`, + error: `The 'default value' option is not applicable for ${typeToString(fieldType)}`, }; } if (!dbTypeMatchesObjectType(fieldType, defaultValueType)) { @@ -1095,9 +1013,7 @@ export default class SchemaController { if (typeof fieldType === 'object' && fieldType.type === 'Relation') { return { code: Parse.Error.INCORRECT_TYPE, - error: `The 'required' option is not applicable for ${typeToString( - fieldType - )}`, + error: `The 'required' option is not applicable for ${typeToString(fieldType)}`, }; } } @@ -1138,21 +1054,14 @@ export default class SchemaController { // object if the provided className-fieldName-type tuple is valid. // The className must already be validated. // If 'freeze' is true, refuse to update the schema for this field. - enforceFieldExists( - className: string, - fieldName: string, - type: string | SchemaField - ) { + enforceFieldExists(className: string, fieldName: string, type: string | SchemaField) { if (fieldName.indexOf('.') > 0) { // subdocument key (x.y) => ok if x is of type 'object' fieldName = fieldName.split('.')[0]; type = 'Object'; } if (!fieldNameIsValid(fieldName)) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `Invalid field name: ${fieldName}.` - ); + throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid field name: ${fieldName}.`); } // If someone tries to create a new field with null/undefined as the value, return; @@ -1222,20 +1131,13 @@ export default class SchemaController { type = { type: type }; } if (!expectedType || !dbTypeMatchesObjectType(expectedType, type)) { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - `Could not add field ${fieldName}` - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, `Could not add field ${fieldName}`); } } } // maintain compatibility - deleteField( - fieldName: string, - className: string, - database: DatabaseController - ) { + deleteField(fieldName: string, className: string, database: DatabaseController) { return this.deleteFields([fieldName], className, database); } @@ -1246,24 +1148,14 @@ export default class SchemaController { // Passing the database and prefix is necessary in order to drop relation collections // and remove fields from objects. Ideally the database would belong to // a database adapter and this function would close over it or access it via member. - deleteFields( - fieldNames: Array, - className: string, - database: DatabaseController - ) { + deleteFields(fieldNames: Array, className: string, database: DatabaseController) { if (!classNameIsValid(className)) { - throw new Parse.Error( - Parse.Error.INVALID_CLASS_NAME, - invalidClassNameMessage(className) - ); + throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, invalidClassNameMessage(className)); } fieldNames.forEach(fieldName => { if (!fieldNameIsValid(fieldName)) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - `invalid field name: ${fieldName}` - ); + throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, `invalid field name: ${fieldName}`); } //Don't allow deleting the default fields. if (!fieldNameIsValidForClass(fieldName, className)) { @@ -1285,30 +1177,23 @@ export default class SchemaController { .then(schema => { fieldNames.forEach(fieldName => { if (!schema.fields[fieldName]) { - throw new Parse.Error( - 255, - `Field ${fieldName} does not exist, cannot delete.` - ); + throw new Parse.Error(255, `Field ${fieldName} does not exist, cannot delete.`); } }); const schemaFields = { ...schema.fields }; - return database.adapter - .deleteFields(className, schema, fieldNames) - .then(() => { - return Promise.all( - fieldNames.map(fieldName => { - const field = schemaFields[fieldName]; - if (field && field.type === 'Relation') { - //For relations, drop the _Join table - return database.adapter.deleteClass( - `_Join:${fieldName}:${className}` - ); - } - return Promise.resolve(); - }) - ); - }); + return database.adapter.deleteFields(className, schema, fieldNames).then(() => { + return Promise.all( + fieldNames.map(fieldName => { + const field = schemaFields[fieldName]; + if (field && field.type === 'Relation') { + //For relations, drop the _Join table + return database.adapter.deleteClass(`_Join:${fieldName}:${className}`); + } + return Promise.resolve(); + }) + ); + }); }) .then(() => this._cache.clear()); } @@ -1380,19 +1265,12 @@ export default class SchemaController { }); if (missingColumns.length > 0) { - throw new Parse.Error( - Parse.Error.INCORRECT_TYPE, - missingColumns[0] + ' is required.' - ); + throw new Parse.Error(Parse.Error.INCORRECT_TYPE, missingColumns[0] + ' is required.'); } return Promise.resolve(this); } - testPermissionsForClassName( - className: string, - aclGroup: string[], - operation: string - ) { + testPermissionsForClassName(className: string, aclGroup: string[], operation: string) { return SchemaController.testPermissions( this.getClassLevelPermissions(className), aclGroup, @@ -1401,11 +1279,7 @@ export default class SchemaController { } // Tests that the class level permission let pass the operation for a given aclGroup - static testPermissions( - classPermissions: ?any, - aclGroup: string[], - operation: string - ): boolean { + static testPermissions(classPermissions: ?any, aclGroup: string[], operation: string): boolean { if (!classPermissions || !classPermissions[operation]) { return true; } @@ -1432,9 +1306,7 @@ export default class SchemaController { operation: string, action?: string ) { - if ( - SchemaController.testPermissions(classPermissions, aclGroup, operation) - ) { + if (SchemaController.testPermissions(classPermissions, aclGroup, operation)) { return Promise.resolve(); } @@ -1465,9 +1337,7 @@ export default class SchemaController { // No matching CLP, let's check the Pointer permissions // And handle those later const permissionField = - ['get', 'find', 'count'].indexOf(operation) > -1 - ? 'readUserFields' - : 'writeUserFields'; + ['get', 'find', 'count'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields'; // Reject create when write lockdown if (permissionField == 'writeUserFields' && operation == 'create') { @@ -1501,12 +1371,7 @@ export default class SchemaController { } // Validates an operation passes class-level-permissions set in the schema - validatePermission( - className: string, - aclGroup: string[], - operation: string, - action?: string - ) { + validatePermission(className: string, aclGroup: string[], operation: string, action?: string) { return SchemaController.validatePermission( this.getClassLevelPermissions(className), className, @@ -1517,18 +1382,12 @@ export default class SchemaController { } getClassLevelPermissions(className: string): any { - return ( - this.schemaData[className] && - this.schemaData[className].classLevelPermissions - ); + return this.schemaData[className] && this.schemaData[className].classLevelPermissions; } // Returns the expected type for a className+key combination // or undefined if the schema is not set - getExpectedType( - className: string, - fieldName: string - ): ?(SchemaField | string) { + getExpectedType(className: string, fieldName: string): ?(SchemaField | string) { if (this.schemaData[className]) { const expectedType = this.schemaData[className].fields[fieldName]; return expectedType === 'map' ? 'Object' : expectedType; @@ -1560,10 +1419,7 @@ const load = ( // does not include the default fields, as it is intended to be passed // to mongoSchemaFromFieldsAndClassName. No validation is done here, it // is done in mongoSchemaFromFieldsAndClassName. -function buildMergedSchemaObject( - existingFields: SchemaFields, - putRequest: any -): SchemaFields { +function buildMergedSchemaObject(existingFields: SchemaFields, putRequest: any): SchemaFields { const newSchema = {}; // @flow-disable-next const sysSchemaField = @@ -1578,14 +1434,10 @@ function buildMergedSchemaObject( oldField !== 'createdAt' && oldField !== 'objectId' ) { - if ( - sysSchemaField.length > 0 && - sysSchemaField.indexOf(oldField) !== -1 - ) { + if (sysSchemaField.length > 0 && sysSchemaField.indexOf(oldField) !== -1) { continue; } - const fieldIsDeleted = - putRequest[oldField] && putRequest[oldField].__op === 'Delete'; + const fieldIsDeleted = putRequest[oldField] && putRequest[oldField].__op === 'Delete'; if (!fieldIsDeleted) { newSchema[oldField] = existingFields[oldField]; } @@ -1593,10 +1445,7 @@ function buildMergedSchemaObject( } for (const newField in putRequest) { if (newField !== 'objectId' && putRequest[newField].__op !== 'Delete') { - if ( - sysSchemaField.length > 0 && - sysSchemaField.indexOf(newField) !== -1 - ) { + if (sysSchemaField.length > 0 && sysSchemaField.indexOf(newField) !== -1) { continue; } newSchema[newField] = putRequest[newField]; @@ -1692,10 +1541,7 @@ function getObjectType(obj): ?(SchemaField | string) { } break; } - throw new Parse.Error( - Parse.Error.INCORRECT_TYPE, - 'This is not a valid ' + obj.__type - ); + throw new Parse.Error(Parse.Error.INCORRECT_TYPE, 'This is not a valid ' + obj.__type); } if (obj['$ne']) { return getObjectType(obj['$ne']); diff --git a/src/Controllers/UserController.js b/src/Controllers/UserController.js index 42e9390c..d853f7fe 100644 --- a/src/Controllers/UserController.js +++ b/src/Controllers/UserController.js @@ -95,16 +95,12 @@ export class UserController extends AdaptableController { throw 'Failed to reset password: username / email / token is invalid'; } - if ( - this.config.passwordPolicy && - this.config.passwordPolicy.resetTokenValidityDuration - ) { + if (this.config.passwordPolicy && this.config.passwordPolicy.resetTokenValidityDuration) { let expiresDate = results[0]._perishable_token_expires_at; if (expiresDate && expiresDate.__type == 'Date') { expiresDate = new Date(expiresDate.iso); } - if (expiresDate < new Date()) - throw 'The password reset link has expired'; + if (expiresDate < new Date()) throw 'The password reset link has expired'; } return results[0]; @@ -123,12 +119,7 @@ export class UserController extends AdaptableController { where.email = user.email; } - var query = new RestQuery( - this.config, - Auth.master(this.config), - '_User', - where - ); + var query = new RestQuery(this.config, Auth.master(this.config), '_User', where); return query.execute().then(function (result) { if (result.results.length != 1) { throw undefined; @@ -146,12 +137,7 @@ export class UserController extends AdaptableController { this.getUserIfNeeded(user).then(user => { const username = encodeURIComponent(user.username); - const link = buildEmailLink( - this.config.verifyEmailURL, - username, - token, - this.config - ); + const link = buildEmailLink(this.config.verifyEmailURL, username, token, this.config); const options = { appName: this.config.appName, link: link, @@ -173,11 +159,7 @@ export class UserController extends AdaptableController { */ regenerateEmailVerifyToken(user) { this.setEmailVerifyToken(user); - return this.config.database.update( - '_User', - { username: user.username }, - user - ); + return this.config.database.update('_User', { username: user.username }, user); } resendVerificationEmail(username) { @@ -194,10 +176,7 @@ export class UserController extends AdaptableController { setPasswordResetToken(email) { const token = { _perishable_token: randomString(25) }; - if ( - this.config.passwordPolicy && - this.config.passwordPolicy.resetTokenValidityDuration - ) { + if (this.config.passwordPolicy && this.config.passwordPolicy.resetTokenValidityDuration) { token._perishable_token_expires_at = Parse._encode( this.config.generatePasswordResetTokenExpiresAt() ); @@ -278,9 +257,7 @@ export class UserController extends AdaptableController { 'Hi,\n\n' + 'You requested to reset your password for ' + appName + - (user.get('username') - ? " (your username is '" + user.get('username') + "')" - : '') + + (user.get('username') ? " (your username is '" + user.get('username') + "')" : '') + '.\n\n' + '' + 'Click here to reset it:\n' + @@ -308,10 +285,7 @@ function buildEmailLink(destination, username, token, config) { const usernameAndToken = `token=${token}&username=${username}`; if (config.parseFrameURL) { - const destinationWithoutHost = destination.replace( - config.publicServerURL, - '' - ); + const destinationWithoutHost = destination.replace(config.publicServerURL, ''); return `${config.parseFrameURL}?link=${encodeURIComponent( destinationWithoutHost diff --git a/src/Controllers/index.js b/src/Controllers/index.js index 5bbd9308..1e4765b6 100644 --- a/src/Controllers/index.js +++ b/src/Controllers/index.js @@ -67,9 +67,7 @@ export function getControllers(options: ParseServerOptions) { }; } -export function getLoggerController( - options: ParseServerOptions -): LoggerController { +export function getLoggerController(options: ParseServerOptions): LoggerController { const { appId, jsonLogs, @@ -88,25 +86,12 @@ export function getLoggerController( silent, maxLogFiles, }; - const loggerControllerAdapter = loadAdapter( - loggerAdapter, - WinstonLoggerAdapter, - loggerOptions - ); + const loggerControllerAdapter = loadAdapter(loggerAdapter, WinstonLoggerAdapter, loggerOptions); return new LoggerController(loggerControllerAdapter, appId, loggerOptions); } -export function getFilesController( - options: ParseServerOptions -): FilesController { - const { - appId, - databaseURI, - filesAdapter, - databaseAdapter, - preserveFileName, - fileKey, - } = options; +export function getFilesController(options: ParseServerOptions): FilesController { + const { appId, databaseURI, filesAdapter, databaseAdapter, preserveFileName, fileKey } = options; if (!filesAdapter && databaseAdapter) { throw 'When using an explicit database adapter, you must also use an explicit filesAdapter.'; } @@ -126,15 +111,13 @@ export function getUserController(options: ParseServerOptions): UserController { }); } -export function getCacheController( - options: ParseServerOptions -): CacheController { +export function getCacheController(options: ParseServerOptions): CacheController { const { appId, cacheAdapter, cacheTTL, cacheMaxSize } = options; - const cacheControllerAdapter = loadAdapter( - cacheAdapter, - InMemoryCacheAdapter, - { appId: appId, ttl: cacheTTL, maxSize: cacheMaxSize } - ); + const cacheControllerAdapter = loadAdapter(cacheAdapter, InMemoryCacheAdapter, { + appId: appId, + ttl: cacheTTL, + maxSize: cacheMaxSize, + }); return new CacheController(cacheControllerAdapter, appId); } @@ -148,20 +131,13 @@ export function getParseGraphQLController( }); } -export function getAnalyticsController( - options: ParseServerOptions -): AnalyticsController { +export function getAnalyticsController(options: ParseServerOptions): AnalyticsController { const { analyticsAdapter } = options; - const analyticsControllerAdapter = loadAdapter( - analyticsAdapter, - AnalyticsAdapter - ); + const analyticsControllerAdapter = loadAdapter(analyticsAdapter, AnalyticsAdapter); return new AnalyticsController(analyticsControllerAdapter); } -export function getLiveQueryController( - options: ParseServerOptions -): LiveQueryController { +export function getLiveQueryController(options: ParseServerOptions): LiveQueryController { return new LiveQueryController(options.liveQuery); } @@ -185,11 +161,7 @@ export function getDatabaseController( ) { throw 'You cannot specify both a databaseAdapter and a databaseURI/databaseOptions/collectionPrefix.'; } else if (!databaseAdapter) { - databaseAdapter = getDatabaseAdapter( - databaseURI, - collectionPrefix, - databaseOptions - ); + databaseAdapter = getDatabaseAdapter(databaseURI, collectionPrefix, databaseOptions); } else { databaseAdapter = loadAdapter(databaseAdapter); } @@ -214,9 +186,7 @@ interface PushControlling { pushWorker: PushWorker; } -export function getPushController( - options: ParseServerOptions -): PushControlling { +export function getPushController(options: ParseServerOptions): PushControlling { const { scheduledPush, push } = options; const pushOptions = Object.assign({}, push); @@ -258,11 +228,7 @@ export function getAuthDataManager(options: ParseServerOptions) { return authDataManager(auth, enableAnonymousUsers); } -export function getDatabaseAdapter( - databaseURI, - collectionPrefix, - databaseOptions -) { +export function getDatabaseAdapter(databaseURI, collectionPrefix, databaseOptions) { let protocol; try { const parsedURI = url.parse(databaseURI); diff --git a/src/GraphQL/ParseGraphQLSchema.js b/src/GraphQL/ParseGraphQLSchema.js index 87287f02..09626644 100644 --- a/src/GraphQL/ParseGraphQLSchema.js +++ b/src/GraphQL/ParseGraphQLSchema.js @@ -1,10 +1,5 @@ import Parse from 'parse/node'; -import { - GraphQLSchema, - GraphQLObjectType, - DocumentNode, - GraphQLNamedType, -} from 'graphql'; +import { GraphQLSchema, GraphQLObjectType, DocumentNode, GraphQLNamedType } from 'graphql'; import { stitchSchemas } from '@graphql-tools/stitch'; import { SchemaDirectiveVisitor } from '@graphql-tools/utils'; import requiredParameter from '../requiredParameter'; @@ -14,9 +9,7 @@ import * as parseClassQueries from './loaders/parseClassQueries'; import * as parseClassMutations from './loaders/parseClassMutations'; import * as defaultGraphQLQueries from './loaders/defaultGraphQLQueries'; import * as defaultGraphQLMutations from './loaders/defaultGraphQLMutations'; -import ParseGraphQLController, { - ParseGraphQLConfig, -} from '../Controllers/ParseGraphQLController'; +import ParseGraphQLController, { ParseGraphQLConfig } from '../Controllers/ParseGraphQLController'; import DatabaseController from '../Controllers/DatabaseController'; import { toGraphQLError } from './parseGraphQLUtils'; import * as schemaDirectives from './loaders/schemaDirectives'; @@ -72,12 +65,7 @@ class ParseGraphQLSchema { parseGraphQLConfig: ParseGraphQLConfig; log: any; appId: string; - graphQLCustomTypeDefs: ?( - | string - | GraphQLSchema - | DocumentNode - | GraphQLNamedType[] - ); + graphQLCustomTypeDefs: ?(string | GraphQLSchema | DocumentNode | GraphQLNamedType[]); constructor( params: { @@ -85,12 +73,7 @@ class ParseGraphQLSchema { parseGraphQLController: ParseGraphQLController, log: any, appId: string, - graphQLCustomTypeDefs: ?( - | string - | GraphQLSchema - | DocumentNode - | GraphQLNamedType[] - ), + graphQLCustomTypeDefs: ?(string | GraphQLSchema | DocumentNode | GraphQLNamedType[]), } = {} ) { this.parseGraphQLController = @@ -99,11 +82,9 @@ class ParseGraphQLSchema { this.databaseController = params.databaseController || requiredParameter('You must provide a databaseController instance!'); - this.log = - params.log || requiredParameter('You must provide a log instance!'); + this.log = params.log || requiredParameter('You must provide a log instance!'); this.graphQLCustomTypeDefs = params.graphQLCustomTypeDefs; - this.appId = - params.appId || requiredParameter('You must provide the appId!'); + this.appId = params.appId || requiredParameter('You must provide the appId!'); } async load() { @@ -216,59 +197,45 @@ class ParseGraphQLSchema { } } }; - Object.values(customGraphQLSchemaTypeMap).forEach( - customGraphQLSchemaType => { - if ( - !customGraphQLSchemaType || - !customGraphQLSchemaType.name || - customGraphQLSchemaType.name.startsWith('__') - ) { - return; - } - const autoGraphQLSchemaType = this.graphQLAutoSchema.getType( - customGraphQLSchemaType.name - ); - if (!autoGraphQLSchemaType) { - this.graphQLAutoSchema._typeMap[ - customGraphQLSchemaType.name - ] = customGraphQLSchemaType; - } + Object.values(customGraphQLSchemaTypeMap).forEach(customGraphQLSchemaType => { + if ( + !customGraphQLSchemaType || + !customGraphQLSchemaType.name || + customGraphQLSchemaType.name.startsWith('__') + ) { + return; } - ); - Object.values(customGraphQLSchemaTypeMap).forEach( - customGraphQLSchemaType => { - if ( - !customGraphQLSchemaType || - !customGraphQLSchemaType.name || - customGraphQLSchemaType.name.startsWith('__') - ) { - return; - } - const autoGraphQLSchemaType = this.graphQLAutoSchema.getType( - customGraphQLSchemaType.name - ); + const autoGraphQLSchemaType = this.graphQLAutoSchema.getType( + customGraphQLSchemaType.name + ); + if (!autoGraphQLSchemaType) { + this.graphQLAutoSchema._typeMap[customGraphQLSchemaType.name] = customGraphQLSchemaType; + } + }); + Object.values(customGraphQLSchemaTypeMap).forEach(customGraphQLSchemaType => { + if ( + !customGraphQLSchemaType || + !customGraphQLSchemaType.name || + customGraphQLSchemaType.name.startsWith('__') + ) { + return; + } + const autoGraphQLSchemaType = this.graphQLAutoSchema.getType( + customGraphQLSchemaType.name + ); - if ( - autoGraphQLSchemaType && - typeof customGraphQLSchemaType.getFields === 'function' - ) { - Object.values(customGraphQLSchemaType.getFields()).forEach( - field => { - findAndReplaceLastType(field, 'type'); - } - ); - autoGraphQLSchemaType._fields = { - ...autoGraphQLSchemaType.getFields(), - ...customGraphQLSchemaType.getFields(), - }; - } + if (autoGraphQLSchemaType && typeof customGraphQLSchemaType.getFields === 'function') { + Object.values(customGraphQLSchemaType.getFields()).forEach(field => { + findAndReplaceLastType(field, 'type'); + }); + autoGraphQLSchemaType._fields = { + ...autoGraphQLSchemaType.getFields(), + ...customGraphQLSchemaType.getFields(), + }; } - ); + }); this.graphQLSchema = stitchSchemas({ - schemas: [ - this.graphQLSchemaDirectivesDefinitions, - this.graphQLAutoSchema, - ], + schemas: [this.graphQLSchemaDirectivesDefinitions, this.graphQLAutoSchema], mergeDirectives: true, }); } else if (typeof this.graphQLCustomTypeDefs === 'function') { @@ -300,20 +267,17 @@ class ParseGraphQLSchema { ); if (graphQLCustomTypeDef) { const graphQLSchemaTypeFieldMap = graphQLSchemaType.getFields(); - Object.keys(graphQLSchemaTypeFieldMap).forEach( - graphQLSchemaTypeFieldName => { - const graphQLSchemaTypeField = - graphQLSchemaTypeFieldMap[graphQLSchemaTypeFieldName]; - if (!graphQLSchemaTypeField.astNode) { - const astNode = graphQLCustomTypeDef.fields.find( - field => field.name.value === graphQLSchemaTypeFieldName - ); - if (astNode) { - graphQLSchemaTypeField.astNode = astNode; - } + Object.keys(graphQLSchemaTypeFieldMap).forEach(graphQLSchemaTypeFieldName => { + const graphQLSchemaTypeField = graphQLSchemaTypeFieldMap[graphQLSchemaTypeFieldName]; + if (!graphQLSchemaTypeField.astNode) { + const astNode = graphQLCustomTypeDef.fields.find( + field => field.name.value === graphQLSchemaTypeFieldName + ); + if (astNode) { + graphQLSchemaTypeField.astNode = astNode; } } - ); + }); } } }); @@ -329,12 +293,7 @@ class ParseGraphQLSchema { return this.graphQLSchema; } - addGraphQLType( - type, - throwError = false, - ignoreReserved = false, - ignoreConnection = false - ) { + addGraphQLType(type, throwError = false, ignoreReserved = false, ignoreConnection = false) { if ( (!ignoreReserved && RESERVED_GRAPHQL_TYPE_NAMES.includes(type.name)) || this.graphQLTypes.find(existingType => existingType.name === type.name) || @@ -351,12 +310,7 @@ class ParseGraphQLSchema { return type; } - addGraphQLQuery( - fieldName, - field, - throwError = false, - ignoreReserved = false - ) { + addGraphQLQuery(fieldName, field, throwError = false, ignoreReserved = false) { if ( (!ignoreReserved && RESERVED_GRAPHQL_QUERY_NAMES.includes(fieldName)) || this.graphQLQueries[fieldName] @@ -372,15 +326,9 @@ class ParseGraphQLSchema { return field; } - addGraphQLMutation( - fieldName, - field, - throwError = false, - ignoreReserved = false - ) { + addGraphQLMutation(fieldName, field, throwError = false, ignoreReserved = false) { if ( - (!ignoreReserved && - RESERVED_GRAPHQL_MUTATION_NAMES.includes(fieldName)) || + (!ignoreReserved && RESERVED_GRAPHQL_MUTATION_NAMES.includes(fieldName)) || this.graphQLMutations[fieldName] ) { const message = `Mutation ${fieldName} could not be added to the auto schema because it collided with an existing field.`; @@ -455,10 +403,7 @@ class ParseGraphQLSchema { * that provide the parseClass along with * its parseClassConfig where provided. */ - _getParseClassesWithConfig( - parseClasses, - parseGraphQLConfig: ParseGraphQLConfig - ) { + _getParseClassesWithConfig(parseClasses, parseGraphQLConfig: ParseGraphQLConfig) { const { classConfigs } = parseGraphQLConfig; // Make sures that the default classes and classes that @@ -488,9 +433,7 @@ class ParseGraphQLSchema { return parseClasses.sort(sortClasses).map(parseClass => { let parseClassConfig; if (classConfigs) { - parseClassConfig = classConfigs.find( - c => c.className === parseClass.className - ); + parseClassConfig = classConfigs.find(c => c.className === parseClass.className); } return [parseClass, parseClassConfig]; }); @@ -521,16 +464,10 @@ class ParseGraphQLSchema { parseGraphQLConfig: ?ParseGraphQLConfig, functionNamesString: string, }): boolean { - const { - parseClasses, - parseClassesString, - parseGraphQLConfig, - functionNamesString, - } = params; + const { parseClasses, parseClassesString, parseGraphQLConfig, functionNamesString } = params; if ( - JSON.stringify(this.parseGraphQLConfig) === - JSON.stringify(parseGraphQLConfig) && + JSON.stringify(this.parseGraphQLConfig) === JSON.stringify(parseGraphQLConfig) && this.functionNamesString === functionNamesString ) { if (this.parseClasses === parseClasses) { diff --git a/src/GraphQL/ParseGraphQLServer.js b/src/GraphQL/ParseGraphQLServer.js index 5426cf5f..bb47ca29 100644 --- a/src/GraphQL/ParseGraphQLServer.js +++ b/src/GraphQL/ParseGraphQLServer.js @@ -9,25 +9,20 @@ import { handleParseErrors, handleParseHeaders } from '../middlewares'; import requiredParameter from '../requiredParameter'; import defaultLogger from '../logger'; import { ParseGraphQLSchema } from './ParseGraphQLSchema'; -import ParseGraphQLController, { - ParseGraphQLConfig, -} from '../Controllers/ParseGraphQLController'; +import ParseGraphQLController, { ParseGraphQLConfig } from '../Controllers/ParseGraphQLController'; class ParseGraphQLServer { parseGraphQLController: ParseGraphQLController; constructor(parseServer, config) { - this.parseServer = - parseServer || - requiredParameter('You must provide a parseServer instance!'); + this.parseServer = parseServer || requiredParameter('You must provide a parseServer instance!'); if (!config || !config.graphQLPath) { requiredParameter('You must provide a config.graphQLPath!'); } this.config = config; this.parseGraphQLController = this.parseServer.config.parseGraphQLController; this.log = - (this.parseServer.config && this.parseServer.config.loggerController) || - defaultLogger; + (this.parseServer.config && this.parseServer.config.loggerController) || defaultLogger; this.parseGraphQLSchema = new ParseGraphQLSchema({ parseGraphQLController: this.parseGraphQLController, databaseController: this.parseServer.config.databaseController, @@ -52,9 +47,7 @@ class ParseGraphQLServer { }, }; } catch (e) { - this.log.error( - e.stack || (typeof e.toString === 'function' && e.toString()) || e - ); + this.log.error(e.stack || (typeof e.toString === 'function' && e.toString()) || e); throw e; } } @@ -101,9 +94,7 @@ class ParseGraphQLServer { } app.get( this.config.playgroundPath || - requiredParameter( - 'You must provide a config.playgroundPath to applyPlayground!' - ), + requiredParameter('You must provide a config.playgroundPath to applyPlayground!'), (_req, res) => { res.setHeader('Content-Type', 'text/html'); res.write( @@ -128,19 +119,13 @@ class ParseGraphQLServer { execute, subscribe, onOperation: async (_message, params, webSocket) => - Object.assign( - {}, - params, - await this._getGraphQLOptions(webSocket.upgradeReq) - ), + Object.assign({}, params, await this._getGraphQLOptions(webSocket.upgradeReq)), }, { server, path: this.config.subscriptionsPath || - requiredParameter( - 'You must provide a config.subscriptionsPath to createSubscriptions!' - ), + requiredParameter('You must provide a config.subscriptionsPath to createSubscriptions!'), } ); } diff --git a/src/GraphQL/parseGraphQLUtils.js b/src/GraphQL/parseGraphQLUtils.js index bc51c1b5..0bd6ad2b 100644 --- a/src/GraphQL/parseGraphQLUtils.js +++ b/src/GraphQL/parseGraphQLUtils.js @@ -3,10 +3,7 @@ import { ApolloError } from 'apollo-server-core'; export function enforceMasterKeyAccess(auth) { if (!auth.isMaster) { - throw new Parse.Error( - Parse.Error.OPERATION_FORBIDDEN, - 'unauthorized: master key is required' - ); + throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'unauthorized: master key is required'); } } @@ -22,12 +19,10 @@ export function toGraphQLError(error) { return new ApolloError(message, code); } -export const extractKeysAndInclude = (selectedFields) => { - selectedFields = selectedFields.filter( - (field) => !field.includes('__typename') - ); +export const extractKeysAndInclude = selectedFields => { + selectedFields = selectedFields.filter(field => !field.includes('__typename')); // Handles "id" field for both current and included objects - selectedFields = selectedFields.map((field) => { + selectedFields = selectedFields.map(field => { if (field === 'id') return 'objectId'; return field.endsWith('.id') ? `${field.substring(0, field.lastIndexOf('.id'))}.objectId` diff --git a/src/LiveQuery/Client.js b/src/LiveQuery/Client.js index 253234b9..56d1baed 100644 --- a/src/LiveQuery/Client.js +++ b/src/LiveQuery/Client.js @@ -3,13 +3,7 @@ import logger from '../logger'; import type { FlattenedObjectData } from './Subscription'; export type Message = { [attr: string]: any }; -const dafaultFields = [ - 'className', - 'objectId', - 'updatedAt', - 'createdAt', - 'ACL', -]; +const dafaultFields = ['className', 'objectId', 'updatedAt', 'createdAt', 'ACL']; class Client { id: number; @@ -110,10 +104,7 @@ class Client { } response['object'] = this._toJSONWithFields(parseObjectJSON, fields); if (parseOriginalObjectJSON) { - response['original'] = this._toJSONWithFields( - parseOriginalObjectJSON, - fields - ); + response['original'] = this._toJSONWithFields(parseOriginalObjectJSON, fields); } } Client.pushResponse(this.parseWebSocket, JSON.stringify(response)); diff --git a/src/LiveQuery/ParseLiveQueryServer.js b/src/LiveQuery/ParseLiveQueryServer.js index 60468523..34a1756c 100644 --- a/src/LiveQuery/ParseLiveQueryServer.js +++ b/src/LiveQuery/ParseLiveQueryServer.js @@ -93,11 +93,7 @@ class ParseLiveQueryServer { } else if (channel === Parse.applicationId + 'afterDelete') { this._onAfterDelete(message); } else { - logger.error( - 'Get message %s from unknown channel %j', - message, - channel - ); + logger.error('Get message %s from unknown channel %j', message, channel); } }); } @@ -131,11 +127,7 @@ class ParseLiveQueryServer { let deletedParseObject = message.currentParseObject.toJSON(); const classLevelPermissions = message.classLevelPermissions; 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); const classSubscriptions = this.subscriptions.get(className); @@ -144,16 +136,11 @@ class ParseLiveQueryServer { return; } for (const subscription of classSubscriptions.values()) { - const isSubscriptionMatched = this._matchesSubscription( - deletedParseObject, - subscription - ); + const isSubscriptionMatched = this._matchesSubscription(deletedParseObject, subscription); if (!isSubscriptionMatched) { continue; } - for (const [clientId, requestIds] of _.entries( - subscription.clientRequestIds - )) { + for (const [clientId, requestIds] of _.entries(subscription.clientRequestIds)) { const client = this.clients.get(clientId); if (typeof client === 'undefined') { continue; @@ -163,13 +150,7 @@ class ParseLiveQueryServer { // Check CLP const op = this._getCLPOperation(subscription.query); let res = {}; - this._matchesCLP( - classLevelPermissions, - message.currentParseObject, - client, - requestId, - op - ) + this._matchesCLP(classLevelPermissions, message.currentParseObject, client, requestId, op) .then(() => { // Check ACL return this._matchesACL(acl, client, requestId); @@ -230,11 +211,7 @@ class ParseLiveQueryServer { const classLevelPermissions = message.classLevelPermissions; let currentParseObject = message.currentParseObject.toJSON(); 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); const classSubscriptions = this.subscriptions.get(className); @@ -251,9 +228,7 @@ class ParseLiveQueryServer { currentParseObject, subscription ); - for (const [clientId, requestIds] of _.entries( - subscription.clientRequestIds - )) { + for (const [clientId, requestIds] of _.entries(subscription.clientRequestIds)) { const client = this.clients.get(clientId); if (typeof client === 'undefined') { continue; @@ -269,11 +244,7 @@ class ParseLiveQueryServer { if (message.originalParseObject) { originalACL = message.originalParseObject.getACL(); } - originalACLCheckingPromise = this._matchesACL( - originalACL, - client, - requestId - ); + originalACLCheckingPromise = this._matchesACL(originalACL, client, requestId); } // Set current ParseObject ACL checking promise, if the object does not match // subscription, we do not need to check ACL @@ -283,25 +254,12 @@ class ParseLiveQueryServer { currentACLCheckingPromise = Promise.resolve(false); } else { const currentACL = message.currentParseObject.getACL(); - currentACLCheckingPromise = this._matchesACL( - currentACL, - client, - requestId - ); + currentACLCheckingPromise = this._matchesACL(currentACL, client, requestId); } const op = this._getCLPOperation(subscription.query); - this._matchesCLP( - classLevelPermissions, - message.currentParseObject, - client, - requestId, - op - ) + this._matchesCLP(classLevelPermissions, message.currentParseObject, client, requestId, op) .then(() => { - return Promise.all([ - originalACLCheckingPromise, - currentACLCheckingPromise, - ]); + return Promise.all([originalACLCheckingPromise, currentACLCheckingPromise]); }) .then(([isOriginalMatched, isCurrentMatched]) => { logger.verbose( @@ -350,22 +308,16 @@ class ParseLiveQueryServer { } if (res.object && typeof res.object.toJSON === 'function') { currentParseObject = res.object.toJSON(); - currentParseObject.className = - res.object.className || className; + currentParseObject.className = res.object.className || className; } if (res.original && typeof res.original.toJSON === 'function') { originalParseObject = res.original.toJSON(); - originalParseObject.className = - res.original.className || className; + originalParseObject.className = res.original.className || className; } const functionName = 'push' + message.event; if (client[functionName]) { - client[functionName]( - requestId, - currentParseObject, - originalParseObject - ); + client[functionName](requestId, currentParseObject, originalParseObject); } }, error => { @@ -447,16 +399,12 @@ class ParseLiveQueryServer { this.clients.delete(clientId); // Delete client from subscriptions - for (const [requestId, subscriptionInfo] of _.entries( - client.subscriptionInfos - )) { + for (const [requestId, subscriptionInfo] of _.entries(client.subscriptionInfos)) { const subscription = subscriptionInfo.subscription; subscription.deleteClientSubscription(clientId, requestId); // If there is no client which is subscribing this subscription, remove it from subscriptions - const classSubscriptions = this.subscriptions.get( - subscription.className - ); + const classSubscriptions = this.subscriptions.get(subscription.className); if (!subscription.hasSubscribingClient()) { classSubscriptions.delete(subscription.hash); } @@ -492,9 +440,7 @@ class ParseLiveQueryServer { return matchesQuery(parseObject, subscription.query); } - getAuthForSessionToken( - sessionToken: ?string - ): Promise<{ auth: ?Auth, userId: ?string }> { + getAuthForSessionToken(sessionToken: ?string): Promise<{ auth: ?Auth, userId: ?string }> { if (!sessionToken) { return Promise.resolve({}); } @@ -514,11 +460,7 @@ class ParseLiveQueryServer { const result = {}; if (error && error.code === Parse.Error.INVALID_SESSION_TOKEN) { result.error = error; - this.authCache.set( - sessionToken, - Promise.resolve(result), - this.config.cacheTimeout - ); + this.authCache.set(sessionToken, Promise.resolve(result), this.config.cacheTimeout); } else { this.authCache.del(sessionToken); } @@ -540,9 +482,7 @@ class ParseLiveQueryServer { const aclGroup = ['*']; let userId; if (typeof subscriptionInfo !== 'undefined') { - const { userId } = await this.getAuthForSessionToken( - subscriptionInfo.sessionToken - ); + const { userId } = await this.getAuthForSessionToken(subscriptionInfo.sessionToken); if (userId) { aclGroup.push(userId); } @@ -602,9 +542,7 @@ class ParseLiveQueryServer { return Promise.resolve() .then(async () => { // 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:') - ); + const acl_has_roles = Object.keys(acl.permissionsById).some(key => key.startsWith('role:')); if (!acl_has_roles) { return false; } @@ -624,11 +562,7 @@ class ParseLiveQueryServer { }); } - async _matchesACL( - acl: any, - client: any, - requestId: number - ): Promise { + async _matchesACL(acl: any, client: any, requestId: number): Promise { // Return true directly if ACL isn't present, ACL is public read, or client has master key if (!acl || acl.getPublicReadAccess() || client.hasMasterKey) { return true; @@ -685,12 +619,7 @@ class ParseLiveQueryServer { client.pushConnect(); runLiveQueryEventHandlers(req); } catch (error) { - Client.pushError( - parseWebsocket, - error.code || 141, - error.message || error, - false - ); + Client.pushError(parseWebsocket, error.code || 141, error.message || error, false); logger.error( `Failed running beforeConnect for session ${request.sessionToken} with:\n Error: ` + JSON.stringify(error) @@ -699,17 +628,10 @@ class ParseLiveQueryServer { } _hasMasterKey(request: any, validKeyPairs: any): boolean { - if ( - !validKeyPairs || - validKeyPairs.size == 0 || - !validKeyPairs.has('masterKey') - ) { + if (!validKeyPairs || validKeyPairs.size == 0 || !validKeyPairs.has('masterKey')) { return false; } - if ( - !request || - !Object.prototype.hasOwnProperty.call(request, 'masterKey') - ) { + if (!request || !Object.prototype.hasOwnProperty.call(request, 'masterKey')) { return false; } return request.masterKey === validKeyPairs.get('masterKey'); @@ -738,9 +660,7 @@ class ParseLiveQueryServer { 2, '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' - ); + logger.error('Can not find this client, make sure you connect to server before subscribing'); return; } const client = this.clients.get(parseWebsocket.clientId); @@ -760,11 +680,7 @@ class ParseLiveQueryServer { if (classSubscriptions.has(subscriptionHash)) { subscription = classSubscriptions.get(subscriptionHash); } else { - subscription = new Subscription( - className, - request.query.where, - subscriptionHash - ); + subscription = new Subscription(className, request.query.where, subscriptionHash); classSubscriptions.set(subscriptionHash, subscription); } @@ -782,10 +698,7 @@ class ParseLiveQueryServer { client.addSubscriptionInfo(request.requestId, subscriptionInfo); // Add clientId to subscription - subscription.addClientSubscription( - parseWebsocket.clientId, - request.requestId - ); + subscription.addClientSubscription(parseWebsocket.clientId, request.requestId); client.pushSubscribe(request.requestId); @@ -803,13 +716,7 @@ class ParseLiveQueryServer { installationId: client.installationId, }); } catch (e) { - Client.pushError( - parseWebsocket, - e.code || 141, - e.message || e, - false, - request.requestId - ); + Client.pushError(parseWebsocket, e.code || 141, e.message || e, false, request.requestId); logger.error( `Failed running beforeSubscribe on ${className} for session ${request.sessionToken} with:\n Error: ` + JSON.stringify(e) @@ -822,11 +729,7 @@ class ParseLiveQueryServer { this._handleSubscribe(parseWebsocket, request); } - _handleUnsubscribe( - parseWebsocket: any, - request: any, - notifyClient: boolean = true - ): any { + _handleUnsubscribe(parseWebsocket: any, request: any, notifyClient: boolean = true): any { // If we can not find this client, return error to client if (!Object.prototype.hasOwnProperty.call(parseWebsocket, 'clientId')) { Client.pushError( diff --git a/src/LiveQuery/ParsePubSub.js b/src/LiveQuery/ParsePubSub.js index c8678abb..34b1d0c2 100644 --- a/src/LiveQuery/ParsePubSub.js +++ b/src/LiveQuery/ParsePubSub.js @@ -14,11 +14,7 @@ ParsePubSub.createPublisher = function (config: any): any { if (useRedis(config)) { return RedisPubSub.createPublisher(config); } else { - const adapter = loadAdapter( - config.pubSubAdapter, - EventEmitterPubSub, - config - ); + const adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config); if (typeof adapter.createPublisher !== 'function') { throw 'pubSubAdapter should have createPublisher()'; } @@ -30,11 +26,7 @@ ParsePubSub.createSubscriber = function (config: any): void { if (useRedis(config)) { return RedisPubSub.createSubscriber(config); } else { - const adapter = loadAdapter( - config.pubSubAdapter, - EventEmitterPubSub, - config - ); + const adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config); if (typeof adapter.createSubscriber !== 'function') { throw 'pubSubAdapter should have createSubscriber()'; } diff --git a/src/LiveQuery/QueryTools.js b/src/LiveQuery/QueryTools.js index f3471bd1..03be6cfe 100644 --- a/src/LiveQuery/QueryTools.js +++ b/src/LiveQuery/QueryTools.js @@ -99,10 +99,7 @@ function contains(haystack: Array, needle: any): boolean { if (typeof ptr === 'string' && ptr === needle.objectId) { return true; } - if ( - ptr.className === needle.className && - ptr.objectId === needle.objectId - ) { + if (ptr.className === needle.className && ptr.objectId === needle.objectId) { return true; } } @@ -118,8 +115,7 @@ function contains(haystack: Array, needle: any): boolean { */ function matchesQuery(object: any, query: any): boolean { if (query instanceof Parse.Query) { - var className = - object.id instanceof Id ? object.id.className : object.className; + var className = object.id instanceof Id ? object.id.className : object.className; if (className !== query.className) { return false; } @@ -158,11 +154,7 @@ function matchesKeyConstraints(object, key, constraints) { var keyComponents = key.split('.'); var subObjectKey = keyComponents[0]; var keyRemainder = keyComponents.slice(1).join('.'); - return matchesKeyConstraints( - object[subObjectKey] || {}, - keyRemainder, - constraints - ); + return matchesKeyConstraints(object[subObjectKey] || {}, keyRemainder, constraints); } var i; if (key === '$or') { @@ -200,11 +192,7 @@ function matchesKeyConstraints(object, key, constraints) { }); } - return equalObjectsGeneric( - object[key], - Parse._decode(key, constraints), - equalObjects - ); + return equalObjectsGeneric(object[key], Parse._decode(key, constraints), equalObjects); } // More complex cases for (var condition in constraints) { @@ -263,10 +251,7 @@ function matchesKeyConstraints(object, key, constraints) { // tries to submit a non-boolean for $exits outside the SDKs, just ignore it. break; } - if ( - (!propertyExists && existenceIsRequired) || - (propertyExists && !existenceIsRequired) - ) { + if ((!propertyExists && existenceIsRequired) || (propertyExists && !existenceIsRequired)) { return false; } break; @@ -311,10 +296,7 @@ function matchesKeyConstraints(object, key, constraints) { } var southWest = compareTo.$box[0]; var northEast = compareTo.$box[1]; - if ( - southWest.latitude > northEast.latitude || - southWest.longitude > northEast.longitude - ) { + if (southWest.latitude > northEast.latitude || southWest.longitude > northEast.longitude) { // Invalid box, crosses the date line return false; } diff --git a/src/LiveQuery/SessionTokenCache.js b/src/LiveQuery/SessionTokenCache.js index e2cb164c..0eb4c2ea 100644 --- a/src/LiveQuery/SessionTokenCache.js +++ b/src/LiveQuery/SessionTokenCache.js @@ -16,10 +16,7 @@ function userForSessionToken(sessionToken) { class SessionTokenCache { cache: Object; - constructor( - timeout: number = 30 * 24 * 60 * 60 * 1000, - maxSize: number = 10000 - ) { + constructor(timeout: number = 30 * 24 * 60 * 60 * 1000, maxSize: number = 10000) { this.cache = new LRU({ max: maxSize, maxAge: timeout, @@ -32,30 +29,18 @@ class SessionTokenCache { } const userId = this.cache.get(sessionToken); 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 Promise.resolve(userId); } return userForSessionToken(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); const userId = user.id; this.cache.set(sessionToken, userId); return Promise.resolve(userId); }, error => { - logger.error( - 'Can not fetch userId for sessionToken %j, error %j', - sessionToken, - error - ); + logger.error('Can not fetch userId for sessionToken %j, error %j', sessionToken, error); return Promise.reject(error); } ); diff --git a/src/LiveQuery/Subscription.js b/src/LiveQuery/Subscription.js index 7a88abc1..83df0b83 100644 --- a/src/LiveQuery/Subscription.js +++ b/src/LiveQuery/Subscription.js @@ -34,11 +34,7 @@ class Subscription { const index = requestIds.indexOf(requestId); 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; } requestIds.splice(index, 1); diff --git a/src/Options/Definitions.js b/src/Options/Definitions.js index 1d4f2b21..b33a26b4 100644 --- a/src/Options/Definitions.js +++ b/src/Options/Definitions.js @@ -65,8 +65,7 @@ module.exports.ParseServerOptions = { }, cacheTTL: { env: 'PARSE_SERVER_CACHE_TTL', - help: - 'Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)', + help: 'Sets the TTL for the in memory cache (in ms), defaults to 5000 (5 seconds)', action: parsers.numberParser('cacheTTL'), default: 5000, }, @@ -80,8 +79,7 @@ module.exports.ParseServerOptions = { }, cluster: { env: 'PARSE_SERVER_CLUSTER', - help: - 'Run with cluster, optionally set the number of processes default to os.cpus().length', + help: 'Run with cluster, optionally set the number of processes default to os.cpus().length', action: parsers.numberOrBooleanParser, }, collectionPrefix: { @@ -107,8 +105,7 @@ module.exports.ParseServerOptions = { }, databaseURI: { env: 'PARSE_SERVER_DATABASE_URI', - help: - 'The full URI to your database. Supported databases are mongodb or postgres.', + help: 'The full URI to your database. Supported databases are mongodb or postgres.', required: true, default: 'mongodb://localhost:27017/parse', }, @@ -154,8 +151,7 @@ module.exports.ParseServerOptions = { }, expireInactiveSessions: { env: 'PARSE_SERVER_EXPIRE_INACTIVE_SESSIONS', - help: - 'Sets wether we should expire the inactive sessions, defaults to true', + help: 'Sets wether we should expire the inactive sessions, defaults to true', action: parsers.booleanParser, default: true, }, @@ -205,8 +201,7 @@ module.exports.ParseServerOptions = { }, liveQueryServerOptions: { env: 'PARSE_SERVER_LIVE_QUERY_SERVER_OPTIONS', - help: - 'Live query server configuration options (will start the liveQuery server)', + help: 'Live query server configuration options (will start the liveQuery server)', action: parsers.objectParser, }, loggerAdapter: { @@ -220,8 +215,7 @@ module.exports.ParseServerOptions = { }, logsFolder: { env: 'PARSE_SERVER_LOGS_FOLDER', - help: - "Folder for the logs (defaults to './logs'); set to null to disable file based logging", + help: "Folder for the logs (defaults to './logs'); set to null to disable file based logging", default: './logs', }, masterKey: { @@ -231,8 +225,7 @@ module.exports.ParseServerOptions = { }, masterKeyIps: { env: 'PARSE_SERVER_MASTER_KEY_IPS', - help: - 'Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)', + help: 'Restrict masterKey to be used by only these ips, defaults to [] (allow all ips)', action: parsers.arrayParser, default: [], }, @@ -310,8 +303,7 @@ module.exports.ParseServerOptions = { }, protectedFields: { env: 'PARSE_SERVER_PROTECTED_FIELDS', - help: - 'Protected fields that should be treated with extra security when fetching details.', + help: 'Protected fields that should be treated with extra security when fetching details.', action: parsers.objectParser, default: { _User: { @@ -331,8 +323,7 @@ module.exports.ParseServerOptions = { }, readOnlyMasterKey: { env: 'PARSE_SERVER_READ_ONLY_MASTER_KEY', - help: - 'Read-only key, which has the same capabilities as MasterKey without writes', + help: 'Read-only key, which has the same capabilities as MasterKey without writes', }, restAPIKey: { env: 'PARSE_SERVER_REST_API_KEY', diff --git a/src/ParseMessageQueue.js b/src/ParseMessageQueue.js index 1dcf55d5..b2ff53f5 100644 --- a/src/ParseMessageQueue.js +++ b/src/ParseMessageQueue.js @@ -3,24 +3,16 @@ import { EventEmitterMQ } from './Adapters/MessageQueue/EventEmitterMQ'; const ParseMessageQueue = {}; -ParseMessageQueue.createPublisher = function(config: any): any { - const adapter = loadAdapter( - config.messageQueueAdapter, - EventEmitterMQ, - config - ); +ParseMessageQueue.createPublisher = function (config: any): any { + const adapter = loadAdapter(config.messageQueueAdapter, EventEmitterMQ, config); if (typeof adapter.createPublisher !== 'function') { throw 'pubSubAdapter should have createPublisher()'; } return adapter.createPublisher(config); }; -ParseMessageQueue.createSubscriber = function(config: any): void { - const adapter = loadAdapter( - config.messageQueueAdapter, - EventEmitterMQ, - config - ); +ParseMessageQueue.createSubscriber = function (config: any): void { + const adapter = loadAdapter(config.messageQueueAdapter, EventEmitterMQ, config); if (typeof adapter.createSubscriber !== 'function') { throw 'messageQueueAdapter should have createSubscriber()'; } diff --git a/src/ParseServer.js b/src/ParseServer.js index 383ad467..a607ec15 100644 --- a/src/ParseServer.js +++ b/src/ParseServer.js @@ -67,11 +67,7 @@ class ParseServer { const allControllers = controllers.getControllers(options); - const { - loggerController, - databaseController, - hooksController, - } = allControllers; + const { loggerController, databaseController, hooksController } = allControllers; this.config = Config.put(Object.assign({}, options, allControllers)); logging.setLogger(loggerController); @@ -116,10 +112,7 @@ class ParseServer { handleShutdown() { const promises = []; const { adapter: databaseAdapter } = this.config.databaseController; - if ( - databaseAdapter && - typeof databaseAdapter.handleShutdown === 'function' - ) { + if (databaseAdapter && typeof databaseAdapter.handleShutdown === 'function') { promises.push(databaseAdapter.handleShutdown()); } const { adapter: fileAdapter } = this.config.filesController; @@ -130,10 +123,7 @@ class ParseServer { if (cacheAdapter && typeof cacheAdapter.handleShutdown === 'function') { promises.push(cacheAdapter.handleShutdown()); } - return (promises.length > 0 - ? Promise.all(promises) - : Promise.resolve() - ).then(() => { + return (promises.length > 0 ? Promise.all(promises) : Promise.resolve()).then(() => { if (this.config.serverCloseComplete) { this.config.serverCloseComplete(); } @@ -164,11 +154,7 @@ class ParseServer { }); }); - api.use( - '/', - bodyParser.urlencoded({ extended: false }), - new PublicAPIRouter().expressRouter() - ); + api.use('/', bodyParser.urlencoded({ extended: false }), new PublicAPIRouter().expressRouter()); api.use(bodyParser.json({ type: '*/*', limit: maxUploadSize })); api.use(middlewares.allowMethodOverride); @@ -186,9 +172,7 @@ class ParseServer { process.on('uncaughtException', err => { if (err.code === 'EADDRINUSE') { // user-friendly message for this common error - process.stderr.write( - `Unable to listen on port ${err.port}. The port is already in use.` - ); + process.stderr.write(`Unable to listen on port ${err.port}. The port is already in use.`); process.exit(0); } else { throw err; @@ -200,13 +184,8 @@ class ParseServer { ParseServer.verifyServerUrl(); }); } - if ( - process.env.PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS === '1' || - directAccess - ) { - Parse.CoreManager.setRESTController( - ParseServerRESTController(appId, appRouter) - ); + if (process.env.PARSE_SERVER_ENABLE_EXPERIMENTAL_DIRECT_ACCESS === '1' || directAccess) { + Parse.CoreManager.setRESTController(ParseServerRESTController(appId, appRouter)); } return api; } @@ -267,9 +246,7 @@ class ParseServer { if (options.mountGraphQL === true || options.mountPlayground === true) { let graphQLCustomTypeDefs = undefined; if (typeof options.graphQLSchema === 'string') { - graphQLCustomTypeDefs = parse( - fs.readFileSync(options.graphQLSchema, 'utf8') - ); + graphQLCustomTypeDefs = parse(fs.readFileSync(options.graphQLSchema, 'utf8')); } else if ( typeof options.graphQLSchema === 'object' || typeof options.graphQLSchema === 'function' @@ -350,11 +327,7 @@ class ParseServer { .catch(response => response) .then(response => { const json = response.data || null; - if ( - response.status !== 200 || - !json || - (json && json.status !== 'ok') - ) { + if (response.status !== 200 || !json || (json && json.status !== 'ok')) { /* eslint-disable no-console */ console.warn( `\nWARNING, Unable to connect to '${Parse.serverURL}'.` + @@ -411,10 +384,7 @@ function injectDefaults(options: ParseServerOptions) { /* eslint-enable no-console */ const userSensitiveFields = Array.from( - new Set([ - ...(defaults.userSensitiveFields || []), - ...(options.userSensitiveFields || []), - ]) + new Set([...(defaults.userSensitiveFields || []), ...(options.userSensitiveFields || [])]) ); // If the options.protectedFields is unset, @@ -422,17 +392,11 @@ function injectDefaults(options: ParseServerOptions) { // Here, protect against the case where protectedFields // is set, but doesn't have _User. if (!('_User' in options.protectedFields)) { - options.protectedFields = Object.assign( - { _User: [] }, - options.protectedFields - ); + options.protectedFields = Object.assign({ _User: [] }, options.protectedFields); } options.protectedFields['_User']['*'] = Array.from( - new Set([ - ...(options.protectedFields['_User']['*'] || []), - ...userSensitiveFields, - ]) + new Set([...(options.protectedFields['_User']['*'] || []), ...userSensitiveFields]) ); } @@ -453,9 +417,7 @@ function injectDefaults(options: ParseServerOptions) { }); options.masterKeyIps = Array.from( - new Set( - options.masterKeyIps.concat(defaults.masterKeyIps, options.masterKeyIps) - ) + new Set(options.masterKeyIps.concat(defaults.masterKeyIps, options.masterKeyIps)) ); } diff --git a/src/ParseServerRESTController.js b/src/ParseServerRESTController.js index 76370b70..c678f99e 100644 --- a/src/ParseServerRESTController.js +++ b/src/ParseServerRESTController.js @@ -14,9 +14,7 @@ function getSessionToken(options) { function getAuth(options = {}, config) { const installationId = options.installationId || 'cloud'; if (options.useMasterKey) { - return Promise.resolve( - new Auth.Auth({ config, isMaster: true, installationId }) - ); + return Promise.resolve(new Auth.Auth({ config, isMaster: true, installationId })); } return getSessionToken(options).then(sessionToken => { if (sessionToken) { @@ -56,13 +54,7 @@ function ParseServerRESTController(applicationId, router) { } return initialPromise.then(() => { const promises = data.requests.map(request => { - return handleRequest( - request.method, - request.path, - request.body, - options, - config - ).then( + return handleRequest(request.method, request.path, request.body, options, config).then( response => { if (options.returnStatus) { const status = response._status; @@ -80,9 +72,7 @@ function ParseServerRESTController(applicationId, router) { }); return Promise.all(promises).then(result => { if (data.transaction === true) { - if ( - result.find(resultItem => typeof resultItem.error === 'object') - ) { + if (result.find(resultItem => typeof resultItem.error === 'object')) { return config.database.abortTransactionalSession().then(() => { return Promise.reject(result); }); diff --git a/src/PromiseRouter.js b/src/PromiseRouter.js index d67bf30d..e1ec4eff 100644 --- a/src/PromiseRouter.js +++ b/src/PromiseRouter.js @@ -66,7 +66,7 @@ export default class PromiseRouter { let handler = handlers[0]; if (handlers.length > 1) { - handler = function(req) { + handler = function (req) { return handlers.reduce((promise, handler) => { return promise.then(() => { return handler(req); @@ -121,10 +121,7 @@ export default class PromiseRouter { tryRouteRequest(method, path, request) { var match = this.match(method, path); if (!match) { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'cannot route ' + method + ' ' + path - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'cannot route ' + method + ' ' + path); } request.params = match.params; return new Promise((resolve, reject) => { @@ -138,7 +135,7 @@ export default class PromiseRouter { // Express handlers should never throw; if a promise handler throws we // just treat it like it resolved to an error. function makeExpressHandler(appId, promiseHandler) { - return function(req, res, next) { + return function (req, res, next) { try { const url = maskSensitiveUrl(req); const body = Object.assign({}, req.body); @@ -155,9 +152,7 @@ function makeExpressHandler(appId, promiseHandler) { result => { clearSchemaCache(req); if (!result.response && !result.location && !result.text) { - log.error( - 'the handler did not include a "response" or a "location" field' - ); + log.error('the handler did not include a "response" or a "location" field'); throw 'control should not get here'; } diff --git a/src/Push/PushQueue.js b/src/Push/PushQueue.js index f67f7c9e..3e70e999 100644 --- a/src/Push/PushQueue.js +++ b/src/Push/PushQueue.js @@ -57,10 +57,7 @@ export class PushQueue { pushStatus: { objectId: pushStatus.objectId }, applicationId: config.applicationId, }; - this.parsePublisher.publish( - this.channel, - JSON.stringify(pushWorkItem) - ); + this.parsePublisher.publish(this.channel, JSON.stringify(pushWorkItem)); skip += limit; } }); diff --git a/src/Push/PushWorker.js b/src/Push/PushWorker.js index d16542ae..2b3c4a2f 100644 --- a/src/Push/PushWorker.js +++ b/src/Push/PushWorker.js @@ -48,14 +48,12 @@ export class PushWorker { const where = utils.applyDeviceTokenExists(query.where); delete query.where; pushStatus = pushStatusHandler(config, pushStatus.objectId); - return rest - .find(config, auth, '_Installation', where, query) - .then(({ results }) => { - if (results.length == 0) { - return; - } - return this.sendToAdapter(body, results, pushStatus, config, UTCOffset); - }); + return rest.find(config, auth, '_Installation', where, query).then(({ results }) => { + if (results.length == 0) { + return; + } + return this.sendToAdapter(body, results, pushStatus, config, UTCOffset); + }); } sendToAdapter( @@ -72,31 +70,20 @@ export class PushWorker { const bodiesPerLocales = utils.bodiesPerLocales(body, locales); // Group installations on the specified locales (en, fr, default etc...) - const grouppedInstallations = utils.groupByLocaleIdentifier( - installations, - locales - ); + const grouppedInstallations = utils.groupByLocaleIdentifier(installations, locales); const promises = Object.keys(grouppedInstallations).map(locale => { const installations = grouppedInstallations[locale]; const body = bodiesPerLocales[locale]; - return this.sendToAdapter( - body, - installations, - pushStatus, - config, - UTCOffset - ); + return this.sendToAdapter(body, installations, pushStatus, config, UTCOffset); }); return Promise.all(promises); } if (!utils.isPushIncrementing(body)) { logger.verbose(`Sending push to ${installations.length}`); - return this.adapter - .send(body, installations, pushStatus.objectId) - .then(results => { - return pushStatus.trackSent(results, UTCOffset).then(() => results); - }); + return this.adapter.send(body, installations, pushStatus.objectId).then(results => { + return pushStatus.trackSent(results, UTCOffset).then(() => results); + }); } // Collect the badges to reduce the # of calls @@ -107,13 +94,7 @@ export class PushWorker { const payload = deepcopy(body); payload.data.badge = parseInt(badge); const installations = badgeInstallationsMap[badge]; - return this.sendToAdapter( - payload, - installations, - pushStatus, - config, - UTCOffset - ); + return this.sendToAdapter(payload, installations, pushStatus, config, UTCOffset); }); return Promise.all(promises); } diff --git a/src/Push/utils.js b/src/Push/utils.js index ce702391..5be13c27 100644 --- a/src/Push/utils.js +++ b/src/Push/utils.js @@ -88,10 +88,7 @@ export function groupByLocaleIdentifier(installations, locales = []) { if (added) { return; } - if ( - installation.localeIdentifier && - installation.localeIdentifier.indexOf(locale) === 0 - ) { + if (installation.localeIdentifier && installation.localeIdentifier.indexOf(locale) === 0) { added = true; map[locale] = map[locale] || []; map[locale].push(installation); diff --git a/src/RestQuery.js b/src/RestQuery.js index 1f6f4b52..ec43992a 100644 --- a/src/RestQuery.js +++ b/src/RestQuery.js @@ -40,10 +40,7 @@ function RestQuery( if (!this.auth.isMaster) { if (this.className == '_Session') { if (!this.auth.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'); } this.restWhere = { $and: [ @@ -175,10 +172,7 @@ function RestQuery( case 'subqueryReadPreference': break; default: - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'bad option: ' + option - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad option: ' + option); } } } @@ -228,14 +222,7 @@ RestQuery.prototype.each = function (callback) { return !finished; }, async () => { - const query = new RestQuery( - config, - auth, - className, - restWhere, - restOptions, - clientSDK - ); + const query = new RestQuery(config, auth, className, restWhere, restOptions, clientSDK); const { results } = await query.execute(); results.forEach(callback); finished = results.length < restOptions.limit; @@ -286,9 +273,7 @@ RestQuery.prototype.getUserAndRoleACL = function () { if (this.auth.user) { return this.auth.getUserRoles().then(roles => { - this.findOptions.acl = this.findOptions.acl.concat(roles, [ - this.auth.user.id, - ]); + this.findOptions.acl = this.findOptions.acl.concat(roles, [this.auth.user.id]); return; }); } else { @@ -326,9 +311,7 @@ RestQuery.prototype.validateClientClassCreation = function () { if (hasClass !== true) { throw new Parse.Error( Parse.Error.OPERATION_FORBIDDEN, - 'This user is not allowed to access ' + - 'non-existent class: ' + - this.className + 'This user is not allowed to access ' + 'non-existent class: ' + this.className ); } }); @@ -367,10 +350,7 @@ RestQuery.prototype.replaceInQuery = function () { // The inQuery value must have precisely two keys - where and className var inQueryValue = inQueryObject['$inQuery']; if (!inQueryValue.where || !inQueryValue.className) { - throw new Parse.Error( - Parse.Error.INVALID_QUERY, - 'improper usage of $inQuery' - ); + throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $inQuery'); } const additionalOptions = { @@ -428,10 +408,7 @@ RestQuery.prototype.replaceNotInQuery = function () { // The notInQuery value must have precisely two keys - where and className var notInQueryValue = notInQueryObject['$notInQuery']; if (!notInQueryValue.where || !notInQueryValue.className) { - throw new Parse.Error( - Parse.Error.INVALID_QUERY, - 'improper usage of $notInQuery' - ); + throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $notInQuery'); } const additionalOptions = { @@ -501,10 +478,7 @@ RestQuery.prototype.replaceSelect = function () { !selectValue.query.className || Object.keys(selectValue).length !== 2 ) { - throw new Parse.Error( - Parse.Error.INVALID_QUERY, - 'improper usage of $select' - ); + throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $select'); } const additionalOptions = { @@ -565,10 +539,7 @@ RestQuery.prototype.replaceDontSelect = function () { !dontSelectValue.query.className || Object.keys(dontSelectValue).length !== 2 ) { - throw new Parse.Error( - Parse.Error.INVALID_QUERY, - 'improper usage of $dontSelect' - ); + throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $dontSelect'); } const additionalOptions = { redirectClassNameForKey: dontSelectValue.query.redirectClassNameForKey, @@ -589,11 +560,7 @@ RestQuery.prototype.replaceDontSelect = function () { additionalOptions ); return subquery.execute().then(response => { - transformDontSelect( - dontSelectObject, - dontSelectValue.key, - response.results - ); + transformDontSelect(dontSelectObject, dontSelectValue.key, response.results); // Keep replacing $dontSelect clauses return this.replaceDontSelect(); }); @@ -692,11 +659,9 @@ RestQuery.prototype.runCount = function () { this.findOptions.count = true; delete this.findOptions.skip; delete this.findOptions.limit; - return this.config.database - .find(this.className, this.restWhere, this.findOptions) - .then(c => { - this.response.count = c; - }); + return this.config.database.find(this.className, this.restWhere, this.findOptions).then(c => { + this.response.count = c; + }); }; // Augments this.response with all pointers on an object @@ -711,10 +676,7 @@ RestQuery.prototype.handleIncludeAll = function () { const includeFields = []; const keyFields = []; for (const field in schema.fields) { - if ( - schema.fields[field].type && - schema.fields[field].type === 'Pointer' - ) { + if (schema.fields[field].type && schema.fields[field].type === 'Pointer') { includeFields.push([field]); keyFields.push(field); } @@ -868,8 +830,7 @@ function includePath(config, auth, response, path, restOptions = {}) { if (restOptions.includeReadPreference) { includeRestOptions.readPreference = restOptions.includeReadPreference; - includeRestOptions.includeReadPreference = - restOptions.includeReadPreference; + includeRestOptions.includeReadPreference = restOptions.includeReadPreference; } else if (restOptions.readPreference) { includeRestOptions.readPreference = restOptions.readPreference; } @@ -882,13 +843,7 @@ function includePath(config, auth, response, path, restOptions = {}) { } else { where = { objectId: { $in: objectIds } }; } - 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 => { results.className = className; return Promise.resolve(results); diff --git a/src/RestWrite.js b/src/RestWrite.js index cc01dca3..0825267e 100644 --- a/src/RestWrite.js +++ b/src/RestWrite.js @@ -24,17 +24,7 @@ import logger from './logger'; // RestWrite will handle objectId, createdAt, and updatedAt for // everything. It also knows to use triggers and special modifications // for the _User class. -function RestWrite( - config, - auth, - className, - query, - data, - originalData, - clientSDK, - context, - action -) { +function RestWrite(config, auth, className, query, data, originalData, clientSDK, context, action) { if (auth.isReadOnly) { throw new Parse.Error( Parse.Error.OPERATION_FORBIDDEN, @@ -55,10 +45,7 @@ function RestWrite( if (!query) { if (this.config.allowCustomObjectId) { - if ( - Object.prototype.hasOwnProperty.call(data, 'objectId') && - !data.objectId - ) { + if (Object.prototype.hasOwnProperty.call(data, 'objectId') && !data.objectId) { throw new Parse.Error( Parse.Error.MISSING_OBJECT_ID, 'objectId must not be empty, null or undefined' @@ -66,16 +53,10 @@ function RestWrite( } } else { if (data.objectId) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - 'objectId is an invalid field name.' - ); + throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'objectId is an invalid field name.'); } if (data.id) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - 'id is an invalid field name.' - ); + throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'id is an invalid field name.'); } } } @@ -175,9 +156,7 @@ RestWrite.prototype.getUserAndRoleACL = function () { if (this.auth.user) { return this.auth.getUserRoles().then(roles => { - this.runOptions.acl = this.runOptions.acl.concat(roles, [ - this.auth.user.id, - ]); + this.runOptions.acl = this.runOptions.acl.concat(roles, [this.auth.user.id]); return; }); } else { @@ -199,9 +178,7 @@ RestWrite.prototype.validateClientClassCreation = function () { if (hasClass !== true) { throw new Parse.Error( Parse.Error.OPERATION_FORBIDDEN, - 'This user is not allowed to access ' + - 'non-existent class: ' + - this.className + 'This user is not allowed to access ' + 'non-existent class: ' + this.className ); } }); @@ -229,11 +206,7 @@ RestWrite.prototype.runBeforeSaveTrigger = function () { // Avoid doing any setup for triggers if there is no 'beforeSave' trigger for this class. if ( - !triggers.triggerExists( - this.className, - triggers.Types.beforeSave, - this.config.applicationId - ) + !triggers.triggerExists(this.className, triggers.Types.beforeSave, this.config.applicationId) ) { return Promise.resolve(); } @@ -277,10 +250,7 @@ RestWrite.prototype.runBeforeSaveTrigger = function () { // In the case that there is no permission for the operation, it throws an error return databasePromise.then(result => { if (!result || result.length <= 0) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); } }); }) @@ -318,11 +288,7 @@ RestWrite.prototype.runBeforeSaveTrigger = function () { RestWrite.prototype.runBeforeLoginTrigger = async function (userData) { // Avoid doing any setup for triggers if there is no 'beforeLogin' trigger if ( - !triggers.triggerExists( - this.className, - triggers.Types.beforeLogin, - this.config.applicationId - ) + !triggers.triggerExists(this.className, triggers.Types.beforeLogin, this.config.applicationId) ) { return; } @@ -349,16 +315,13 @@ RestWrite.prototype.runBeforeLoginTrigger = async function (userData) { RestWrite.prototype.setRequiredFieldsIfNeeded = function () { if (this.data) { return this.validSchemaController.getAllClasses().then(allClasses => { - const schema = allClasses.find( - oneClass => oneClass.className === this.className - ); + const schema = allClasses.find(oneClass => oneClass.className === this.className); const setRequiredFieldIfNeeded = (fieldName, setDefault) => { if ( this.data[fieldName] === undefined || this.data[fieldName] === null || this.data[fieldName] === '' || - (typeof this.data[fieldName] === 'object' && - this.data[fieldName].__op === 'Delete') + (typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete') ) { if ( setDefault && @@ -366,23 +329,15 @@ RestWrite.prototype.setRequiredFieldsIfNeeded = function () { schema.fields[fieldName].defaultValue !== null && schema.fields[fieldName].defaultValue !== undefined && (this.data[fieldName] === undefined || - (typeof this.data[fieldName] === 'object' && - this.data[fieldName].__op === 'Delete')) + (typeof this.data[fieldName] === 'object' && this.data[fieldName].__op === 'Delete')) ) { this.data[fieldName] = schema.fields[fieldName].defaultValue; - this.storage.fieldsChangedByTrigger = - this.storage.fieldsChangedByTrigger || []; + this.storage.fieldsChangedByTrigger = this.storage.fieldsChangedByTrigger || []; if (this.storage.fieldsChangedByTrigger.indexOf(fieldName) < 0) { this.storage.fieldsChangedByTrigger.push(fieldName); } - } else if ( - schema.fields[fieldName] && - schema.fields[fieldName].required === true - ) { - throw new Parse.Error( - Parse.Error.VALIDATION_ERROR, - `${fieldName} is required` - ); + } else if (schema.fields[fieldName] && schema.fields[fieldName].required === true) { + throw new Parse.Error(Parse.Error.VALIDATION_ERROR, `${fieldName} is required`); } } }; @@ -394,9 +349,7 @@ RestWrite.prototype.setRequiredFieldsIfNeeded = function () { // Only assign new objectId if we are creating new object if (!this.data.objectId) { - this.data.objectId = cryptoUtils.newObjectId( - this.config.objectIdSize - ); + this.data.objectId = cryptoUtils.newObjectId(this.config.objectIdSize); } if (schema) { Object.keys(schema.fields).forEach(fieldName => { @@ -422,23 +375,11 @@ RestWrite.prototype.validateAuthData = function () { } if (!this.query && !this.data.authData) { - if ( - typeof this.data.username !== 'string' || - _.isEmpty(this.data.username) - ) { - throw new Parse.Error( - Parse.Error.USERNAME_MISSING, - 'bad or missing username' - ); + if (typeof this.data.username !== 'string' || _.isEmpty(this.data.username)) { + throw new Parse.Error(Parse.Error.USERNAME_MISSING, 'bad or missing username'); } - if ( - typeof this.data.password !== 'string' || - _.isEmpty(this.data.password) - ) { - throw new Parse.Error( - Parse.Error.PASSWORD_MISSING, - 'password is required' - ); + if (typeof this.data.password !== 'string' || _.isEmpty(this.data.password)) { + throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'password is required'); } } @@ -448,10 +389,7 @@ RestWrite.prototype.validateAuthData = function () { ) { // Handle saving authData to {} or if authData doesn't exist return; - } else if ( - Object.prototype.hasOwnProperty.call(this.data, 'authData') && - !this.data.authData - ) { + } else if (Object.prototype.hasOwnProperty.call(this.data, 'authData') && !this.data.authData) { // Handle saving authData to null throw new Parse.Error( Parse.Error.UNSUPPORTED_SERVICE, @@ -482,9 +420,7 @@ RestWrite.prototype.handleAuthDataValidation = function (authData) { if (authData[provider] === null) { return Promise.resolve(); } - const validateAuthData = this.config.authDataManager.getValidatorForProvider( - provider - ); + const validateAuthData = this.config.authDataManager.getValidatorForProvider(provider); if (!validateAuthData) { throw new Parse.Error( Parse.Error.UNSUPPORTED_SERVICE, @@ -595,8 +531,7 @@ RestWrite.prototype.handleAuthData = function (authData) { if (this.response) { // Assign the new authData in the response Object.keys(mutatedAuthData).forEach(provider => { - this.response.response.authData[provider] = - mutatedAuthData[provider]; + this.response.response.authData[provider] = mutatedAuthData[provider]; }); // Run the DB update directly, as 'master' @@ -614,10 +549,7 @@ RestWrite.prototype.handleAuthData = function (authData) { // Trying to update auth data but users // are different if (userResult.objectId !== userId) { - throw new Parse.Error( - Parse.Error.ACCOUNT_ALREADY_LINKED, - 'this auth is already used' - ); + throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used'); } // No auth data was mutated, just keep going if (!hasMutatedAuthData) { @@ -628,10 +560,7 @@ RestWrite.prototype.handleAuthData = function (authData) { return this.handleAuthDataValidation(authData).then(() => { if (results.length > 1) { // More than 1 user with the passed id's - throw new Parse.Error( - Parse.Error.ACCOUNT_ALREADY_LINKED, - 'this auth is already used' - ); + throw new Parse.Error(Parse.Error.ACCOUNT_ALREADY_LINKED, 'this auth is already used'); } }); }); @@ -757,10 +686,7 @@ RestWrite.prototype._validateEmail = function () { // Validate basic email address format if (!this.data.email.match(/^.+@.+$/)) { return Promise.reject( - new Parse.Error( - Parse.Error.INVALID_EMAIL_ADDRESS, - 'Email address format is invalid.' - ) + new Parse.Error(Parse.Error.INVALID_EMAIL_ADDRESS, 'Email address format is invalid.') ); } // Case insensitive match, see note above function. @@ -823,9 +749,7 @@ RestWrite.prototype._validatePasswordRequirements = function () { (this.config.passwordPolicy.validatorCallback && !this.config.passwordPolicy.validatorCallback(this.data.password)) ) { - return Promise.reject( - new Parse.Error(Parse.Error.VALIDATION_ERROR, policyError) - ); + return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, policyError)); } // check whether password contain username @@ -833,26 +757,19 @@ RestWrite.prototype._validatePasswordRequirements = function () { if (this.data.username) { // username is not passed during password reset if (this.data.password.indexOf(this.data.username) >= 0) - return Promise.reject( - new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError) - ); + return Promise.reject(new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError)); } else { // retrieve the User object using objectId during password reset - return this.config.database - .find('_User', { objectId: this.objectId() }) - .then(results => { - if (results.length != 1) { - throw undefined; - } - if (this.data.password.indexOf(results[0].username) >= 0) - return Promise.reject( - new Parse.Error( - Parse.Error.VALIDATION_ERROR, - containsUsernameError - ) - ); - return Promise.resolve(); - }); + return this.config.database.find('_User', { objectId: this.objectId() }).then(results => { + if (results.length != 1) { + throw undefined; + } + if (this.data.password.indexOf(results[0].username) >= 0) + return Promise.reject( + new Parse.Error(Parse.Error.VALIDATION_ERROR, containsUsernameError) + ); + return Promise.resolve(); + }); } } return Promise.resolve(); @@ -999,11 +916,7 @@ RestWrite.prototype.destroyDuplicatedSessions = function () { // Handles any followup logic RestWrite.prototype.handleFollowup = function () { - if ( - this.storage && - this.storage['clearSessions'] && - this.config.revokeSessionOnPasswordReset - ) { + if (this.storage && this.storage['clearSessions'] && this.config.revokeSessionOnPasswordReset) { var sessionQuery = { user: { __type: 'Pointer', @@ -1038,26 +951,16 @@ RestWrite.prototype.handleSession = function () { } if (!this.auth.user && !this.auth.isMaster) { - throw new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'Session token required.' - ); + throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token required.'); } // TODO: Verify proper error to throw if (this.data.ACL) { - throw new Parse.Error( - Parse.Error.INVALID_KEY_NAME, - 'Cannot set ' + 'ACL on a Session.' - ); + throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, 'Cannot set ' + 'ACL on a Session.'); } if (this.query) { - if ( - this.data.user && - !this.auth.isMaster && - this.data.user.objectId != this.auth.user.id - ) { + if (this.data.user && !this.auth.isMaster && this.data.user.objectId != this.auth.user.id) { throw new Parse.Error(Parse.Error.INVALID_KEY_NAME); } else if (this.data.installationId) { throw new Parse.Error(Parse.Error.INVALID_KEY_NAME); @@ -1085,10 +988,7 @@ RestWrite.prototype.handleSession = function () { return createSession().then(results => { if (!results.response) { - throw new Parse.Error( - Parse.Error.INTERNAL_SERVER_ERROR, - 'Error creating session.' - ); + throw new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'Error creating session.'); } sessionData['objectId'] = results.response['objectId']; this.response = { @@ -1118,8 +1018,7 @@ RestWrite.prototype.handleInstallation = function () { ) { throw new Parse.Error( 135, - 'at least one ID field (deviceToken, installationId) ' + - 'must be specified in this operation' + 'at least one ID field (deviceToken, installationId) ' + 'must be specified in this operation' ); } @@ -1146,12 +1045,7 @@ RestWrite.prototype.handleInstallation = function () { } // Updating _Installation but not updating anything critical - if ( - this.query && - !this.data.deviceToken && - !installationId && - !this.data.deviceType - ) { + if (this.query && !this.data.deviceToken && !installationId && !this.data.deviceType) { return; } @@ -1194,11 +1088,7 @@ RestWrite.prototype.handleInstallation = function () { }) .then(results => { results.forEach(result => { - if ( - this.query && - this.query.objectId && - result.objectId == this.query.objectId - ) { + if (this.query && this.query.objectId && result.objectId == this.query.objectId) { objectIdMatch = result; } if (result.installationId == installationId) { @@ -1212,20 +1102,14 @@ RestWrite.prototype.handleInstallation = function () { // Sanity checks when running a query if (this.query && this.query.objectId) { if (!objectIdMatch) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found for update.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found for update.'); } if ( this.data.installationId && objectIdMatch.installationId && this.data.installationId !== objectIdMatch.installationId ) { - throw new Parse.Error( - 136, - 'installationId may not be changed in this ' + 'operation' - ); + throw new Parse.Error(136, 'installationId may not be changed in this ' + 'operation'); } if ( this.data.deviceToken && @@ -1234,20 +1118,14 @@ RestWrite.prototype.handleInstallation = function () { !this.data.installationId && !objectIdMatch.installationId ) { - throw new Parse.Error( - 136, - 'deviceToken may not be changed in this ' + 'operation' - ); + throw new Parse.Error(136, 'deviceToken may not be changed in this ' + 'operation'); } if ( this.data.deviceType && this.data.deviceType && this.data.deviceType !== objectIdMatch.deviceType ) { - throw new Parse.Error( - 136, - 'deviceType may not be changed in this ' + 'operation' - ); + throw new Parse.Error(136, 'deviceType may not be changed in this ' + 'operation'); } } @@ -1260,10 +1138,7 @@ RestWrite.prototype.handleInstallation = function () { } // need to specify deviceType only if it's new if (!this.query && !this.data.deviceType && !idMatch) { - throw new Parse.Error( - 135, - 'deviceType must be specified in this operation' - ); + throw new Parse.Error(135, 'deviceType must be specified in this operation'); } }) .then(() => { @@ -1310,10 +1185,7 @@ RestWrite.prototype.handleInstallation = function () { return; } } else { - if ( - deviceTokenMatches.length == 1 && - !deviceTokenMatches[0]['installationId'] - ) { + if (deviceTokenMatches.length == 1 && !deviceTokenMatches[0]['installationId']) { // 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 // object. @@ -1332,10 +1204,7 @@ RestWrite.prototype.handleInstallation = function () { throw err; }); } else { - if ( - this.data.deviceToken && - idMatch.deviceToken != this.data.deviceToken - ) { + if (this.data.deviceToken && idMatch.deviceToken != this.data.deviceToken) { // We're setting the device token on an existing installation, so // we should try cleaning out old installations that match this // device token. @@ -1364,16 +1233,14 @@ RestWrite.prototype.handleInstallation = function () { if (this.data.appIdentifier) { delQuery['appIdentifier'] = this.data.appIdentifier; } - this.config.database - .destroy('_Installation', delQuery) - .catch(err => { - if (err.code == Parse.Error.OBJECT_NOT_FOUND) { - // no deletions were made. Can be ignored. - return; - } - // rethrow the error - throw err; - }); + this.config.database.destroy('_Installation', delQuery).catch(err => { + if (err.code == Parse.Error.OBJECT_NOT_FOUND) { + // no deletions were made. Can be ignored. + return; + } + // rethrow the error + throw err; + }); } // In non-merge scenarios, just return the installation match id return idMatch.objectId; @@ -1397,10 +1264,7 @@ RestWrite.prototype.handleInstallation = function () { RestWrite.prototype.expandFilesForExistingObjects = function () { // Check whether we have a short-circuited response - only then run expansion. if (this.response && this.response.response) { - this.config.filesController.expandFilesInObject( - this.config, - this.response.response - ); + this.config.filesController.expandFilesInObject(this.config, this.response.response); } }; @@ -1413,11 +1277,7 @@ RestWrite.prototype.runDatabaseOperation = function () { this.config.cacheController.role.clear(); } - if ( - this.className === '_User' && - this.query && - this.auth.isUnauthenticated() - ) { + if (this.className === '_User' && this.query && this.auth.isUnauthenticated()) { throw new Parse.Error( Parse.Error.SESSION_MISSING, `Cannot modify user ${this.query.objectId}.` @@ -1437,11 +1297,7 @@ RestWrite.prototype.runDatabaseOperation = function () { if (this.query) { // Force the user to not lockout // Matched with parse.com - if ( - this.className === '_User' && - this.data.ACL && - this.auth.isMaster !== true - ) { + if (this.className === '_User' && this.data.ACL && this.auth.isMaster !== true) { this.data.ACL[this.query.objectId] = { read: true, write: true }; } // update password timestamp if user password is being changed @@ -1484,8 +1340,7 @@ RestWrite.prototype.runDatabaseOperation = function () { } //n-1 passwords go into history including last password while ( - oldPasswords.length > - Math.max(0, this.config.passwordPolicy.maxPasswordHistory - 2) + oldPasswords.length > Math.max(0, this.config.passwordPolicy.maxPasswordHistory - 2) ) { oldPasswords.shift(); } @@ -1525,48 +1380,28 @@ RestWrite.prototype.runDatabaseOperation = function () { ACL[this.data.objectId] = { read: true, write: true }; this.data.ACL = ACL; // password timestamp to be used when password expiry policy is enforced - if ( - this.config.passwordPolicy && - this.config.passwordPolicy.maxPasswordAge - ) { + if (this.config.passwordPolicy && this.config.passwordPolicy.maxPasswordAge) { this.data._password_changed_at = Parse._encode(new Date()); } } // Run a create return this.config.database - .create( - this.className, - this.data, - this.runOptions, - false, - this.validSchemaController - ) + .create(this.className, this.data, this.runOptions, false, this.validSchemaController) .catch(error => { - if ( - this.className !== '_User' || - error.code !== Parse.Error.DUPLICATE_VALUE - ) { + if (this.className !== '_User' || error.code !== Parse.Error.DUPLICATE_VALUE) { throw error; } // Quick check, if we were able to infer the duplicated field name - if ( - error && - error.userInfo && - error.userInfo.duplicated_field === 'username' - ) { + if (error && error.userInfo && error.userInfo.duplicated_field === 'username') { throw new Parse.Error( Parse.Error.USERNAME_TAKEN, 'Account already exists for this username.' ); } - if ( - error && - error.userInfo && - error.userInfo.duplicated_field === 'email' - ) { + if (error && error.userInfo && error.userInfo.duplicated_field === 'email') { throw new Parse.Error( Parse.Error.EMAIL_TAKEN, 'Account already exists for this email address.' @@ -1641,9 +1476,7 @@ RestWrite.prototype.runAfterSaveTrigger = function () { triggers.Types.afterSave, this.config.applicationId ); - const hasLiveQuery = this.config.liveQueryController.hasLiveQuery( - this.className - ); + const hasLiveQuery = this.config.liveQueryController.hasLiveQuery(this.className); if (!hasAfterSaveHook && !hasLiveQuery) { return Promise.resolve(); } @@ -1662,16 +1495,11 @@ RestWrite.prototype.runAfterSaveTrigger = function () { // Build the inflated object, different from beforeSave, originalData is not empty // since developers can change data in the beforeSave. const updatedObject = this.buildUpdatedObject(extraData); - updatedObject._handleSaveResponse( - this.response.response, - this.response.status || 200 - ); + updatedObject._handleSaveResponse(this.response.response, this.response.status || 200); this.config.database.loadSchema().then(schemaController => { // Notifiy LiveQueryServer if possible - const perms = schemaController.getClassLevelPermissions( - updatedObject.className - ); + const perms = schemaController.getClassLevelPermissions(updatedObject.className); this.config.liveQueryController.onAfterSave( updatedObject.className, updatedObject, @@ -1702,8 +1530,7 @@ RestWrite.prototype.runAfterSaveTrigger = function () { // A helper to figure out what location this operation happens at. RestWrite.prototype.location = function () { - var middle = - this.className === '_User' ? '/users/' : '/classes/' + this.className + '/'; + var middle = this.className === '_User' ? '/users/' : '/classes/' + this.className + '/'; const mount = this.config.mount || this.config.serverURL; return mount + middle + this.data.objectId; }; diff --git a/src/Routers/AggregateRouter.js b/src/Routers/AggregateRouter.js index cd849b56..b994f5a6 100644 --- a/src/Routers/AggregateRouter.js +++ b/src/Routers/AggregateRouter.js @@ -38,10 +38,7 @@ const ALLOWED_KEYS = [...BASE_KEYS, ...PIPELINE_KEYS]; export class AggregateRouter extends ClassesRouter { handleFind(req) { - const body = Object.assign( - req.body, - ClassesRouter.JSONFromQuery(req.query) - ); + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); const options = {}; if (body.distinct) { options.distinct = String(body.distinct); @@ -118,9 +115,7 @@ export class AggregateRouter extends ClassesRouter { return pipeline.map(stage => { const keys = Object.keys(stage); if (keys.length != 1) { - throw new Error( - `Pipeline stages should only have one key found ${keys.join(', ')}` - ); + throw new Error(`Pipeline stages should only have one key found ${keys.join(', ')}`); } return AggregateRouter.transformStage(keys[0], stage); }); @@ -128,10 +123,7 @@ export class AggregateRouter extends ClassesRouter { static transformStage(stageName, stage) { if (ALLOWED_KEYS.indexOf(stageName) === -1) { - throw new Parse.Error( - Parse.Error.INVALID_QUERY, - `Invalid parameter for query: ${stageName}` - ); + throw new Parse.Error(Parse.Error.INVALID_QUERY, `Invalid parameter for query: ${stageName}`); } if (stageName === 'group') { if (Object.prototype.hasOwnProperty.call(stage[stageName], '_id')) { @@ -153,14 +145,9 @@ export class AggregateRouter extends ClassesRouter { } mountRoutes() { - this.route( - 'GET', - '/aggregate/:className', - middleware.promiseEnforceMasterKeyAccess, - req => { - return this.handleFind(req); - } - ); + this.route('GET', '/aggregate/:className', middleware.promiseEnforceMasterKeyAccess, req => { + return this.handleFind(req); + }); } } diff --git a/src/Routers/AudiencesRouter.js b/src/Routers/AudiencesRouter.js index e9ece1d4..43fcfd71 100644 --- a/src/Routers/AudiencesRouter.js +++ b/src/Routers/AudiencesRouter.js @@ -8,10 +8,7 @@ export class AudiencesRouter extends ClassesRouter { } handleFind(req) { - const body = Object.assign( - req.body, - ClassesRouter.JSONFromQuery(req.query) - ); + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); const options = ClassesRouter.optionsFromBody(body); return rest @@ -42,14 +39,9 @@ export class AudiencesRouter extends ClassesRouter { } mountRoutes() { - this.route( - 'GET', - '/push_audiences', - middleware.promiseEnforceMasterKeyAccess, - req => { - return this.handleFind(req); - } - ); + this.route('GET', '/push_audiences', middleware.promiseEnforceMasterKeyAccess, req => { + return this.handleFind(req); + }); this.route( 'GET', '/push_audiences/:objectId', @@ -58,14 +50,9 @@ export class AudiencesRouter extends ClassesRouter { return this.handleGet(req); } ); - this.route( - 'POST', - '/push_audiences', - middleware.promiseEnforceMasterKeyAccess, - req => { - return this.handleCreate(req); - } - ); + this.route('POST', '/push_audiences', middleware.promiseEnforceMasterKeyAccess, req => { + return this.handleCreate(req); + }); this.route( 'PUT', '/push_audiences/:objectId', diff --git a/src/Routers/ClassesRouter.js b/src/Routers/ClassesRouter.js index a335f00d..d1fc13bc 100644 --- a/src/Routers/ClassesRouter.js +++ b/src/Routers/ClassesRouter.js @@ -19,10 +19,7 @@ export class ClassesRouter extends PromiseRouter { } handleFind(req) { - const body = Object.assign( - req.body, - ClassesRouter.JSONFromQuery(req.query) - ); + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); const options = ClassesRouter.optionsFromBody(body); if (req.config.maxLimit && body.limit > req.config.maxLimit) { // Silently replace the limit on the query with the max configured @@ -51,18 +48,12 @@ export class ClassesRouter extends PromiseRouter { // Returns a promise for a {response} object. handleGet(req) { - const body = Object.assign( - req.body, - ClassesRouter.JSONFromQuery(req.query) - ); + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); const options = {}; for (const key of Object.keys(body)) { 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'); } } @@ -96,10 +87,7 @@ export class ClassesRouter extends PromiseRouter { ) .then(response => { if (!response.results || response.results.length == 0) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); } if (this.className(req) === '_User') { @@ -142,13 +130,7 @@ export class ClassesRouter extends PromiseRouter { handleDelete(req) { return rest - .del( - req.config, - req.auth, - this.className(req), - req.params.objectId, - req.info.context - ) + .del(req.config, req.auth, this.className(req), req.params.objectId, req.info.context) .then(() => { return { response: {} }; }); @@ -187,10 +169,7 @@ export class ClassesRouter extends PromiseRouter { for (const key of Object.keys(body)) { 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}`); } } const options = {}; @@ -229,10 +208,7 @@ export class ClassesRouter extends PromiseRouter { if (typeof body.subqueryReadPreference === 'string') { options.subqueryReadPreference = body.subqueryReadPreference; } - if ( - body.hint && - (typeof body.hint === 'string' || typeof body.hint === 'object') - ) { + if (body.hint && (typeof body.hint === 'string' || typeof body.hint === 'object')) { options.hint = body.hint; } if (body.explain) { @@ -251,14 +227,9 @@ export class ClassesRouter extends PromiseRouter { this.route('POST', '/classes/:className', promiseEnsureIdempotency, req => { return this.handleCreate(req); }); - this.route( - 'PUT', - '/classes/:className/:objectId', - promiseEnsureIdempotency, - req => { - return this.handleUpdate(req); - } - ); + this.route('PUT', '/classes/:className/:objectId', promiseEnsureIdempotency, req => { + return this.handleUpdate(req); + }); this.route('DELETE', '/classes/:className/:objectId', req => { return this.handleDelete(req); }); diff --git a/src/Routers/CloudCodeRouter.js b/src/Routers/CloudCodeRouter.js index 9f4a82a2..32735312 100644 --- a/src/Routers/CloudCodeRouter.js +++ b/src/Routers/CloudCodeRouter.js @@ -56,28 +56,24 @@ export class CloudCodeRouter extends PromiseRouter { } static getJobs(req) { - return rest - .find(req.config, req.auth, '_JobSchedule', {}, {}) - .then(scheduledJobs => { - return { - response: scheduledJobs.results, - }; - }); + return rest.find(req.config, req.auth, '_JobSchedule', {}, {}).then(scheduledJobs => { + return { + response: scheduledJobs.results, + }; + }); } static getJobsData(req) { const config = req.config; const jobs = triggers.getJobs(config.applicationId) || {}; - return rest - .find(req.config, req.auth, '_JobSchedule', {}, {}) - .then(scheduledJobs => { - return { - response: { - in_use: scheduledJobs.results.map(job => job.jobName), - jobs: Object.keys(jobs), - }, - }; - }); + return rest.find(req.config, req.auth, '_JobSchedule', {}, {}).then(scheduledJobs => { + return { + response: { + in_use: scheduledJobs.results.map(job => job.jobName), + jobs: Object.keys(jobs), + }, + }; + }); } static createJob(req) { diff --git a/src/Routers/FeaturesRouter.js b/src/Routers/FeaturesRouter.js index c0cc56d7..649cefcb 100644 --- a/src/Routers/FeaturesRouter.js +++ b/src/Routers/FeaturesRouter.js @@ -4,61 +4,56 @@ import * as middleware from '../middlewares'; export class FeaturesRouter extends PromiseRouter { mountRoutes() { - this.route( - 'GET', - '/serverInfo', - middleware.promiseEnforceMasterKeyAccess, - req => { - const { config } = req; - const features = { - globalConfig: { - create: true, - read: true, - update: true, - delete: true, - }, - hooks: { - create: true, - read: true, - update: true, - delete: true, - }, - cloudCode: { - jobs: true, - }, - logs: { - level: true, - size: true, - order: true, - until: true, - from: true, - }, - push: { - immediatePush: config.hasPushSupport, - scheduledPush: config.hasPushScheduledSupport, - storedPushData: config.hasPushSupport, - pushAudiences: true, - localization: true, - }, - schemas: { - addField: true, - removeField: true, - addClass: true, - removeClass: true, - clearAllDataFromClass: true, - exportClass: false, - editClassLevelPermissions: true, - editPointerPermissions: true, - }, - }; + this.route('GET', '/serverInfo', middleware.promiseEnforceMasterKeyAccess, req => { + const { config } = req; + const features = { + globalConfig: { + create: true, + read: true, + update: true, + delete: true, + }, + hooks: { + create: true, + read: true, + update: true, + delete: true, + }, + cloudCode: { + jobs: true, + }, + logs: { + level: true, + size: true, + order: true, + until: true, + from: true, + }, + push: { + immediatePush: config.hasPushSupport, + scheduledPush: config.hasPushScheduledSupport, + storedPushData: config.hasPushSupport, + pushAudiences: true, + localization: true, + }, + schemas: { + addField: true, + removeField: true, + addClass: true, + removeClass: true, + clearAllDataFromClass: true, + exportClass: false, + editClassLevelPermissions: true, + editPointerPermissions: true, + }, + }; - return { - response: { - features: features, - parseServerVersion: version, - }, - }; - } - ); + return { + response: { + features: features, + parseServerVersion: version, + }, + }; + }); } } diff --git a/src/Routers/FilesRouter.js b/src/Routers/FilesRouter.js index 01d1103f..2b0140fe 100644 --- a/src/Routers/FilesRouter.js +++ b/src/Routers/FilesRouter.js @@ -40,9 +40,7 @@ export class FilesRouter { router.get('/files/:appId/metadata/:filename', this.metadataHandler); router.post('/files', function (req, res, next) { - next( - new Parse.Error(Parse.Error.INVALID_FILE_NAME, 'Filename not provided.') - ); + next(new Parse.Error(Parse.Error.INVALID_FILE_NAME, 'Filename not provided.')); }); router.post( @@ -72,13 +70,11 @@ export class FilesRouter { const filename = req.params.filename; const contentType = mime.getType(filename); if (isFileStreamable(req, filesController)) { - filesController - .handleFileStream(config, filename, req, res, contentType) - .catch(() => { - res.status(404); - res.set('Content-Type', 'text/plain'); - res.end('File not found.'); - }); + filesController.handleFileStream(config, filename, req, res, contentType).catch(() => { + res.status(404); + res.set('Content-Type', 'text/plain'); + res.end('File not found.'); + }); } else { filesController .getFileData(config, filename) @@ -103,9 +99,7 @@ export class FilesRouter { const contentType = req.get('Content-type'); if (!req.body || !req.body.length) { - next( - new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'Invalid file upload.') - ); + next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'Invalid file upload.')); return; } @@ -243,8 +237,5 @@ export class FilesRouter { } function isFileStreamable(req, filesController) { - return ( - req.get('Range') && - typeof filesController.adapter.handleFileStream === 'function' - ); + return req.get('Range') && typeof filesController.adapter.handleFileStream === 'function'; } diff --git a/src/Routers/FunctionsRouter.js b/src/Routers/FunctionsRouter.js index 85f59601..c6a20312 100644 --- a/src/Routers/FunctionsRouter.js +++ b/src/Routers/FunctionsRouter.js @@ -4,10 +4,7 @@ var Parse = require('parse/node').Parse, triggers = require('../triggers'); import PromiseRouter from '../PromiseRouter'; -import { - promiseEnforceMasterKeyAccess, - promiseEnsureIdempotency, -} from '../middlewares'; +import { promiseEnforceMasterKeyAccess, promiseEnsureIdempotency } from '../middlewares'; import { jobStatusHandler } from '../StatusHandler'; import _ from 'lodash'; import { logger } from '../logger'; @@ -121,10 +118,7 @@ export class FunctionsRouter extends PromiseRouter { const theFunction = triggers.getFunction(functionName, applicationId); if (!theFunction) { - throw new Parse.Error( - Parse.Error.SCRIPT_FAILED, - `Invalid function: "${functionName}"` - ); + throw new Parse.Error(Parse.Error.SCRIPT_FAILED, `Invalid function: "${functionName}"`); } let params = Object.assign({}, req.body, req.query); params = parseParams(params); @@ -141,15 +135,12 @@ export class FunctionsRouter extends PromiseRouter { }; return new Promise(function (resolve, reject) { - const userString = - req.auth && req.auth.user ? req.auth.user.id : undefined; + const userString = req.auth && req.auth.user ? req.auth.user.id : undefined; const cleanInput = logger.truncateLogMessage(JSON.stringify(params)); const { success, error, message } = FunctionsRouter.createResponseObject( result => { try { - const cleanResult = logger.truncateLogMessage( - JSON.stringify(result.response.result) - ); + const cleanResult = logger.truncateLogMessage(JSON.stringify(result.response.result)); logger.info( `Ran cloud function ${functionName} for user ${userString} with:\n Input: ${cleanInput}\n Result: ${cleanResult}`, { diff --git a/src/Routers/GlobalConfigRouter.js b/src/Routers/GlobalConfigRouter.js index ca189ead..f45c0768 100644 --- a/src/Routers/GlobalConfigRouter.js +++ b/src/Routers/GlobalConfigRouter.js @@ -54,14 +54,9 @@ export class GlobalConfigRouter extends PromiseRouter { this.route('GET', '/config', req => { return this.getGlobalConfig(req); }); - this.route( - 'PUT', - '/config', - middleware.promiseEnforceMasterKeyAccess, - req => { - return this.updateGlobalConfig(req); - } - ); + this.route('PUT', '/config', middleware.promiseEnforceMasterKeyAccess, req => { + return this.updateGlobalConfig(req); + }); } } diff --git a/src/Routers/GraphQLRouter.js b/src/Routers/GraphQLRouter.js index cdf25659..8c2cbd54 100644 --- a/src/Routers/GraphQLRouter.js +++ b/src/Routers/GraphQLRouter.js @@ -19,31 +19,19 @@ export class GraphQLRouter extends PromiseRouter { "read-only masterKey isn't allowed to update the GraphQL config." ); } - const data = await req.config.parseGraphQLController.updateGraphQLConfig( - req.body.params - ); + const data = await req.config.parseGraphQLController.updateGraphQLConfig(req.body.params); return { response: data, }; } mountRoutes() { - this.route( - 'GET', - GraphQLConfigPath, - middleware.promiseEnforceMasterKeyAccess, - req => { - return this.getGraphQLConfig(req); - } - ); - this.route( - 'PUT', - GraphQLConfigPath, - middleware.promiseEnforceMasterKeyAccess, - req => { - return this.updateGraphQLConfig(req); - } - ); + this.route('GET', GraphQLConfigPath, middleware.promiseEnforceMasterKeyAccess, req => { + return this.getGraphQLConfig(req); + }); + this.route('PUT', GraphQLConfigPath, middleware.promiseEnforceMasterKeyAccess, req => { + return this.updateGraphQLConfig(req); + }); } } diff --git a/src/Routers/HooksRouter.js b/src/Routers/HooksRouter.js index 404094cb..27ddfb98 100644 --- a/src/Routers/HooksRouter.js +++ b/src/Routers/HooksRouter.js @@ -4,15 +4,11 @@ import * as middleware from '../middlewares'; export class HooksRouter extends PromiseRouter { createHook(aHook, config) { - return config.hooksController - .createHook(aHook) - .then(hook => ({ response: hook })); + return config.hooksController.createHook(aHook).then(hook => ({ response: hook })); } updateHook(aHook, config) { - return config.hooksController - .updateHook(aHook) - .then(hook => ({ response: hook })); + return config.hooksController.updateHook(aHook).then(hook => ({ response: hook })); } handlePost(req) { @@ -22,17 +18,12 @@ export class HooksRouter extends PromiseRouter { handleGetFunctions(req) { var hooksController = req.config.hooksController; if (req.params.functionName) { - return hooksController - .getFunction(req.params.functionName) - .then(foundFunction => { - if (!foundFunction) { - throw new Parse.Error( - 143, - `no function named: ${req.params.functionName} is defined` - ); - } - return Promise.resolve({ response: foundFunction }); - }); + return hooksController.getFunction(req.params.functionName).then(foundFunction => { + if (!foundFunction) { + throw new Parse.Error(143, `no function named: ${req.params.functionName} is defined`); + } + return Promise.resolve({ response: foundFunction }); + }); } return hooksController.getFunctions().then( @@ -52,26 +43,19 @@ export class HooksRouter extends PromiseRouter { .getTrigger(req.params.className, req.params.triggerName) .then(foundTrigger => { if (!foundTrigger) { - throw new Parse.Error( - 143, - `class ${req.params.className} does not exist` - ); + throw new Parse.Error(143, `class ${req.params.className} does not exist`); } return Promise.resolve({ response: foundTrigger }); }); } - return hooksController - .getTriggers() - .then(triggers => ({ response: triggers || [] })); + return hooksController.getTriggers().then(triggers => ({ response: triggers || [] })); } handleDelete(req) { var hooksController = req.config.hooksController; if (req.params.functionName) { - return hooksController - .deleteFunction(req.params.functionName) - .then(() => ({ response: {} })); + return hooksController.deleteFunction(req.params.functionName).then(() => ({ response: {} })); } else if (req.params.className && req.params.triggerName) { return hooksController .deleteTrigger(req.params.className, req.params.triggerName) diff --git a/src/Routers/IAPValidationRouter.js b/src/Routers/IAPValidationRouter.js index ad5de163..a270054f 100644 --- a/src/Routers/IAPValidationRouter.js +++ b/src/Routers/IAPValidationRouter.js @@ -58,10 +58,7 @@ function getFileForProductIdentifier(productIdentifier, req) { const products = result.results; if (!products || products.length != 1) { // Error not found or too many - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.'); } var download = products[0].download; @@ -76,10 +73,7 @@ export class IAPValidationRouter extends PromiseRouter { if (!receipt || !productIdentifier) { // TODO: Error, malformed request - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'missing receipt or productIdentifier' - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'missing receipt or productIdentifier'); } // Transform the object if there diff --git a/src/Routers/InstallationsRouter.js b/src/Routers/InstallationsRouter.js index 609db51e..e7cbbbae 100644 --- a/src/Routers/InstallationsRouter.js +++ b/src/Routers/InstallationsRouter.js @@ -10,10 +10,7 @@ export class InstallationsRouter extends ClassesRouter { } handleFind(req) { - const body = Object.assign( - req.body, - ClassesRouter.JSONFromQuery(req.query) - ); + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); const options = ClassesRouter.optionsFromBody(body); return rest .find( @@ -40,14 +37,9 @@ export class InstallationsRouter extends ClassesRouter { this.route('POST', '/installations', promiseEnsureIdempotency, req => { return this.handleCreate(req); }); - this.route( - 'PUT', - '/installations/:objectId', - promiseEnsureIdempotency, - req => { - return this.handleUpdate(req); - } - ); + this.route('PUT', '/installations/:objectId', promiseEnsureIdempotency, req => { + return this.handleUpdate(req); + }); this.route('DELETE', '/installations/:objectId', req => { return this.handleDelete(req); }); diff --git a/src/Routers/LogsRouter.js b/src/Routers/LogsRouter.js index 0bc2e234..182a4f16 100644 --- a/src/Routers/LogsRouter.js +++ b/src/Routers/LogsRouter.js @@ -17,10 +17,7 @@ export class LogsRouter extends PromiseRouter { validateRequest(req) { if (!req.config || !req.config.loggerController) { - throw new Parse.Error( - Parse.Error.PUSH_MISCONFIGURED, - 'Logger adapter is not available' - ); + throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Logger adapter is not available'); } } diff --git a/src/Routers/PublicAPIRouter.js b/src/Routers/PublicAPIRouter.js index 74538354..5009ee7d 100644 --- a/src/Routers/PublicAPIRouter.js +++ b/src/Routers/PublicAPIRouter.js @@ -12,8 +12,7 @@ const views = path.resolve(__dirname, '../../views'); export class PublicAPIRouter extends PromiseRouter { verifyEmail(req) { const { username, token: rawToken } = req.query; - const token = - rawToken && typeof rawToken !== 'string' ? rawToken.toString() : rawToken; + const token = rawToken && typeof rawToken !== 'string' ? rawToken.toString() : rawToken; const appId = req.params.appId; const config = Config.get(appId); @@ -95,22 +94,15 @@ export class PublicAPIRouter extends PromiseRouter { }); } // Should we keep the file in memory or leave like that? - fs.readFile( - path.resolve(views, 'choose_password'), - 'utf-8', - (err, data) => { - if (err) { - return reject(err); - } - data = data.replace( - 'PARSE_SERVER_URL', - `'${config.publicServerURL}'` - ); - resolve({ - text: data, - }); + fs.readFile(path.resolve(views, 'choose_password'), 'utf-8', (err, data) => { + if (err) { + return reject(err); } - ); + data = data.replace('PARSE_SERVER_URL', `'${config.publicServerURL}'`); + resolve({ + text: data, + }); + }); }); } @@ -126,8 +118,7 @@ export class PublicAPIRouter extends PromiseRouter { } const { username, token: rawToken } = req.query; - const token = - rawToken && typeof rawToken !== 'string' ? rawToken.toString() : rawToken; + const token = rawToken && typeof rawToken !== 'string' ? rawToken.toString() : rawToken; if (!username || !token) { return this.invalidLink(req); @@ -164,8 +155,7 @@ export class PublicAPIRouter extends PromiseRouter { } const { username, new_password, token: rawToken } = req.body; - const token = - rawToken && typeof rawToken !== 'string' ? rawToken.toString() : rawToken; + const token = rawToken && typeof rawToken !== 'string' ? rawToken.toString() : rawToken; if ((!username || !token || !new_password) && req.xhr === false) { return this.invalidLink(req); diff --git a/src/Routers/PurgeRouter.js b/src/Routers/PurgeRouter.js index 6d0aca0c..3195d134 100644 --- a/src/Routers/PurgeRouter.js +++ b/src/Routers/PurgeRouter.js @@ -30,14 +30,9 @@ export class PurgeRouter extends PromiseRouter { } mountRoutes() { - this.route( - 'DELETE', - '/purge/:className', - middleware.promiseEnforceMasterKeyAccess, - req => { - return this.handlePurge(req); - } - ); + this.route('DELETE', '/purge/:className', middleware.promiseEnforceMasterKeyAccess, req => { + return this.handlePurge(req); + }); } } diff --git a/src/Routers/PushRouter.js b/src/Routers/PushRouter.js index b6542fce..e5d6a78d 100644 --- a/src/Routers/PushRouter.js +++ b/src/Routers/PushRouter.js @@ -4,12 +4,7 @@ import { Parse } from 'parse/node'; export class PushRouter extends PromiseRouter { mountRoutes() { - this.route( - 'POST', - '/push', - middleware.promiseEnforceMasterKeyAccess, - PushRouter.handlePOST - ); + this.route('POST', '/push', middleware.promiseEnforceMasterKeyAccess, PushRouter.handlePOST); } static handlePOST(req) { @@ -21,10 +16,7 @@ export class PushRouter extends PromiseRouter { } const pushController = req.config.pushController; if (!pushController) { - 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'); } const where = PushRouter.getQueryCondition(req); diff --git a/src/Routers/SchemasRouter.js b/src/Routers/SchemasRouter.js index efc831dc..ae0a736e 100644 --- a/src/Routers/SchemasRouter.js +++ b/src/Routers/SchemasRouter.js @@ -28,15 +28,9 @@ function getOneSchema(req) { .then(schema => ({ response: schema })) .catch(error => { if (error === undefined) { - throw new Parse.Error( - Parse.Error.INVALID_CLASS_NAME, - `Class ${className} does not exist.` - ); + throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} does not exist.`); } else { - throw new Parse.Error( - Parse.Error.INTERNAL_SERVER_ERROR, - 'Database adapter error.' - ); + throw new Parse.Error(Parse.Error.INTERNAL_SERVER_ERROR, 'Database adapter error.'); } }); } @@ -50,10 +44,7 @@ function createSchema(req) { } if (req.params.className && req.body.className) { if (req.params.className != req.body.className) { - return classNameMismatchResponse( - req.body.className, - req.params.className - ); + return classNameMismatchResponse(req.body.className, req.params.className); } } @@ -116,31 +107,19 @@ const deleteSchema = req => { SchemaController.invalidClassNameMessage(req.params.className) ); } - return req.config.database - .deleteSchema(req.params.className) - .then(() => ({ response: {} })); + return req.config.database.deleteSchema(req.params.className).then(() => ({ response: {} })); }; export class SchemasRouter extends PromiseRouter { mountRoutes() { - this.route( - 'GET', - '/schemas', - middleware.promiseEnforceMasterKeyAccess, - getAllSchemas - ); + this.route('GET', '/schemas', middleware.promiseEnforceMasterKeyAccess, getAllSchemas); this.route( 'GET', '/schemas/:className', middleware.promiseEnforceMasterKeyAccess, getOneSchema ); - this.route( - 'POST', - '/schemas', - middleware.promiseEnforceMasterKeyAccess, - createSchema - ); + this.route('POST', '/schemas', middleware.promiseEnforceMasterKeyAccess, createSchema); this.route( 'POST', '/schemas/:className', diff --git a/src/Routers/SessionsRouter.js b/src/Routers/SessionsRouter.js index dac7cff8..b2577c93 100644 --- a/src/Routers/SessionsRouter.js +++ b/src/Routers/SessionsRouter.js @@ -11,10 +11,7 @@ export class SessionsRouter extends ClassesRouter { handleMe(req) { // TODO: Verify correct behavior if (!req.info || !req.info.sessionToken) { - throw new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'Session token required.' - ); + throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token required.'); } return rest .find( @@ -28,10 +25,7 @@ export class SessionsRouter extends ClassesRouter { ) .then(response => { if (!response.results || response.results.length == 0) { - throw new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'Session token not found.' - ); + throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Session token not found.'); } return { response: response.results[0], diff --git a/src/Routers/UsersRouter.js b/src/Routers/UsersRouter.js index 61448dac..7e278456 100644 --- a/src/Routers/UsersRouter.js +++ b/src/Routers/UsersRouter.js @@ -50,26 +50,17 @@ export class UsersRouter extends ClassesRouter { // TODO: use the right error codes / descriptions. if (!username && !email) { - throw new Parse.Error( - Parse.Error.USERNAME_MISSING, - 'username/email is required.' - ); + throw new Parse.Error(Parse.Error.USERNAME_MISSING, 'username/email is required.'); } if (!password) { - throw new Parse.Error( - Parse.Error.PASSWORD_MISSING, - 'password is required.' - ); + throw new Parse.Error(Parse.Error.PASSWORD_MISSING, 'password is required.'); } if ( typeof password !== 'string' || (email && typeof email !== 'string') || (username && typeof username !== 'string') ) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Invalid username/password.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Invalid username/password.'); } let user; @@ -86,10 +77,7 @@ export class UsersRouter extends ClassesRouter { .find('_User', query) .then(results => { if (!results.length) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Invalid username/password.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Invalid username/password.'); } if (results.length > 1) { @@ -111,34 +99,21 @@ export class UsersRouter extends ClassesRouter { }) .then(() => { if (!isValidPassword) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Invalid username/password.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Invalid username/password.'); } // Ensure the user isn't locked out // A locked out user won't be able to login // To lock a user out, just set the ACL to `masterKey` only ({}). // Empty ACL is OK - if ( - !req.auth.isMaster && - user.ACL && - Object.keys(user.ACL).length == 0 - ) { - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Invalid username/password.' - ); + if (!req.auth.isMaster && user.ACL && Object.keys(user.ACL).length == 0) { + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Invalid username/password.'); } if ( req.config.verifyUserEmails && req.config.preventLoginWithUnverifiedEmail && !user.emailVerified ) { - throw new Parse.Error( - Parse.Error.EMAIL_NOT_FOUND, - 'User email is not verified.' - ); + throw new Parse.Error(Parse.Error.EMAIL_NOT_FOUND, 'User email is not verified.'); } delete user.password; @@ -166,10 +141,7 @@ export class UsersRouter extends ClassesRouter { handleMe(req) { 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'); } const sessionToken = req.info.sessionToken; return rest @@ -183,15 +155,8 @@ export class UsersRouter extends ClassesRouter { req.info.context ) .then(response => { - if ( - !response.results || - response.results.length == 0 || - !response.results[0].user - ) { - throw new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'Invalid session token' - ); + if (!response.results || response.results.length == 0 || !response.results[0].user) { + throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Invalid session token'); } else { const user = response.results[0].user; // Send token back on the login, because SDKs expect that. @@ -228,8 +193,7 @@ export class UsersRouter extends ClassesRouter { } // Calculate the expiry time. const expiresAt = new Date( - changedAt.getTime() + - 86400000 * req.config.passwordPolicy.maxPasswordAge + changedAt.getTime() + 86400000 * req.config.passwordPolicy.maxPasswordAge ); if (expiresAt < new Date()) // fail of current time is past password expiry time @@ -267,9 +231,7 @@ export class UsersRouter extends ClassesRouter { await createSession(); - const afterLoginUser = Parse.User.fromJSON( - Object.assign({ className: '_User' }, user) - ); + const afterLoginUser = Parse.User.fromJSON(Object.assign({ className: '_User' }, user)); maybeRunTrigger( TriggerTypes.afterLogin, { ...req.auth, user: afterLoginUser }, @@ -345,8 +307,7 @@ export class UsersRouter extends ClassesRouter { emailAdapter: req.config.userController.adapter, appName: req.config.appName, publicServerURL: req.config.publicServerURL, - emailVerifyTokenValidityDuration: - req.config.emailVerifyTokenValidityDuration, + emailVerifyTokenValidityDuration: req.config.emailVerifyTokenValidityDuration, }); } catch (e) { if (typeof e === 'string') { @@ -366,10 +327,7 @@ export class UsersRouter extends ClassesRouter { const { email } = req.body; 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') { throw new Parse.Error( @@ -403,10 +361,7 @@ export class UsersRouter extends ClassesRouter { const { email } = req.body; 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') { throw new Parse.Error( @@ -417,10 +372,7 @@ export class UsersRouter extends ClassesRouter { return req.config.database.find('_User', { email: email }).then(results => { if (!results.length || results.length < 1) { - throw new Parse.Error( - Parse.Error.EMAIL_NOT_FOUND, - `No user found with email ${email}` - ); + throw new Parse.Error(Parse.Error.EMAIL_NOT_FOUND, `No user found with email ${email}`); } const user = results[0]; @@ -428,10 +380,7 @@ export class UsersRouter extends ClassesRouter { delete user.password; if (user.emailVerified) { - throw new Parse.Error( - Parse.Error.OTHER_CAUSE, - `Email ${email} is already verified.` - ); + throw new Parse.Error(Parse.Error.OTHER_CAUSE, `Email ${email} is already verified.`); } const userController = req.config.userController; diff --git a/src/StatusHandler.js b/src/StatusHandler.js index 8ae2d655..45010f38 100644 --- a/src/StatusHandler.js +++ b/src/StatusHandler.js @@ -57,12 +57,10 @@ function restStatusHandler(className, config) { const auth = Auth.master(config); function create(object) { lastPromise = lastPromise.then(() => { - return rest - .create(config, auth, className, object) - .then(({ response }) => { - // merge the objects - return Promise.resolve(Object.assign({}, object, response)); - }); + return rest.create(config, auth, className, object).then(({ response }) => { + // merge the objects + return Promise.resolve(Object.assign({}, object, response)); + }); }); return lastPromise; } @@ -156,9 +154,7 @@ export function pushStatusHandler(config, existingObjectId) { pushTime = body.push_time; status = 'scheduled'; } else { - logger.warn( - 'Trying to schedule a push while server is not configured.' - ); + logger.warn('Trying to schedule a push while server is not configured.'); logger.warn('Push will be sent immediately'); } } @@ -216,8 +212,7 @@ export function pushStatusHandler(config, existingObjectId) { const trackSent = function ( results, UTCOffset, - cleanupInstallations = process.env - .PARSE_SERVER_CLEANUP_INVALID_INSTALLATIONS + cleanupInstallations = process.env.PARSE_SERVER_CLEANUP_INVALID_INSTALLATIONS ) { const update = { numSent: 0, @@ -289,9 +284,7 @@ export function pushStatusHandler(config, existingObjectId) { }); if (devicesToRemove.length > 0 && cleanupInstallations) { - logger.info( - `Removing device tokens on ${devicesToRemove.length} _Installations` - ); + logger.info(`Removing device tokens on ${devicesToRemove.length} _Installations`); database.update( '_Installation', { deviceToken: { $in: devicesToRemove } }, diff --git a/src/batch.js b/src/batch.js index 667960ca..9bf6da78 100644 --- a/src/batch.js +++ b/src/batch.js @@ -28,10 +28,7 @@ function makeBatchRoutingPathFunction(originalUrl, serverURL, publicServerURL) { const makeRoutablePath = function (requestPath) { // The routablePath is the path minus the api prefix if (requestPath.slice(0, apiPrefix.length) != apiPrefix) { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'cannot route batch path ' + requestPath - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'cannot route batch path ' + requestPath); } return path.posix.join('/', requestPath.slice(apiPrefix.length)); }; @@ -44,12 +41,7 @@ function makeBatchRoutingPathFunction(originalUrl, serverURL, publicServerURL) { return function (requestPath) { // Build the new path by removing the public path // and joining with the local path - const 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 return makeRoutablePath(newPath); }; @@ -62,10 +54,7 @@ function makeBatchRoutingPathFunction(originalUrl, serverURL, publicServerURL) { // TODO: pass along auth correctly function handleBatch(router, req) { if (!Array.isArray(req.body.requests)) { - throw new Parse.Error( - Parse.Error.INVALID_JSON, - 'requests must be an array' - ); + throw new Parse.Error(Parse.Error.INVALID_JSON, 'requests must be an array'); } // The batch paths are all from the root of our domain. @@ -100,16 +89,14 @@ function handleBatch(router, req) { info: req.info, }; - return router - .tryRouteRequest(restRequest.method, routablePath, request) - .then( - response => { - return { success: response.response }; - }, - error => { - return { error: { code: error.code, error: error.message } }; - } - ); + return router.tryRouteRequest(restRequest.method, routablePath, request).then( + response => { + return { success: response.response }; + }, + error => { + return { error: { code: error.code, error: error.message } }; + } + ); }); return Promise.all(promises).then(results => { diff --git a/src/cli/parse-server.js b/src/cli/parse-server.js index 4828b550..4ee9dc4c 100755 --- a/src/cli/parse-server.js +++ b/src/cli/parse-server.js @@ -15,23 +15,15 @@ const help = function () { console.log(' Usage with npm start'); console.log(''); console.log(' $ npm start -- path/to/config.json'); - console.log( - ' $ npm start -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL' - ); - console.log( - ' $ npm start -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL' - ); + console.log(' $ npm start -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL'); + console.log(' $ npm start -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL'); console.log(''); console.log(''); console.log(' Usage:'); console.log(''); console.log(' $ parse-server path/to/config.json'); - console.log( - ' $ parse-server -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL' - ); - console.log( - ' $ parse-server -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL' - ); + console.log(' $ parse-server -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL'); + console.log(' $ parse-server -- --appId APP_ID --masterKey MASTER_KEY --serverURL serverURL'); console.log(''); }; @@ -43,9 +35,7 @@ runner({ if (!options.appId || !options.masterKey) { program.outputHelp(); console.error(''); - console.error( - '\u001b[31mERROR: appId and masterKey are required\u001b[0m' - ); + console.error('\u001b[31mERROR: appId and masterKey are required\u001b[0m'); console.error(''); process.exit(1); } @@ -67,19 +57,14 @@ runner({ } if (options.cluster) { - const numCPUs = - typeof options.cluster === 'number' - ? options.cluster - : os.cpus().length; + const numCPUs = typeof options.cluster === 'number' ? options.cluster : os.cpus().length; if (cluster.isMaster) { logOptions(); for (let i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code) => { - console.log( - `worker ${worker.process.pid} died (${code})... Restarting` - ); + console.log(`worker ${worker.process.pid} died (${code})... Restarting`); cluster.fork(); }); } else { @@ -96,9 +81,7 @@ runner({ } function printSuccessMessage() { - console.log( - '[' + process.pid + '] parse-server running on ' + options.serverURL - ); + console.log('[' + process.pid + '] parse-server running on ' + options.serverURL); if (options.mountGraphQL) { console.log( '[' + diff --git a/src/cloud-code/Parse.Cloud.js b/src/cloud-code/Parse.Cloud.js index ddd31bd2..30f00b9e 100644 --- a/src/cloud-code/Parse.Cloud.js +++ b/src/cloud-code/Parse.Cloud.js @@ -2,10 +2,7 @@ import { Parse } from 'parse/node'; import * as triggers from '../triggers'; function isParseObjectConstructor(object) { - return ( - typeof object === 'function' && - Object.prototype.hasOwnProperty.call(object, 'className') - ); + return typeof object === 'function' && Object.prototype.hasOwnProperty.call(object, 'className'); } function getClassName(parseClass) { @@ -52,12 +49,7 @@ var ParseCloud = {}; * @param {(Object|Function)} validator An optional function to help validating cloud code. This function can be an async function and should take one parameter a {@link Parse.Cloud.FunctionRequest}, or a {@link Parse.Cloud.ValidatorObject}. */ ParseCloud.define = function (functionName, handler, validationHandler) { - triggers.addFunction( - functionName, - handler, - validationHandler, - Parse.applicationId - ); + triggers.addFunction(functionName, handler, validationHandler, Parse.applicationId); }; /** @@ -178,12 +170,7 @@ ParseCloud.beforeLogin = function (handler) { className = getClassName(handler); handler = arguments[1]; } - triggers.addTrigger( - triggers.Types.beforeLogin, - className, - handler, - Parse.applicationId - ); + triggers.addTrigger(triggers.Types.beforeLogin, className, handler, Parse.applicationId); }; /** @@ -213,12 +200,7 @@ ParseCloud.afterLogin = function (handler) { className = getClassName(handler); handler = arguments[1]; } - triggers.addTrigger( - triggers.Types.afterLogin, - className, - handler, - Parse.applicationId - ); + triggers.addTrigger(triggers.Types.afterLogin, className, handler, Parse.applicationId); }; /** @@ -247,12 +229,7 @@ ParseCloud.afterLogout = function (handler) { className = getClassName(handler); handler = arguments[1]; } - triggers.addTrigger( - triggers.Types.afterLogout, - className, - handler, - Parse.applicationId - ); + triggers.addTrigger(triggers.Types.afterLogout, className, handler, Parse.applicationId); }; /** @@ -613,11 +590,7 @@ ParseCloud.onLiveQueryEvent = function (handler) { * @param {Function} func The function to run after a live query event. This function can be async and should take one parameter, a {@link Parse.Cloud.LiveQueryEventTrigger}. * @param {(Object|Function)} validator An optional function to help validating cloud code. This function can be an async function and should take one parameter a {@link Parse.Cloud.LiveQueryEventTrigger}, or a {@link Parse.Cloud.ValidatorObject}. */ -ParseCloud.afterLiveQueryEvent = function ( - parseClass, - handler, - validationHandler -) { +ParseCloud.afterLiveQueryEvent = function (parseClass, handler, validationHandler) { const className = getClassName(parseClass); triggers.addTrigger( triggers.Types.afterEvent, diff --git a/src/cloud-code/httpRequest.js b/src/cloud-code/httpRequest.js index 699525d5..0f70a8d6 100644 --- a/src/cloud-code/httpRequest.js +++ b/src/cloud-code/httpRequest.js @@ -47,18 +47,13 @@ const encodeBody = function ({ body, headers = {} }) { } else { /* istanbul ignore next */ if (contentTypeKeys.length > 1) { - log.error( - 'Parse.Cloud.httpRequest', - 'multiple content-type headers are set.' - ); + log.error('Parse.Cloud.httpRequest', 'multiple content-type headers are set.'); } // There maybe many, we'll just take the 1st one var contentType = contentTypeKeys[0]; if (headers[contentType].match(/application\/json/i)) { body = JSON.stringify(body); - } else if ( - headers[contentType].match(/application\/x-www-form-urlencoded/i) - ) { + } else if (headers[contentType].match(/application\/x-www-form-urlencoded/i)) { body = querystring.stringify(body); } } @@ -137,10 +132,7 @@ module.exports = function httpRequest(options) { requestOptions.agent = options.agent; } return new Promise((resolve, reject) => { - const req = client.request( - requestOptions, - makeCallback(resolve, reject, options) - ); + const req = client.request(requestOptions, makeCallback(resolve, reject, options)); if (options.body) { req.write(options.body); } diff --git a/src/cryptoUtils.js b/src/cryptoUtils.js index 580b843a..f85b62c3 100644 --- a/src/cryptoUtils.js +++ b/src/cryptoUtils.js @@ -23,8 +23,7 @@ export function randomString(size: number): string { if (size === 0) { throw new Error('Zero-length randomString is useless.'); } - const chars = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789'; + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789'; let objectId = ''; const bytes = randomBytes(size); for (let i = 0; i < bytes.length; ++i) { @@ -44,7 +43,5 @@ export function newToken(): string { } export function md5Hash(string: string): string { - return createHash('md5') - .update(string) - .digest('hex'); + return createHash('md5').update(string).digest('hex'); } diff --git a/src/defaults.js b/src/defaults.js index ba603424..a2b105d8 100644 --- a/src/defaults.js +++ b/src/defaults.js @@ -16,16 +16,13 @@ const { verbose, level } = (() => { return { verbose, level: verbose ? 'verbose' : undefined }; })(); -const DefinitionDefaults = Object.keys(ParseServerOptions).reduce( - (memo, key) => { - const def = ParseServerOptions[key]; - if (Object.prototype.hasOwnProperty.call(def, 'default')) { - memo[key] = def.default; - } - return memo; - }, - {} -); +const DefinitionDefaults = Object.keys(ParseServerOptions).reduce((memo, key) => { + const def = ParseServerOptions[key]; + if (Object.prototype.hasOwnProperty.call(def, 'default')) { + memo[key] = def.default; + } + return memo; +}, {}); const computedDefaults = { jsonLogs: process.env.JSON_LOGS || false, diff --git a/src/deprecated.js b/src/deprecated.js index e92c6212..dd20a730 100644 --- a/src/deprecated.js +++ b/src/deprecated.js @@ -1,5 +1,5 @@ export function useExternal(name, moduleName) { - return function() { + return function () { throw `${name} is not provided by parse-server anymore; please install ${moduleName}`; }; } diff --git a/src/index.js b/src/index.js index 4bfc2934..2806fb8b 100644 --- a/src/index.js +++ b/src/index.js @@ -13,7 +13,7 @@ import { ParseServerOptions } from './Options'; import { ParseGraphQLServer } from './GraphQL/ParseGraphQLServer'; // Factory function -const _ParseServer = function(options: ParseServerOptions) { +const _ParseServer = function (options: ParseServerOptions) { const server = new ParseServer(options); return server.app; }; diff --git a/src/middlewares.js b/src/middlewares.js index 2a2af995..1c0a3720 100644 --- a/src/middlewares.js +++ b/src/middlewares.js @@ -81,8 +81,7 @@ export function handleParseHeaders(req, res, next) { req.body && req.body._ApplicationId && AppCache.get(req.body._ApplicationId) && - (!info.masterKey || - AppCache.get(req.body._ApplicationId).masterKey === info.masterKey) + (!info.masterKey || AppCache.get(req.body._ApplicationId).masterKey === info.masterKey) ) { info.appId = req.body._ApplicationId; info.javascriptKey = req.body._JavaScriptKey || ''; @@ -251,10 +250,7 @@ export function handleParseHeaders(req, res, next) { return; } else { // TODO: Determine the correct error scenario. - req.config.loggerController.error( - 'error getting auth for sessionToken', - error - ); + req.config.loggerController.error('error getting auth for sessionToken', error); throw new Parse.Error(Parse.Error.UNKNOWN_ERROR, error); } }); @@ -327,10 +323,7 @@ export function allowCrossDomain(appId) { res.header('Access-Control-Allow-Origin', allowOrigin); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', allowHeaders); - res.header( - 'Access-Control-Expose-Headers', - 'X-Parse-Job-Status-Id, X-Parse-Push-Status-Id' - ); + res.header('Access-Control-Expose-Headers', 'X-Parse-Job-Status-Id, X-Parse-Push-Status-Id'); // intercept OPTIONS method if ('OPTIONS' == req.method) { res.sendStatus(200); @@ -443,9 +436,7 @@ export function promiseEnsureIdempotency(req) { return Promise.resolve(); } // Try to store request - const expiryDate = new Date( - new Date().setSeconds(new Date().getSeconds() + ttl) - ); + const expiryDate = new Date(new Date().setSeconds(new Date().getSeconds() + ttl)); return rest .create(config, auth.master(config), '_Idempotency', { reqId: requestId, @@ -453,10 +444,7 @@ export function promiseEnsureIdempotency(req) { }) .catch(e => { if (e.code == Parse.Error.DUPLICATE_VALUE) { - throw new Parse.Error( - Parse.Error.DUPLICATE_REQUEST, - 'Duplicate request' - ); + throw new Parse.Error(Parse.Error.DUPLICATE_REQUEST, 'Duplicate request'); } throw e; }); diff --git a/src/rest.js b/src/rest.js index c605e8b5..f443d594 100644 --- a/src/rest.js +++ b/src/rest.js @@ -15,31 +15,16 @@ var triggers = require('./triggers'); function checkTriggers(className, config, types) { return types.some(triggerType => { - return triggers.getTrigger( - className, - triggers.Types[triggerType], - config.applicationId - ); + return triggers.getTrigger(className, triggers.Types[triggerType], config.applicationId); }); } function checkLiveQuery(className, config) { - return ( - config.liveQueryController && - config.liveQueryController.hasLiveQuery(className) - ); + return config.liveQueryController && config.liveQueryController.hasLiveQuery(className); } // Returns a promise for an object with optional keys 'results' and 'count'. -function find( - config, - auth, - className, - restWhere, - restOptions, - clientSDK, - context -) { +function find(config, auth, className, restWhere, restOptions, clientSDK, context) { enforceRoleSecurity('find', className, auth); return triggers .maybeRunQueryTrigger( @@ -54,28 +39,13 @@ function find( .then(result => { restWhere = result.restWhere || restWhere; restOptions = result.restOptions || restOptions; - const query = new RestQuery( - config, - auth, - className, - restWhere, - restOptions, - clientSDK - ); + const query = new RestQuery(config, auth, className, restWhere, restOptions, clientSDK); return query.execute(); }); } // get is just like find but only queries an objectId. -const get = ( - config, - auth, - className, - objectId, - restOptions, - clientSDK, - context -) => { +const get = (config, auth, className, objectId, restOptions, clientSDK, context) => { var restWhere = { objectId }; enforceRoleSecurity('get', className, auth); return triggers @@ -92,14 +62,7 @@ const get = ( .then(result => { restWhere = result.restWhere || restWhere; restOptions = result.restOptions || restOptions; - const query = new RestQuery( - config, - auth, - className, - restWhere, - restOptions, - clientSDK - ); + const query = new RestQuery(config, auth, className, restWhere, restOptions, clientSDK); return query.execute(); }); }; @@ -111,10 +74,7 @@ function del(config, auth, className, objectId, context) { } if (className === '_User' && auth.isUnauthenticated()) { - throw new Parse.Error( - Parse.Error.SESSION_MISSING, - 'Insufficient auth to delete user' - ); + throw new Parse.Error(Parse.Error.SESSION_MISSING, 'Insufficient auth to delete user'); } enforceRoleSecurity('delete', className, auth); @@ -124,10 +84,7 @@ function del(config, auth, className, objectId, context) { return Promise.resolve() .then(() => { - const hasTriggers = checkTriggers(className, config, [ - 'beforeDelete', - 'afterDelete', - ]); + const hasTriggers = checkTriggers(className, config, ['beforeDelete', 'afterDelete']); const hasLiveQuery = checkLiveQuery(className, config); if (hasTriggers || hasLiveQuery || className == '_Session') { return new RestQuery(config, auth, className, { objectId }) @@ -138,10 +95,7 @@ function del(config, auth, className, objectId, context) { firstResult.className = className; if (className === '_Session' && !auth.isMaster) { if (!auth.user || firstResult.user.objectId !== auth.user.id) { - throw new Parse.Error( - Parse.Error.INVALID_SESSION_TOKEN, - 'Invalid session token' - ); + throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Invalid session token'); } } var cacheAdapter = config.cacheController; @@ -156,10 +110,7 @@ function del(config, auth, className, objectId, context) { context ); } - throw new Parse.Error( - Parse.Error.OBJECT_NOT_FOUND, - 'Object not found for delete.' - ); + throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found for delete.'); }); } return Promise.resolve({}); @@ -195,12 +146,7 @@ function del(config, auth, className, objectId, context) { .then(() => { // Notify LiveQuery server if possible const perms = schemaController.getClassLevelPermissions(className); - config.liveQueryController.onAfterDelete( - className, - inflatedObject, - null, - perms - ); + config.liveQueryController.onAfterDelete(className, inflatedObject, null, perms); return triggers.maybeRunTrigger( triggers.Types.afterDelete, auth, @@ -218,39 +164,19 @@ function del(config, auth, className, objectId, context) { // Returns a promise for a {response, status, location} object. function create(config, auth, className, restObject, clientSDK, context) { enforceRoleSecurity('create', className, auth); - var write = new RestWrite( - config, - auth, - className, - null, - restObject, - null, - clientSDK, - context - ); + var write = new RestWrite(config, auth, className, null, restObject, null, clientSDK, context); return write.execute(); } // Returns a promise that contains the fields of the update that the // REST API is supposed to return. // Usually, this is just updatedAt. -function update( - config, - auth, - className, - restWhere, - restObject, - clientSDK, - context -) { +function update(config, auth, className, restWhere, restObject, clientSDK, context) { enforceRoleSecurity('update', className, auth); return Promise.resolve() .then(() => { - const hasTriggers = checkTriggers(className, config, [ - 'beforeSave', - 'afterSave', - ]); + const hasTriggers = checkTriggers(className, config, ['beforeSave', 'afterSave']); const hasLiveQuery = checkLiveQuery(className, config); if (hasTriggers || hasLiveQuery) { // Do not use find, as it runs the before finds @@ -292,11 +218,7 @@ function update( function handleSessionMissingError(error, className, auth) { // If we're trying to update a user without / with bad session token - if ( - className === '_User' && - error.code === Parse.Error.OBJECT_NOT_FOUND && - !auth.isMaster - ) { + if (className === '_User' && error.code === Parse.Error.OBJECT_NOT_FOUND && !auth.isMaster) { throw new Parse.Error(Parse.Error.SESSION_MISSING, 'Insufficient auth.'); } throw error; @@ -326,10 +248,7 @@ function enforceRoleSecurity(method, className, auth) { } // readOnly masterKey is not allowed - if ( - auth.isReadOnly && - (method === 'delete' || method === 'create' || method === 'update') - ) { + if (auth.isReadOnly && (method === 'delete' || method === 'create' || method === 'update')) { const error = `read-only masterKey isn't allowed to perform the ${method} operation.`; throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error); } diff --git a/src/triggers.js b/src/triggers.js index 19e8a205..88dae097 100644 --- a/src/triggers.js +++ b/src/triggers.js @@ -53,10 +53,7 @@ function validateClassNameForTriggers(className, type) { // TODO: Allow proper documented way of using nested increment ops throw 'Only afterSave is allowed on _PushStatus'; } - if ( - (type === Types.beforeLogin || type === Types.afterLogin) && - className !== '_User' - ) { + if ((type === Types.beforeLogin || type === Types.afterLogin) && className !== '_User') { // TODO: check if upstream code will handle `Error` instance rather // than this anti-pattern of throwing strings throw 'Only the _User class is allowed for the beforeLogin and afterLogin triggers'; @@ -121,12 +118,7 @@ function get(category, name, applicationId) { return store[lastComponent]; } -export function addFunction( - functionName, - handler, - validationHandler, - applicationId -) { +export function addFunction(functionName, handler, validationHandler, applicationId) { add(Category.Functions, functionName, handler, applicationId); add(Category.Validators, functionName, validationHandler, applicationId); } @@ -135,51 +127,20 @@ export function addJob(jobName, handler, applicationId) { add(Category.Jobs, jobName, handler, applicationId); } -export function addTrigger( - type, - className, - handler, - applicationId, - validationHandler -) { +export function addTrigger(type, className, handler, applicationId, validationHandler) { validateClassNameForTriggers(className, type); add(Category.Triggers, `${type}.${className}`, handler, applicationId); - add( - Category.Validators, - `${type}.${className}`, - validationHandler, - applicationId - ); + add(Category.Validators, `${type}.${className}`, validationHandler, applicationId); } -export function addFileTrigger( - type, - handler, - applicationId, - validationHandler -) { +export function addFileTrigger(type, handler, applicationId, validationHandler) { add(Category.Triggers, `${type}.${FileClassName}`, handler, applicationId); - add( - Category.Validators, - `${type}.${FileClassName}`, - validationHandler, - applicationId - ); + add(Category.Validators, `${type}.${FileClassName}`, validationHandler, applicationId); } -export function addConnectTrigger( - type, - handler, - applicationId, - validationHandler -) { +export function addConnectTrigger(type, handler, applicationId, validationHandler) { add(Category.Triggers, `${type}.${ConnectClassName}`, handler, applicationId); - add( - Category.Validators, - `${type}.${ConnectClassName}`, - validationHandler, - applicationId - ); + add(Category.Validators, `${type}.${ConnectClassName}`, validationHandler, applicationId); } export function addLiveQueryEventHandler(handler, applicationId) { @@ -211,11 +172,7 @@ export function getFileTrigger(type, applicationId) { return getTrigger(FileClassName, type, applicationId); } -export function triggerExists( - className: string, - type: string, - applicationId: string -): boolean { +export function triggerExists(className: string, type: string, applicationId: string): boolean { return getTrigger(className, type, applicationId) != undefined; } @@ -225,9 +182,7 @@ export function getFunction(functionName, applicationId) { export function getFunctionNames(applicationId) { const store = - (_triggerStore[applicationId] && - _triggerStore[applicationId][Category.Functions]) || - {}; + (_triggerStore[applicationId] && _triggerStore[applicationId][Category.Functions]) || {}; const functionNames = []; const extractFunctionNames = (namespace, store) => { Object.keys(store).forEach(name => { @@ -308,15 +263,7 @@ export function getRequestObject( return request; } -export function getRequestQueryObject( - triggerType, - auth, - query, - count, - config, - context, - isGet -) { +export function getRequestQueryObject(triggerType, auth, query, count, config, context, isGet) { isGet = !!isGet; var request = { @@ -371,11 +318,7 @@ export function getResponseObject(request, resolve, reject) { ) { return resolve(response); } - if ( - response && - typeof response === 'object' && - request.triggerName === Types.afterSave - ) { + if (response && typeof response === 'object' && request.triggerName === Types.afterSave) { return resolve(response); } if (request.triggerName === Types.afterSave) { @@ -417,13 +360,7 @@ function logTriggerAfterHook(triggerType, className, input, auth) { ); } -function logTriggerSuccessBeforeHook( - triggerType, - className, - input, - result, - auth -) { +function logTriggerSuccessBeforeHook(triggerType, className, input, result, auth) { const cleanInput = logger.truncateLogMessage(JSON.stringify(input)); const cleanResult = logger.truncateLogMessage(JSON.stringify(result)); logger.info( @@ -453,14 +390,7 @@ function logTriggerErrorBeforeHook(triggerType, className, input, auth, error) { ); } -export function maybeRunAfterFindTrigger( - triggerType, - auth, - className, - objects, - config, - query -) { +export function maybeRunAfterFindTrigger(triggerType, auth, className, objects, config, query) { return new Promise((resolve, reject) => { const trigger = getTrigger(className, triggerType, config.applicationId); if (!trigger) { @@ -479,13 +409,7 @@ export function maybeRunAfterFindTrigger( reject(error); } ); - logTriggerSuccessBeforeHook( - triggerType, - className, - 'AfterFind', - JSON.stringify(objects), - auth - ); + logTriggerSuccessBeforeHook(triggerType, className, 'AfterFind', JSON.stringify(objects), auth); request.objects = objects.map(object => { //setting the class name to transform into parse object object.className = className; @@ -608,13 +532,11 @@ export function maybeRunQueryTrigger( } if (requestObject.includeReadPreference) { restOptions = restOptions || {}; - restOptions.includeReadPreference = - requestObject.includeReadPreference; + restOptions.includeReadPreference = requestObject.includeReadPreference; } if (requestObject.subqueryReadPreference) { restOptions = restOptions || {}; - restOptions.subqueryReadPreference = - requestObject.subqueryReadPreference; + restOptions.subqueryReadPreference = requestObject.subqueryReadPreference; } return { restWhere, @@ -733,10 +655,7 @@ function builtInTriggerValidator(options, request) { if (!opts.includes(val)) { throw ( - opt.error || - `Validation failed. Invalid option for ${key}. Expected: ${opts.join( - ', ' - )}` + opt.error || `Validation failed. Invalid option for ${key}. Expected: ${opts.join(', ')}` ); } }; @@ -826,11 +745,7 @@ export function maybeRunTrigger( return Promise.resolve({}); } return new Promise(function (resolve, reject) { - var trigger = getTrigger( - parseObject.className, - triggerType, - config.applicationId - ); + var trigger = getTrigger(parseObject.className, triggerType, config.applicationId); if (!trigger) return resolve(); var request = getRequestObject( triggerType, @@ -879,10 +794,7 @@ export function maybeRunTrigger( // to the RestWrite.execute() call. return Promise.resolve() .then(() => { - return maybeRunValidator( - request, - `${triggerType}.${parseObject.className}` - ); + return maybeRunValidator(request, `${triggerType}.${parseObject.className}`); }) .then(() => { const promise = trigger(request); @@ -891,12 +803,7 @@ export function maybeRunTrigger( triggerType === Types.afterDelete || triggerType === Types.afterLogin ) { - logTriggerAfterHook( - triggerType, - parseObject.className, - parseObject.toJSON(), - auth - ); + logTriggerAfterHook(triggerType, parseObject.className, parseObject.toJSON(), auth); } // beforeSave is expected to return null (nothing) if (triggerType === Types.beforeSave) { @@ -928,15 +835,8 @@ export function inflate(data, restObject) { return Parse.Object.fromJSON(copy); } -export function runLiveQueryEventHandlers( - data, - applicationId = Parse.applicationId -) { - if ( - !_triggerStore || - !_triggerStore[applicationId] || - !_triggerStore[applicationId].LiveQuery - ) { +export function runLiveQueryEventHandlers(data, applicationId = Parse.applicationId) { + if (!_triggerStore || !_triggerStore[applicationId] || !_triggerStore[applicationId].LiveQuery) { return; } _triggerStore[applicationId].LiveQuery.forEach(handler => handler(data)); @@ -967,21 +867,11 @@ export function getRequestFileObject(triggerType, auth, fileObject, config) { return request; } -export async function maybeRunFileTrigger( - triggerType, - fileObject, - config, - auth -) { +export async function maybeRunFileTrigger(triggerType, fileObject, config, auth) { const fileTrigger = getFileTrigger(triggerType, config.applicationId); if (typeof fileTrigger === 'function') { try { - const request = getRequestFileObject( - triggerType, - auth, - fileObject, - config - ); + const request = getRequestFileObject(triggerType, auth, fileObject, config); await maybeRunValidator(request, `${triggerType}.${FileClassName}`); const result = await fileTrigger(request); logTriggerSuccessBeforeHook( @@ -1007,11 +897,7 @@ export async function maybeRunFileTrigger( } export async function maybeRunConnectTrigger(triggerType, request) { - const trigger = getTrigger( - ConnectClassName, - triggerType, - Parse.applicationId - ); + const trigger = getTrigger(ConnectClassName, triggerType, Parse.applicationId); if (!trigger) { return; } @@ -1020,11 +906,7 @@ export async function maybeRunConnectTrigger(triggerType, request) { return trigger(request); } -export async function maybeRunSubscribeTrigger( - triggerType, - className, - request -) { +export async function maybeRunSubscribeTrigger(triggerType, className, request) { const trigger = getTrigger(className, triggerType, Parse.applicationId); if (!trigger) { return; @@ -1042,11 +924,7 @@ export async function maybeRunSubscribeTrigger( request.query = query; } -export async function maybeRunAfterEventTrigger( - triggerType, - className, - request -) { +export async function maybeRunAfterEventTrigger(triggerType, className, request) { const trigger = getTrigger(className, triggerType, Parse.applicationId); if (!trigger) { return; diff --git a/src/vendor/mongodbUrl.js b/src/vendor/mongodbUrl.js index b6920b89..76172930 100644 --- a/src/vendor/mongodbUrl.js +++ b/src/vendor/mongodbUrl.js @@ -191,18 +191,14 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || /^\/\/[^@\/]+@[^@\/]+/.test(rest)) { - var slashes = - rest.charCodeAt(0) === 47 /*/*/ && rest.charCodeAt(1) === 47; /*/*/ + var slashes = rest.charCodeAt(0) === 47 /*/*/ && rest.charCodeAt(1) === 47; /*/*/ if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.slice(2); this.slashes = true; } } - if ( - !hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto])) - ) { + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // @@ -283,8 +279,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = - hostname.charCodeAt(0) === 91 /*[*/ && - hostname.charCodeAt(hostname.length - 1) === 93; /*]*/ + hostname.charCodeAt(0) === 91 /*[*/ && hostname.charCodeAt(hostname.length - 1) === 93; /*]*/ // validate a little. if (!ipv6Hostname) { @@ -358,9 +353,7 @@ Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { } var firstIdx = - questionIdx !== -1 && (hashIdx === -1 || questionIdx < hashIdx) - ? questionIdx - : hashIdx; + questionIdx !== -1 && (hashIdx === -1 || questionIdx < hashIdx) ? questionIdx : hashIdx; if (firstIdx === -1) { if (rest.length > 0) this.pathname = rest; } else if (firstIdx > 0) { @@ -513,9 +506,7 @@ function urlFormat(obj) { if (typeof obj === 'string') obj = urlParse(obj); else if (typeof obj !== 'object' || obj === null) throw new TypeError( - 'Parameter "urlObj" must be an object, not ' + obj === null - ? 'null' - : typeof obj + 'Parameter "urlObj" must be an object, not ' + obj === null ? 'null' : typeof obj ); else if (!(obj instanceof Url)) return Url.prototype.format.call(obj); @@ -539,11 +530,7 @@ Url.prototype.format = function () { if (this.host) { host = auth + this.host; } else if (this.hostname) { - host = - auth + - (this.hostname.indexOf(':') === -1 - ? this.hostname - : '[' + this.hostname + ']'); + host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } @@ -554,8 +541,7 @@ Url.prototype.format = function () { var search = this.search || (query && '?' + query) || ''; - if (protocol && protocol.charCodeAt(protocol.length - 1) !== 58 /*:*/) - protocol += ':'; + if (protocol && protocol.charCodeAt(protocol.length - 1) !== 58 /*:*/) protocol += ':'; var newPathname = ''; var lastPos = 0; @@ -574,20 +560,15 @@ Url.prototype.format = function () { } } if (lastPos > 0) { - if (lastPos !== pathname.length) - pathname = newPathname + pathname.slice(lastPos); + if (lastPos !== pathname.length) pathname = newPathname + pathname.slice(lastPos); else pathname = newPathname; } // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. - if ( - this.slashes || - ((!protocol || slashedProtocol[protocol]) && host !== false) - ) { + if (this.slashes || ((!protocol || slashedProtocol[protocol]) && host !== false)) { host = '//' + (host || ''); - if (pathname && pathname.charCodeAt(0) !== 47 /*/*/) - pathname = '/' + pathname; + if (pathname && pathname.charCodeAt(0) !== 47 /*/*/) pathname = '/' + pathname; } else if (!host) { host = ''; } @@ -651,11 +632,7 @@ Url.prototype.resolveObject = function (relative) { } //urlParse appends trailing / to urls like http://www.example.com - if ( - slashedProtocol[result.protocol] && - result.hostname && - !result.pathname - ) { + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } @@ -716,10 +693,8 @@ Url.prototype.resolveObject = function (relative) { } var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/'; - var isRelAbs = - relative.host || (relative.pathname && relative.pathname.charAt(0) === '/'); - var mustEndAbs = - isRelAbs || isSourceAbs || (result.host && relative.pathname); + var isRelAbs = relative.host || (relative.pathname && relative.pathname.charAt(0) === '/'); + var mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname); var removeAllDots = mustEndAbs; var srcPath = (result.pathname && result.pathname.split('/')) || []; var relPath = (relative.pathname && relative.pathname.split('/')) || []; @@ -752,12 +727,9 @@ Url.prototype.resolveObject = function (relative) { if (isRelAbs) { // it's absolute. - result.host = - relative.host || relative.host === '' ? relative.host : result.host; + result.host = relative.host || relative.host === '' ? relative.host : result.host; result.hostname = - relative.hostname || relative.hostname === '' - ? relative.hostname - : result.hostname; + relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; @@ -780,9 +752,7 @@ Url.prototype.resolveObject = function (relative) { //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') const authInHost = - result.host && result.host.indexOf('@') > 0 - ? result.host.split('@') - : false; + result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); @@ -792,9 +762,7 @@ Url.prototype.resolveObject = function (relative) { result.query = relative.query; //to support http.request if (result.pathname !== null || result.search !== null) { - result.path = - (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; @@ -819,8 +787,7 @@ Url.prototype.resolveObject = function (relative) { // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = - ((result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..')) || + ((result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..')) || last === ''; // strip single dots, resolve double dots to parent dir @@ -846,11 +813,7 @@ Url.prototype.resolveObject = function (relative) { } } - if ( - mustEndAbs && - srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/') - ) { + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } @@ -858,8 +821,7 @@ Url.prototype.resolveObject = function (relative) { srcPath.push(''); } - var isAbsolute = - srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { @@ -871,10 +833,7 @@ Url.prototype.resolveObject = function (relative) { //occasionally the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - const authInHost = - result.host && result.host.indexOf('@') > 0 - ? result.host.split('@') - : false; + const authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); @@ -896,9 +855,7 @@ Url.prototype.resolveObject = function (relative) { //to support request.http if (result.pathname !== null || result.search !== null) { - result.path = - (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; @@ -923,8 +880,7 @@ Url.prototype.parseHost = function () { // About 1.5x faster than the two-arg version of Array#splice(). /* istanbul ignore next: improve coverage */ function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) - list[i] = list[k]; + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) list[i] = list[k]; list.pop(); }