From ca286b7108197034a3ff02063a259ff12181a329 Mon Sep 17 00:00:00 2001 From: Arthur Cinader Date: Wed, 7 Dec 2016 15:17:05 -0800 Subject: [PATCH] Enable prefer-const lint rule (#3202) --- .eslintrc.json | 3 +- spec/Analytics.spec.js | 4 +- spec/AuthenticationAdapters.spec.js | 18 +- spec/CLI.spec.js | 12 +- spec/ClientSDK.spec.js | 2 +- spec/CloudCode.spec.js | 116 ++++++------ spec/CloudCodeLogger.spec.js | 18 +- spec/EmailVerificationToken.spec.js | 16 +- spec/HTTPRequest.spec.js | 50 ++--- spec/Logger.spec.js | 8 +- spec/MockEmailAdapterWithOptions.js | 2 +- spec/MongoStorageAdapter.spec.js | 46 ++--- spec/MongoTransform.spec.js | 10 +- spec/Parse.Push.spec.js | 4 +- spec/ParseAPI.spec.js | 178 +++++++++--------- spec/ParseFile.spec.js | 4 +- spec/ParseGlobalConfig.spec.js | 8 +- spec/ParseHooks.spec.js | 2 +- spec/ParseInstallation.spec.js | 56 +++--- spec/ParseLiveQueryServer.spec.js | 2 +- spec/ParseObject.spec.js | 52 ++--- spec/ParsePubSub.spec.js | 4 +- spec/ParseQuery.spec.js | 92 ++++----- spec/ParseRelation.spec.js | 94 ++++----- spec/ParseRole.spec.js | 18 +- spec/ParseServerRESTController.spec.js | 6 +- spec/ParseUser.spec.js | 60 +++--- spec/PointerPermissions.spec.js | 154 +++++++-------- spec/PushController.spec.js | 34 ++-- spec/RestQuery.spec.js | 18 +- spec/RevocableSessionsUpgrade.spec.js | 4 +- spec/Schema.spec.js | 36 ++-- spec/TwitterAuth.spec.js | 2 +- spec/Uniqueness.spec.js | 30 +-- spec/ValidationAndPasswordsReset.spec.js | 24 +-- spec/WinstonLoggerAdapter.spec.js | 8 +- spec/batch.spec.js | 18 +- spec/helper.js | 10 +- spec/index.spec.js | 8 +- spec/rest.spec.js | 16 +- spec/schemas.spec.js | 100 +++++----- src/AccountLockout.js | 2 +- src/Adapters/Auth/index.js | 4 +- src/Adapters/Auth/twitter.js | 2 +- src/Adapters/Cache/InMemoryCache.js | 2 +- src/Adapters/Cache/InMemoryCacheAdapter.js | 2 +- src/Adapters/Files/GridStoreAdapter.js | 8 +- src/Adapters/Logger/WinstonLogger.js | 8 +- src/Adapters/Logger/WinstonLoggerAdapter.js | 10 +- src/Adapters/PubSub/EventEmitterPubSub.js | 6 +- src/Adapters/Storage/Mongo/MongoCollection.js | 8 +- .../Storage/Mongo/MongoSchemaCollection.js | 2 +- .../Storage/Mongo/MongoStorageAdapter.js | 22 +-- src/Adapters/Storage/Mongo/MongoTransform.js | 30 +-- .../Storage/Postgres/PostgresClient.js | 3 +- .../Postgres/PostgresStorageAdapter.js | 158 ++++++++-------- src/Auth.js | 14 +- src/ClientSDK.js | 8 +- src/Config.js | 2 +- src/Controllers/AdaptableController.js | 4 +- src/Controllers/CacheController.js | 12 +- src/Controllers/DatabaseController.js | 86 ++++----- src/Controllers/FilesController.js | 8 +- src/Controllers/HooksController.js | 4 +- src/Controllers/LiveQueryController.js | 6 +- src/Controllers/LoggerController.js | 12 +- src/Controllers/PushController.js | 16 +- src/Controllers/SchemaCache.js | 2 +- src/Controllers/SchemaController.js | 60 +++--- src/Controllers/UserController.js | 24 +-- src/LiveQuery/Client.js | 10 +- src/LiveQuery/ParseCloudCodePublisher.js | 2 +- src/LiveQuery/ParseLiveQueryServer.js | 100 +++++----- src/LiveQuery/ParsePubSub.js | 8 +- src/LiveQuery/ParseWebSocketServer.js | 10 +- src/LiveQuery/QueryTools.js | 4 +- src/LiveQuery/RequestSchema.js | 12 +- src/LiveQuery/SessionTokenCache.js | 4 +- src/LiveQuery/Subscription.js | 6 +- src/ParseServer.js | 8 +- src/ParseServerRESTController.js | 10 +- src/PromiseRouter.js | 20 +- src/RestQuery.js | 30 +-- src/RestWrite.js | 48 ++--- src/Routers/ClassesRouter.js | 20 +- src/Routers/CloudCodeRouter.js | 4 +- src/Routers/GlobalConfigRouter.js | 4 +- src/Routers/InstallationsRouter.js | 2 +- src/Routers/PublicAPIRouter.js | 32 ++-- src/Routers/PushRouter.js | 10 +- src/Routers/SchemasRouter.js | 4 +- src/Routers/UsersRouter.js | 24 +-- src/StatusHandler.js | 50 ++--- src/batch.js | 10 +- src/cli/parse-server.js | 4 +- src/cli/utils/commander.js | 6 +- src/cli/utils/runner.js | 4 +- src/cloud-code/HTTPResponse.js | 4 +- src/cloud-code/httpRequest.js | 2 +- src/cryptoUtils.js | 4 +- src/defaults.js | 6 +- src/index.js | 6 +- src/logger.js | 2 +- src/middlewares.js | 2 +- src/rest.js | 6 +- src/triggers.js | 16 +- 106 files changed, 1183 insertions(+), 1183 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 65dcb7db03..8c7060f739 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,6 +19,7 @@ "no-trailing-spaces": 2, "eol-last": 2, "space-in-parens": ["error", "never"], - "no-multiple-empty-lines": 1 + "no-multiple-empty-lines": 1, + "prefer-const": "error" } } diff --git a/spec/Analytics.spec.js b/spec/Analytics.spec.js index 4980826d09..a4e7d87acc 100644 --- a/spec/Analytics.spec.js +++ b/spec/Analytics.spec.js @@ -17,7 +17,7 @@ describe('AnalyticsController', () => { }).then(() => { expect(analyticsAdapter.trackEvent).toHaveBeenCalled(); var lastCall = analyticsAdapter.trackEvent.calls.first(); - let args = lastCall.args; + const args = lastCall.args; expect(args[0]).toEqual('MyEvent'); expect(args[1]).toEqual({ dimensions: { @@ -45,7 +45,7 @@ describe('AnalyticsController', () => { }).then(() => { expect(analyticsAdapter.appOpened).toHaveBeenCalled(); var lastCall = analyticsAdapter.appOpened.calls.first(); - let args = lastCall.args; + const args = lastCall.args; expect(args[0]).toEqual({ dimensions: { key: 'value', diff --git a/spec/AuthenticationAdapters.spec.js b/spec/AuthenticationAdapters.spec.js index c2f4a106f0..22af6ba26b 100644 --- a/spec/AuthenticationAdapters.spec.js +++ b/spec/AuthenticationAdapters.spec.js @@ -208,7 +208,7 @@ describe('AuthenticationProviers', function() { id: 'hello', token: 'world' } - let adapter = { + const adapter = { validateAppId: function() { return Promise.resolve(); }, @@ -220,15 +220,15 @@ describe('AuthenticationProviers', function() { } }; - let authDataSpy = spyOn(adapter, 'validateAuthData').and.callThrough(); - let appIdSpy = spyOn(adapter, 'validateAppId').and.callThrough(); + const authDataSpy = spyOn(adapter, 'validateAuthData').and.callThrough(); + const appIdSpy = spyOn(adapter, 'validateAppId').and.callThrough(); - let authenticationHandler = authenticationLoader({ + const authenticationHandler = authenticationLoader({ customAuthentication: adapter }); validateAuthenticationHandler(authenticationHandler); - let validator = authenticationHandler.getValidatorForProvider('customAuthentication'); + const validator = authenticationHandler.getValidatorForProvider('customAuthentication'); validateValidator(validator); validator(validAuthData).then(() => { @@ -243,12 +243,12 @@ describe('AuthenticationProviers', function() { }); it('properly loads custom adapter module object', (done) => { - let authenticationHandler = authenticationLoader({ + const authenticationHandler = authenticationLoader({ customAuthentication: path.resolve('./spec/support/CustomAuth.js') }); validateAuthenticationHandler(authenticationHandler); - let validator = authenticationHandler.getValidatorForProvider('customAuthentication'); + const validator = authenticationHandler.getValidatorForProvider('customAuthentication'); validateValidator(validator); validator({ @@ -262,12 +262,12 @@ describe('AuthenticationProviers', function() { }); it('properly loads custom adapter module object', (done) => { - let authenticationHandler = authenticationLoader({ + const authenticationHandler = authenticationLoader({ customAuthentication: { module: path.resolve('./spec/support/CustomAuthFunction.js'), options: { token: 'valid-token' }} }); validateAuthenticationHandler(authenticationHandler); - let validator = authenticationHandler.getValidatorForProvider('customAuthentication'); + const validator = authenticationHandler.getValidatorForProvider('customAuthentication'); validateValidator(validator); validator({ diff --git a/spec/CLI.spec.js b/spec/CLI.spec.js index c91a1f17dd..06312fc602 100644 --- a/spec/CLI.spec.js +++ b/spec/CLI.spec.js @@ -94,7 +94,7 @@ describe('commander additions', () => { 'PROGRAM_ARG_0': 'arg0ENVValue', 'PROGRAM_ARG_1': 'arg1ENVValue', }); - let options = commander.getOptions(); + const options = commander.getOptions(); expect(options.arg2).toBe(8888); expect(options.arg3).toBe('hello'); //config value expect(options.arg4).toBe('/1'); @@ -123,7 +123,7 @@ describe('commander additions', () => { it('should load config from apps', (done) => { commander.loadDefinitions(testDefinitions); commander.parse(['node', './CLI.spec.js', './spec/configs/CLIConfigApps.json']); - let options = commander.getOptions(); + const options = commander.getOptions(); expect(options.arg1).toBe('my_app'); expect(options.arg2).toBe(8888); expect(options.arg3).toBe('hello'); //config value @@ -142,8 +142,8 @@ describe('commander additions', () => { describe('definitions', () => { it('should have valid types', () => { - for (let key in definitions) { - let definition = definitions[key]; + for (const key in definitions) { + const definition = definitions[key]; expect(typeof definition).toBe('object'); if (typeof definition.env !== 'undefined') { expect(typeof definition.env).toBe('string'); @@ -161,8 +161,8 @@ describe('definitions', () => { describe('LiveQuery definitions', () => { it('should have valid types', () => { - for (let key in liveQueryDefinitions) { - let definition = liveQueryDefinitions[key]; + for (const key in liveQueryDefinitions) { + const definition = liveQueryDefinitions[key]; expect(typeof definition).toBe('object'); if (typeof definition.env !== 'undefined') { expect(typeof definition.env).toBe('string'); diff --git a/spec/ClientSDK.spec.js b/spec/ClientSDK.spec.js index 92e07a8dc0..985c1e86a1 100644 --- a/spec/ClientSDK.spec.js +++ b/spec/ClientSDK.spec.js @@ -2,7 +2,7 @@ var ClientSDK = require('../src/ClientSDK'); describe('ClientSDK', () => { it('should properly parse the SDK versions', () => { - let clientSDKFromVersion = ClientSDK.fromString; + const clientSDKFromVersion = ClientSDK.fromString; expect(clientSDKFromVersion('i1.1.1')).toEqual({ sdk: 'i', version: '1.1.1' diff --git a/spec/CloudCode.spec.js b/spec/CloudCode.spec.js index c840fe9e97..236f10a80b 100644 --- a/spec/CloudCode.spec.js +++ b/spec/CloudCode.spec.js @@ -180,10 +180,10 @@ describe('Cloud Code', () => { it('test afterSave ran on created object and returned a promise', function(done) { Parse.Cloud.afterSave('AfterSaveTest2', function(req) { - let obj = req.object; + const obj = req.object; if(!obj.existed()) { - let promise = new Parse.Promise(); + const promise = new Parse.Promise(); setTimeout(function(){ obj.set('proof', obj.id); obj.save().then(function(){ @@ -195,13 +195,13 @@ describe('Cloud Code', () => { } }); - let obj = new Parse.Object('AfterSaveTest2'); + const obj = new Parse.Object('AfterSaveTest2'); obj.save().then(function(){ - let query = new Parse.Query('AfterSaveTest2'); + const query = new Parse.Query('AfterSaveTest2'); query.equalTo('proof', obj.id); query.find().then(function(results) { expect(results.length).toEqual(1); - let savedObject = results[0]; + const savedObject = results[0]; expect(savedObject.get('proof')).toEqual(obj.id); done(); }, @@ -215,10 +215,10 @@ describe('Cloud Code', () => { // TODO: Fails on CI randomly as racing xit('test afterSave ignoring promise, object not found', function(done) { Parse.Cloud.afterSave('AfterSaveTest2', function(req) { - let obj = req.object; + const obj = req.object; if(!obj.existed()) { - let promise = new Parse.Promise(); + const promise = new Parse.Promise(); setTimeout(function(){ obj.set('proof', obj.id); obj.save().then(function(){ @@ -230,12 +230,12 @@ describe('Cloud Code', () => { } }); - let obj = new Parse.Object('AfterSaveTest2'); + const obj = new Parse.Object('AfterSaveTest2'); obj.save().then(function(){ done(); }) - let query = new Parse.Query('AfterSaveTest2'); + const query = new Parse.Query('AfterSaveTest2'); query.equalTo('proof', obj.id); query.find().then(function(results) { expect(results.length).toEqual(0); @@ -247,7 +247,7 @@ describe('Cloud Code', () => { it('test afterSave rejecting promise', function(done) { Parse.Cloud.afterSave('AfterSaveTest2', function() { - let promise = new Parse.Promise(); + const promise = new Parse.Promise(); setTimeout(function(){ promise.reject("THIS SHOULD BE IGNORED"); }, 1000); @@ -255,7 +255,7 @@ describe('Cloud Code', () => { return promise; }); - let obj = new Parse.Object('AfterSaveTest2'); + const obj = new Parse.Object('AfterSaveTest2'); obj.save().then(function(){ done(); }, function(error){ @@ -266,10 +266,10 @@ describe('Cloud Code', () => { it('test afterDelete returning promise, object is deleted when destroy resolves', function(done) { Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) { - let promise = new Parse.Promise(); + const promise = new Parse.Promise(); setTimeout(function(){ - let obj = new Parse.Object('AfterDeleteTestProof'); + const obj = new Parse.Object('AfterDeleteTestProof'); obj.set('proof', req.object.id); obj.save().then(function(){ promise.resolve(); @@ -280,19 +280,19 @@ describe('Cloud Code', () => { return promise; }); - let errorHandler = function(error) { + const errorHandler = function(error) { fail(error); done(); } - let obj = new Parse.Object('AfterDeleteTest2'); + const obj = new Parse.Object('AfterDeleteTest2'); obj.save().then(function(){ obj.destroy().then(function(){ - let query = new Parse.Query('AfterDeleteTestProof'); + const query = new Parse.Query('AfterDeleteTestProof'); query.equalTo('proof', obj.id); query.find().then(function(results) { expect(results.length).toEqual(1); - let deletedObject = results[0]; + const deletedObject = results[0]; expect(deletedObject.get('proof')).toEqual(obj.id); done(); }, errorHandler); @@ -302,10 +302,10 @@ describe('Cloud Code', () => { it('test afterDelete ignoring promise, object is not yet deleted', function(done) { Parse.Cloud.afterDelete('AfterDeleteTest2', function(req) { - let promise = new Parse.Promise(); + const promise = new Parse.Promise(); setTimeout(function(){ - let obj = new Parse.Object('AfterDeleteTestProof'); + const obj = new Parse.Object('AfterDeleteTestProof'); obj.set('proof', req.object.id); obj.save().then(function(){ promise.resolve(); @@ -316,18 +316,18 @@ describe('Cloud Code', () => { return promise; }); - let errorHandler = function(error) { + const errorHandler = function(error) { fail(error); done(); } - let obj = new Parse.Object('AfterDeleteTest2'); + const obj = new Parse.Object('AfterDeleteTest2'); obj.save().then(function(){ obj.destroy().then(function(){ done(); }) - let query = new Parse.Query('AfterDeleteTestProof'); + const query = new Parse.Query('AfterDeleteTestProof'); query.equalTo('proof', obj.id); query.find().then(function(results) { expect(results.length).toEqual(0); @@ -509,7 +509,7 @@ describe('Cloud Code', () => { return res.success({}); }); - let params = { + const params = { 'date': { '__type': 'Date', 'iso': '2016-05-22T09:00:00.000Z' @@ -616,7 +616,7 @@ describe('Cloud Code', () => { res.success(); }); - let obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('foo', 'bar'); obj.set('fooAgain', 'barAgain'); obj.save().then(() => { @@ -703,7 +703,7 @@ describe('Cloud Code', () => { request.object.set('foo', 'baz'); response.success(); }); - let obj = new Parse.Object('ChangingObject'); + const obj = new Parse.Object('ChangingObject'); obj.save({ foo: 'bar' }).then((objAgain) => { expect(objAgain.get('foo')).toEqual('baz'); done(); @@ -726,9 +726,9 @@ describe('Cloud Code', () => { expect(request.object.get('file')).toBeUndefined(); return Promise.resolve(); }); - let file = new Parse.File("yolo.txt", [1,2,3], "text/plain"); + const file = new Parse.File("yolo.txt", [1,2,3], "text/plain"); file.save().then(() => { - let obj = new Parse.Object('ChangingObject'); + const obj = new Parse.Object('ChangingObject'); return obj.save({ file, date: new Date() }) }).then(() => { done(); @@ -995,7 +995,7 @@ describe('Cloud Code', () => { }); let object; - let testObject = new TestObject({key: 'value'}); + const testObject = new TestObject({key: 'value'}); testObject.save().then(() => { object = new BeforeSaveObject(); return object.save().then(() => { @@ -1026,7 +1026,7 @@ describe('Cloud Code', () => { }, res.error); }); - let object = new BeforeSaveObject(); + const object = new BeforeSaveObject(); object.save().then((objectAgain) => { // Originally it would throw as it would be a non-relation expect(() => { objectAgain.relation('testsRelation') }).not.toThrow(); @@ -1194,7 +1194,7 @@ describe('Cloud Code', () => { }); function getJobStatus(jobId) { - let q = new Parse.Query('_JobStatus'); + const q = new Parse.Query('_JobStatus'); return q.get(jobId, {useMasterKey: true}); } }); @@ -1203,9 +1203,9 @@ describe('Cloud Code', () => { describe('beforeFind hooks', () => { it('should add beforeFind trigger', (done) => { Parse.Cloud.beforeFind('MyObject', (req) => { - let q = req.query; + const q = req.query; expect(q instanceof Parse.Query).toBe(true); - let jsonQuery = q.toJSON(); + const jsonQuery = q.toJSON(); expect(jsonQuery.where.key).toEqual('value'); expect(jsonQuery.where.some).toEqual({'$gt': 10}); expect(jsonQuery.include).toEqual('otherKey,otherValue'); @@ -1213,7 +1213,7 @@ describe('beforeFind hooks', () => { expect(jsonQuery.skip).toBe(undefined); }); - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.equalTo('key', 'value'); query.greaterThan('some', 10); query.include('otherKey'); @@ -1225,21 +1225,21 @@ describe('beforeFind hooks', () => { it('should use modify', (done) => { Parse.Cloud.beforeFind('MyObject', (req) => { - let q = req.query; + const q = req.query; q.equalTo('forced', true); }); - let obj0 = new Parse.Object('MyObject'); + const obj0 = new Parse.Object('MyObject'); obj0.set('forced', false); - let obj1 = new Parse.Object('MyObject'); + const obj1 = new Parse.Object('MyObject'); obj1.set('forced', true); Parse.Object.saveAll([obj0, obj1]).then(() => { - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.equalTo('forced', false); query.find().then((results) => { expect(results.length).toBe(1); - let firstResult = results[0]; + const firstResult = results[0]; expect(firstResult.get('forced')).toBe(true); done(); }); @@ -1248,19 +1248,19 @@ describe('beforeFind hooks', () => { it('should use the modified the query', (done) => { Parse.Cloud.beforeFind('MyObject', (req) => { - let q = req.query; - let otherQuery = new Parse.Query('MyObject'); + const q = req.query; + const otherQuery = new Parse.Query('MyObject'); otherQuery.equalTo('forced', true); return Parse.Query.or(q, otherQuery); }); - let obj0 = new Parse.Object('MyObject'); + const obj0 = new Parse.Object('MyObject'); obj0.set('forced', false); - let obj1 = new Parse.Object('MyObject'); + const obj1 = new Parse.Object('MyObject'); obj1.set('forced', true); Parse.Object.saveAll([obj0, obj1]).then(() => { - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.equalTo('forced', false); query.find().then((results) => { expect(results.length).toBe(2); @@ -1274,7 +1274,7 @@ describe('beforeFind hooks', () => { return Promise.reject('Do not run that query'); }); - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.find().then(() => { fail('should not succeed'); done(); @@ -1287,7 +1287,7 @@ describe('beforeFind hooks', () => { it('should handle empty where', (done) => { Parse.Cloud.beforeFind('MyObject', (req) => { - let otherQuery = new Parse.Query('MyObject'); + const otherQuery = new Parse.Query('MyObject'); otherQuery.equalTo('some', true); return Parse.Query.or(req.query, otherQuery); }); @@ -1315,10 +1315,10 @@ describe('afterFind hooks', () => { } res.success(req.objects); }); - let obj = new Parse.Object('MyObject'); + const obj = new Parse.Object('MyObject'); obj.set('secretField', 'SSID'); obj.save().then(function() { - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.get(obj.id).then(function(result) { expect(result.get('secretField')).toEqual('###'); done(); @@ -1339,10 +1339,10 @@ describe('afterFind hooks', () => { } res.success(req.objects); }); - let obj = new Parse.Object('MyObject'); + const obj = new Parse.Object('MyObject'); obj.set('secretField', 'SSID'); obj.save().then(function() { - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.equalTo('objectId',obj.id); query.find().then(function(results) { expect(results[0].get('secretField')).toEqual('###'); @@ -1359,7 +1359,7 @@ describe('afterFind hooks', () => { it('should filter out results',(done) => { Parse.Cloud.afterFind('MyObject', (req, res) => { - let filteredResults = []; + const filteredResults = []; for(let i = 0 ; i < req.objects.length ; i++){ if(req.objects[i].get("secretField")==="SSID1") { filteredResults.push(req.objects[i]); @@ -1367,12 +1367,12 @@ describe('afterFind hooks', () => { } res.success(filteredResults); }); - let obj0 = new Parse.Object('MyObject'); + const obj0 = new Parse.Object('MyObject'); obj0.set('secretField', 'SSID1'); - let obj1 = new Parse.Object('MyObject'); + const obj1 = new Parse.Object('MyObject'); obj1.set('secretField', 'SSID2'); Parse.Object.saveAll([obj0, obj1]).then(function() { - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.find().then(function(results) { expect(results[0].get('secretField')).toEqual('SSID1'); expect(results.length).toEqual(1); @@ -1391,10 +1391,10 @@ describe('afterFind hooks', () => { Parse.Cloud.afterFind('MyObject', (req, res) => { res.error(Parse.Error.SCRIPT_FAILED, "It should fail"); }); - let obj = new Parse.Object('MyObject'); + const obj = new Parse.Object('MyObject'); obj.set('secretField', 'SSID'); obj.save().then(function() { - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.equalTo('objectId',obj.id); query.find().then(function() { fail("AfterFind should handle response failure correctly"); @@ -1409,7 +1409,7 @@ describe('afterFind hooks', () => { it('should also work with promise',(done) => { Parse.Cloud.afterFind('MyObject', (req) => { - let promise = new Parse.Promise(); + const promise = new Parse.Promise(); setTimeout(function(){ for(let i = 0 ; i < req.objects.length ; i++){ req.objects[i].set("secretField","###"); @@ -1418,10 +1418,10 @@ describe('afterFind hooks', () => { }, 1000); return promise; }); - let obj = new Parse.Object('MyObject'); + const obj = new Parse.Object('MyObject'); obj.set('secretField', 'SSID'); obj.save().then(function() { - let query = new Parse.Query('MyObject'); + const query = new Parse.Query('MyObject'); query.equalTo('objectId',obj.id); query.find().then(function(results) { expect(results[0].get('secretField')).toEqual('###'); diff --git a/spec/CloudCodeLogger.spec.js b/spec/CloudCodeLogger.spec.js index 1a43e56782..0ded5e04ea 100644 --- a/spec/CloudCodeLogger.spec.js +++ b/spec/CloudCodeLogger.spec.js @@ -37,10 +37,10 @@ describe("Cloud Code Logger", () => { return logController.getLogs({ from: Date.now() - 500, size: 1000 }); }).then((res) => { expect(res.length).not.toBe(0); - let lastLogs = res.slice(0, 3); - let cloudFunctionMessage = lastLogs[0]; - let errorMessage = lastLogs[1]; - let infoMessage = lastLogs[2]; + const lastLogs = res.slice(0, 3); + const cloudFunctionMessage = lastLogs[0]; + const errorMessage = lastLogs[1]; + const infoMessage = lastLogs[2]; expect(cloudFunctionMessage.level).toBe('info'); expect(cloudFunctionMessage.params).toEqual({}); expect(cloudFunctionMessage.message).toMatch(/Ran cloud function loggerTest for user [^ ]* with:\n {2}Input: {}\n {2}Result: {}/); @@ -82,15 +82,15 @@ describe("Cloud Code Logger", () => { res.success({}); }); - let obj = new Parse.Object('MyObject'); + const obj = new Parse.Object('MyObject'); obj.save().then(() => { return logController.getLogs({ from: Date.now() - 500, size: 1000 }) }).then((res) => { expect(res.length).not.toBe(0); - let lastLogs = res.slice(0, 3); - let cloudTriggerMessage = lastLogs[0]; - let errorMessage = lastLogs[1]; - let infoMessage = lastLogs[2]; + const lastLogs = res.slice(0, 3); + const cloudTriggerMessage = lastLogs[0]; + const errorMessage = lastLogs[1]; + const infoMessage = lastLogs[2]; expect(cloudTriggerMessage.level).toBe('info'); expect(cloudTriggerMessage.triggerType).toEqual('beforeSave'); expect(cloudTriggerMessage.message).toMatch(/beforeSave triggered for MyObject for user [^ ]*\n {2}Input: {}\n {2}Result: {}/); diff --git a/spec/EmailVerificationToken.spec.js b/spec/EmailVerificationToken.spec.js index 9163aa92ea..8d01bc1157 100644 --- a/spec/EmailVerificationToken.spec.js +++ b/spec/EmailVerificationToken.spec.js @@ -241,12 +241,12 @@ describe("Email Verification Token Expiration: ", () => { return user.signUp(); }) .then(() => { - let config = new Config('test'); + const config = new Config('test'); return config.database.find('_User', {username: 'sets_email_verify_token_expires_at'}); }) .then(results => { expect(results.length).toBe(1); - let user = results[0]; + const user = results[0]; expect(typeof user).toBe('object'); expect(user.emailVerified).toEqual(false); expect(typeof user._email_verify_token).toBe('string'); @@ -288,7 +288,7 @@ describe("Email Verification Token Expiration: ", () => { followRedirect: false, }, (error, response) => { expect(response.statusCode).toEqual(302); - let config = new Config('test'); + const config = new Config('test'); return config.database.find('_User', {username: 'unsets_email_verify_token_expires_at'}).then((results) => { expect(results.length).toBe(1); return results[0]; @@ -420,18 +420,18 @@ describe("Email Verification Token Expiration: ", () => { it('setting the email on the user should set a new email verification token and new expiration date for the token when expire email verify token flag is set', done => { - let user = new Parse.User(); + const user = new Parse.User(); let userBeforeEmailReset; let sendEmailOptions; - let emailAdapter = { + const emailAdapter = { sendVerificationEmail: options => { sendEmailOptions = options; }, sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => {} }; - let serverConfig = { + const serverConfig = { appName: 'emailVerifyToken', verifyUserEmails: true, emailAdapter: emailAdapter, @@ -447,7 +447,7 @@ describe("Email Verification Token Expiration: ", () => { return user.signUp(); }) .then(() => { - let config = new Config('test'); + const config = new Config('test'); return config.database.find('_User', {username: 'newEmailVerifyTokenOnEmailReset'}).then((results) => { return results[0]; }); @@ -464,7 +464,7 @@ describe("Email Verification Token Expiration: ", () => { }); }) .then(() => { - let config = new Config('test'); + const config = new Config('test'); return config.database.find('_User', {username: 'newEmailVerifyTokenOnEmailReset'}).then((results) => { return results[0]; }); diff --git a/spec/HTTPRequest.spec.js b/spec/HTTPRequest.spec.js index e9a2506a9a..4bf88c517a 100644 --- a/spec/HTTPRequest.spec.js +++ b/spec/HTTPRequest.spec.js @@ -162,10 +162,10 @@ describe("httpRequest", () => { }); it("should encode a query string body by default", (done) => { - let options = { + const options = { body: {"foo": "bar"}, } - let result = httpRequest.encodeBody(options); + const result = httpRequest.encodeBody(options); expect(result.body).toEqual('foo=bar'); expect(result.headers['Content-Type']).toEqual('application/x-www-form-urlencoded'); done(); @@ -173,30 +173,30 @@ describe("httpRequest", () => { }) it("should encode a JSON body", (done) => { - let options = { + const options = { body: {"foo": "bar"}, headers: {'Content-Type': 'application/json'} } - let result = httpRequest.encodeBody(options); + const result = httpRequest.encodeBody(options); expect(result.body).toEqual('{"foo":"bar"}'); done(); }) it("should encode a www-form body", (done) => { - let options = { + const options = { body: {"foo": "bar", "bar": "baz"}, headers: {'cOntent-tYpe': 'application/x-www-form-urlencoded'} } - let result = httpRequest.encodeBody(options); + const result = httpRequest.encodeBody(options); expect(result.body).toEqual("foo=bar&bar=baz"); done(); }); it("should not encode a wrong content type", (done) => { - let options = { + const options = { body:{"foo": "bar", "bar": "baz"}, headers: {'cOntent-tYpe': 'mime/jpeg'} } - let result = httpRequest.encodeBody(options); + const result = httpRequest.encodeBody(options); expect(result.body).toEqual({"foo": "bar", "bar": "baz"}); done(); }); @@ -247,7 +247,7 @@ describe("httpRequest", () => { }); it('should not crash with undefined body', () => { - let httpResponse = new HTTPResponse({}); + const httpResponse = new HTTPResponse({}); expect(httpResponse.body).toBeUndefined(); expect(httpResponse.data).toBeUndefined(); expect(httpResponse.text).toBeUndefined(); @@ -255,23 +255,23 @@ describe("httpRequest", () => { }); it('serialized httpResponse correctly with body string', () => { - let httpResponse = new HTTPResponse({}, 'hello'); + const httpResponse = new HTTPResponse({}, 'hello'); expect(httpResponse.text).toBe('hello'); expect(httpResponse.data).toBe(undefined); expect(httpResponse.body).toBe('hello'); - let serialized = JSON.stringify(httpResponse); - let result = JSON.parse(serialized); + const serialized = JSON.stringify(httpResponse); + const result = JSON.parse(serialized); expect(result.text).toBe('hello'); expect(result.data).toBe(undefined); expect(result.body).toBe(undefined); }); it('serialized httpResponse correctly with body object', () => { - let httpResponse = new HTTPResponse({}, {foo: "bar"}); + const httpResponse = new HTTPResponse({}, {foo: "bar"}); Parse._encode(httpResponse); - let serialized = JSON.stringify(httpResponse); - let result = JSON.parse(serialized); + const serialized = JSON.stringify(httpResponse); + const result = JSON.parse(serialized); expect(httpResponse.text).toEqual('{"foo":"bar"}'); expect(httpResponse.data).toEqual({foo: 'bar'}); @@ -283,29 +283,29 @@ describe("httpRequest", () => { }); it('serialized httpResponse correctly with body buffer string', () => { - let httpResponse = new HTTPResponse({}, new Buffer('hello')); + const httpResponse = new HTTPResponse({}, new Buffer('hello')); expect(httpResponse.text).toBe('hello'); expect(httpResponse.data).toBe(undefined); - let serialized = JSON.stringify(httpResponse); - let result = JSON.parse(serialized); + const serialized = JSON.stringify(httpResponse); + const result = JSON.parse(serialized); expect(result.text).toBe('hello'); expect(result.data).toBe(undefined); }); it('serialized httpResponse correctly with body buffer JSON Object', () => { - let json = '{"foo":"bar"}'; - let httpResponse = new HTTPResponse({}, new Buffer(json)); - let serialized = JSON.stringify(httpResponse); - let result = JSON.parse(serialized); + const json = '{"foo":"bar"}'; + const httpResponse = new HTTPResponse({}, new Buffer(json)); + const serialized = JSON.stringify(httpResponse); + const result = JSON.parse(serialized); expect(result.text).toEqual('{"foo":"bar"}'); expect(result.data).toEqual({foo: 'bar'}); }); it('serialized httpResponse with Parse._encode should be allright', () => { - let json = '{"foo":"bar"}'; - let httpResponse = new HTTPResponse({}, new Buffer(json)); - let encoded = Parse._encode(httpResponse); + const json = '{"foo":"bar"}'; + const httpResponse = new HTTPResponse({}, new Buffer(json)); + const encoded = Parse._encode(httpResponse); let foundData, foundText, foundBody = false; for(var key in encoded) { if (key == 'data') { diff --git a/spec/Logger.spec.js b/spec/Logger.spec.js index 2629f0a8ef..8a869ec245 100644 --- a/spec/Logger.spec.js +++ b/spec/Logger.spec.js @@ -23,8 +23,8 @@ describe('Logger', () => { it('should have files transports', (done) => { reconfigureServer().then(() => { - let transports = logging.logger.transports; - let transportKeys = Object.keys(transports); + const transports = logging.logger.transports; + const transportKeys = Object.keys(transports); expect(transportKeys.length).toBe(3); done(); }); @@ -34,8 +34,8 @@ describe('Logger', () => { reconfigureServer({ logsFolder: null }).then(() => { - let transports = logging.logger.transports; - let transportKeys = Object.keys(transports); + const transports = logging.logger.transports; + const transportKeys = Object.keys(transports); expect(transportKeys.length).toBe(1); done(); }); diff --git a/spec/MockEmailAdapterWithOptions.js b/spec/MockEmailAdapterWithOptions.js index a695144e60..5de84d0521 100644 --- a/spec/MockEmailAdapterWithOptions.js +++ b/spec/MockEmailAdapterWithOptions.js @@ -2,7 +2,7 @@ module.exports = options => { if (!options) { throw "Options were not provided" } - let adapter = { + const adapter = { sendVerificationEmail: () => Promise.resolve(), sendPasswordResetEmail: () => Promise.resolve(), sendMail: () => Promise.resolve() diff --git a/spec/MongoStorageAdapter.spec.js b/spec/MongoStorageAdapter.spec.js index 86d15e2686..2b5add7908 100644 --- a/spec/MongoStorageAdapter.spec.js +++ b/spec/MongoStorageAdapter.spec.js @@ -48,7 +48,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); it('stores objectId in _id', done => { - let adapter = new MongoStorageAdapter({ uri: databaseURI }); + const adapter = new MongoStorageAdapter({ uri: databaseURI }); adapter.createObject('Foo', { fields: {} }, { objectId: 'abcde' }) .then(() => adapter._rawFind('Foo', {})) .then(results => { @@ -62,7 +62,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { it('find succeeds when query is within maxTimeMS', (done) => { const maxTimeMS = 250; - let adapter = new MongoStorageAdapter({ + const adapter = new MongoStorageAdapter({ uri: databaseURI, mongoOptions: { maxTimeMS }, }); @@ -78,7 +78,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { it('find fails when query exceeds maxTimeMS', (done) => { const maxTimeMS = 250; - let adapter = new MongoStorageAdapter({ + const adapter = new MongoStorageAdapter({ uri: databaseURI, mongoOptions: { maxTimeMS }, }); @@ -98,7 +98,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); it('stores pointers with a _p_ prefix', (done) => { - let obj = { + const obj = { objectId: 'bar', aPointer: { __type: 'Pointer', @@ -106,7 +106,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { objectId: 'qwerty' } }; - let adapter = new MongoStorageAdapter({ uri: databaseURI }); + const adapter = new MongoStorageAdapter({ uri: databaseURI }); adapter.createObject('APointerDarkly', { fields: { objectId: { type: 'String' }, aPointer: { type: 'Pointer', targetClass: 'JustThePointer' }, @@ -114,7 +114,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { .then(() => adapter._rawFind('APointerDarkly', {})) .then(results => { expect(results.length).toEqual(1); - let output = results[0]; + const output = results[0]; expect(typeof output._id).toEqual('string'); expect(typeof output._p_aPointer).toEqual('string'); expect(output._p_aPointer).toEqual('JustThePointer$qwerty'); @@ -124,24 +124,24 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); it('handles object and subdocument', done => { - let adapter = new MongoStorageAdapter({ uri: databaseURI }); - let schema = { fields : { subdoc: { type: 'Object' } } }; - let obj = { subdoc: {foo: 'bar', wu: 'tan'} }; + const adapter = new MongoStorageAdapter({ uri: databaseURI }); + const schema = { fields : { subdoc: { type: 'Object' } } }; + const obj = { subdoc: {foo: 'bar', wu: 'tan'} }; adapter.createObject('MyClass', schema, obj) .then(() => adapter._rawFind('MyClass', {})) .then(results => { expect(results.length).toEqual(1); - let mob = results[0]; + const mob = results[0]; expect(typeof mob.subdoc).toBe('object'); expect(mob.subdoc.foo).toBe('bar'); expect(mob.subdoc.wu).toBe('tan'); - let obj = { 'subdoc.wu': 'clan' }; + const obj = { 'subdoc.wu': 'clan' }; return adapter.findOneAndUpdate('MyClass', schema, {}, obj); }) .then(() => adapter._rawFind('MyClass', {})) .then(results => { expect(results.length).toEqual(1); - let mob = results[0]; + const mob = results[0]; expect(typeof mob.subdoc).toBe('object'); expect(mob.subdoc.foo).toBe('bar'); expect(mob.subdoc.wu).toBe('clan'); @@ -150,8 +150,8 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); it('handles creating an array, object, date', (done) => { - let adapter = new MongoStorageAdapter({ uri: databaseURI }); - let obj = { + const adapter = new MongoStorageAdapter({ uri: databaseURI }); + const obj = { array: [1, 2, 3], object: {foo: 'bar'}, date: { @@ -159,7 +159,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { iso: '2016-05-26T20:55:01.154Z', }, }; - let schema = { fields: { + const schema = { fields: { array: { type: 'Array' }, object: { type: 'Object' }, date: { type: 'Date' }, @@ -168,7 +168,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { .then(() => adapter._rawFind('MyClass', {})) .then(results => { expect(results.length).toEqual(1); - let mob = results[0]; + const mob = results[0]; expect(mob.array instanceof Array).toBe(true); expect(typeof mob.object).toBe('object'); expect(mob.date instanceof Date).toBe(true); @@ -176,7 +176,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }) .then(results => { expect(results.length).toEqual(1); - let mob = results[0]; + const mob = results[0]; expect(mob.array instanceof Array).toBe(true); expect(typeof mob.object).toBe('object'); expect(mob.date.__type).toBe('Date'); @@ -191,9 +191,9 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }); it("handles updating a single object with array, object date", (done) => { - let adapter = new MongoStorageAdapter({ uri: databaseURI }); + const adapter = new MongoStorageAdapter({ uri: databaseURI }); - let schema = { fields: { + const schema = { fields: { array: { type: 'Array' }, object: { type: 'Object' }, date: { type: 'Date' }, @@ -204,7 +204,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { .then(() => adapter._rawFind('MyClass', {})) .then(results => { expect(results.length).toEqual(1); - let update = { + const update = { array: [1, 2, 3], object: {foo: 'bar'}, date: { @@ -212,11 +212,11 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { iso: '2016-05-26T20:55:01.154Z', }, }; - let query = {}; + const query = {}; return adapter.findOneAndUpdate('MyClass', schema, query, update) }) .then(results => { - let mob = results; + const mob = results; expect(mob.array instanceof Array).toBe(true); expect(typeof mob.object).toBe('object'); expect(mob.date.__type).toBe('Date'); @@ -225,7 +225,7 @@ describe_only_db('mongo')('MongoStorageAdapter', () => { }) .then(results => { expect(results.length).toEqual(1); - let mob = results[0]; + const mob = results[0]; expect(mob.array instanceof Array).toBe(true); expect(typeof mob.object).toBe('object'); expect(mob.date instanceof Date).toBe(true); diff --git a/spec/MongoTransform.spec.js b/spec/MongoTransform.spec.js index 00a8ba31dd..f0bb6ec4d9 100644 --- a/spec/MongoTransform.spec.js +++ b/spec/MongoTransform.spec.js @@ -1,9 +1,9 @@ // These tests are unit tests designed to only test transform.js. "use strict"; -let transform = require('../src/Adapters/Storage/Mongo/MongoTransform'); -let dd = require('deep-diff'); -let mongodb = require('mongodb'); +const transform = require('../src/Adapters/Storage/Mongo/MongoTransform'); +const dd = require('deep-diff'); +const mongodb = require('mongodb'); describe('parseObjectToMongoObjectForCreate', () => { it('a basic number', (done) => { @@ -179,7 +179,7 @@ describe('parseObjectToMongoObjectForCreate', () => { }); it('untransforms objects containing nested special keys', done => { - let input = {array: [{ + const input = {array: [{ _id: "Test ID", _hashed_password: "I Don't know why you would name a key this, but if you do it should work", _tombstone: { @@ -190,7 +190,7 @@ describe('parseObjectToMongoObjectForCreate', () => { }, regularKey: "some data", }]} - let output = transform.mongoObjectToParseObject(null, input, { + const output = transform.mongoObjectToParseObject(null, input, { fields: { array: { type: 'Array' }}, }); expect(dd(output, input)).toEqual(undefined); diff --git a/spec/Parse.Push.spec.js b/spec/Parse.Push.spec.js index 8e6321b3d0..b9ead0b544 100644 --- a/spec/Parse.Push.spec.js +++ b/spec/Parse.Push.spec.js @@ -1,13 +1,13 @@ 'use strict'; -let request = require('request'); +const request = require('request'); describe('Parse.Push', () => { var setup = function() { var pushAdapter = { send: function(body, installations) { var badge = body.data.badge; - let promises = installations.map((installation) => { + const promises = installations.map((installation) => { if (installation.deviceType == "ios") { expect(installation.badge).toEqual(badge); expect(installation.originalBadge+1).toEqual(installation.badge); diff --git a/spec/ParseAPI.spec.js b/spec/ParseAPI.spec.js index 68692fa9a4..01a92a30de 100644 --- a/spec/ParseAPI.spec.js +++ b/spec/ParseAPI.spec.js @@ -5,7 +5,7 @@ var request = require('request'); const rp = require('request-promise'); const Parse = require("parse/node"); -let Config = require('../src/Config'); +const Config = require('../src/Config'); const SchemaController = require('../src/Controllers/SchemaController'); var TestUtils = require('../src/TestUtils'); @@ -23,7 +23,7 @@ describe_only_db('mongo')('miscellaneous', () => { obj.set('foo', 'bar'); return obj.save(); }).then(() => { - let config = new Config(appId); + const config = new Config(appId); return config.database.adapter.find('TestObject', { fields: {} }, {}, {}); }).then((results) => { expect(results.length).toEqual(1); @@ -83,7 +83,7 @@ describe('miscellaneous', function() { it('fail to create a duplicate username', done => { let numCreated = 0; let numFailed = 0; - let p1 = createTestUser(); + const p1 = createTestUser(); p1.then(() => { numCreated++; expect(numCreated).toEqual(1); @@ -93,7 +93,7 @@ describe('miscellaneous', function() { expect(numFailed).toEqual(1); expect(error.code).toEqual(Parse.Error.USERNAME_TAKEN); }); - let p2 = createTestUser(); + const p2 = createTestUser(); p2.then(() => { numCreated++; expect(numCreated).toEqual(1); @@ -114,11 +114,11 @@ describe('miscellaneous', function() { it('ensure that email is uniquely indexed', done => { let numFailed = 0; let numCreated = 0; - let user1 = new Parse.User(); + const user1 = new Parse.User(); user1.setPassword('asdf'); user1.setUsername('u1'); user1.setEmail('dupe@dupe.dupe'); - let p1 = user1.signUp(); + const p1 = user1.signUp(); p1.then(() => { numCreated++; expect(numCreated).toEqual(1); @@ -128,11 +128,11 @@ describe('miscellaneous', function() { expect(error.code).toEqual(Parse.Error.EMAIL_TAKEN); }); - let user2 = new Parse.User(); + const user2 = new Parse.User(); user2.setPassword('asdf'); user2.setUsername('u2'); user2.setEmail('dupe@dupe.dupe'); - let p2 = user2.signUp(); + const p2 = user2.signUp(); p2.then(() => { numCreated++; expect(numCreated).toEqual(1); @@ -151,7 +151,7 @@ describe('miscellaneous', function() { }); it('ensure that if people already have duplicate users, they can still sign up new users', done => { - let config = new Config('test'); + const config = new Config('test'); // Remove existing data to clear out unique index TestUtils.destroyAllDataPermanently() .then(() => config.database.adapter.createClass('_User', userSchema)) @@ -161,13 +161,13 @@ describe('miscellaneous', function() { .then(reconfigureServer) .catch(error => { expect(error.code).toEqual(Parse.Error.DUPLICATE_VALUE); - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword('asdf'); user.setUsername('zxcv'); return user.signUp().catch(fail); }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword('asdf'); user.setUsername('u'); return user.signUp() @@ -183,7 +183,7 @@ describe('miscellaneous', function() { }); it('ensure that if people already have duplicate emails, they can still sign up new users', done => { - let config = new Config('test'); + const config = new Config('test'); // Remove existing data to clear out unique index TestUtils.destroyAllDataPermanently() .then(() => config.database.adapter.createClass('_User', userSchema)) @@ -191,14 +191,14 @@ describe('miscellaneous', function() { .then(() => config.database.adapter.createObject('_User', userSchema, { objectId: 'y', email: 'a@b.c' })) .then(reconfigureServer) .catch(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword('asdf'); user.setUsername('qqq'); user.setEmail('unique@unique.unique'); return user.signUp().catch(fail); }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword('asdf'); user.setUsername('www'); user.setEmail('a@b.c'); @@ -211,11 +211,11 @@ describe('miscellaneous', function() { }); it('ensure that if you try to sign up a user with a unique username and email, but duplicates in some other field that has a uniqueness constraint, you get a regular duplicate value error', done => { - let config = new Config('test'); + const config = new Config('test'); config.database.adapter.addFieldIfNotExists('_User', 'randomField', { type: 'String' }) .then(() => config.database.adapter.ensureUniqueness('_User', userSchema, ['randomField'])) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword('asdf'); user.setUsername('1'); user.setEmail('1@b.c'); @@ -223,7 +223,7 @@ describe('miscellaneous', function() { return user.signUp() }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword('asdf'); user.setUsername('2'); user.setEmail('2@b.c'); @@ -374,7 +374,7 @@ describe('miscellaneous', function() { let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.beforeSave('GameScore', (req, res) => { - let object = req.object; + const object = req.object; expect(object instanceof Parse.Object).toBeTruthy(); expect(object.get('fooAgain')).toEqual('barAgain'); if (triggerTime == 0) { @@ -397,7 +397,7 @@ describe('miscellaneous', function() { res.success(); }); - let obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('foo', 'bar'); obj.set('fooAgain', 'barAgain'); obj.save().then(() => { @@ -417,13 +417,13 @@ describe('miscellaneous', function() { let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.beforeSave('GameScore', (req, res) => { - let object = req.object; + const object = req.object; object.set('foo', 'bar'); triggerTime++; res.success(object); }); - let obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('foo', 'baz'); obj.save().then(() => { expect(triggerTime).toBe(1); @@ -439,10 +439,10 @@ describe('miscellaneous', function() { let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.beforeSave('GameScore', (req, res) => { - let object = req.object; + const object = req.object; expect(object instanceof Parse.Object).toBeTruthy(); expect(object.get('fooAgain')).toEqual('barAgain'); - let originalObject = req.original; + const originalObject = req.original; if (triggerTime == 0) { // No id/createdAt/updatedAt expect(object.id).toBeUndefined(); @@ -472,7 +472,7 @@ describe('miscellaneous', function() { res.success(); }); - let obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.set('foo', 'bar'); obj.set('fooAgain', 'barAgain'); obj.save().then(() => { @@ -490,13 +490,13 @@ describe('miscellaneous', function() { }); it('pointer mutation properly saves object', done => { - let className = 'GameScore'; + const className = 'GameScore'; Parse.Cloud.beforeSave(className, (req, res) => { - let object = req.object; + const object = req.object; expect(object instanceof Parse.Object).toBeTruthy(); - let child = object.get('child'); + const child = object.get('child'); expect(child instanceof Parse.Object).toBeTruthy(); child.set('a', 'b'); child.save().then(() => { @@ -504,20 +504,20 @@ describe('miscellaneous', function() { }); }); - let obj = new Parse.Object(className); + const obj = new Parse.Object(className); obj.set('foo', 'bar'); - let child = new Parse.Object('Child'); + const child = new Parse.Object('Child'); child.save().then(() => { obj.set('child', child); return obj.save(); }).then(() => { - let query = new Parse.Query(className); + const query = new Parse.Query(className); query.include('child'); return query.get(obj.id).then(objAgain => { expect(objAgain.get('foo')).toEqual('bar'); - let childAgain = objAgain.get('child'); + const childAgain = objAgain.get('child'); expect(childAgain instanceof Parse.Object).toBeTruthy(); expect(childAgain.get('a')).toEqual('b'); @@ -703,9 +703,9 @@ describe('miscellaneous', function() { var triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.afterSave('GameScore', function(req, res) { - let object = req.object; + const object = req.object; expect(object instanceof Parse.Object).toBeTruthy(); - let originalObject = req.original; + const originalObject = req.original; if (triggerTime == 0) { // Create expect(object.get('yolo')).toEqual(1); @@ -740,13 +740,13 @@ describe('miscellaneous', function() { let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.beforeSave('GameScore', function(req, res) { - let object = req.object; + const object = req.object; if (triggerTime == 0) { - let acl = object.getACL(); + const acl = object.getACL(); expect(acl.getPublicReadAccess()).toBeTruthy(); expect(acl.getPublicWriteAccess()).toBeTruthy(); } else if (triggerTime == 1) { - let acl = object.getACL(); + const acl = object.getACL(); expect(acl.getPublicReadAccess()).toBeFalsy(); expect(acl.getPublicWriteAccess()).toBeTruthy(); } else { @@ -756,8 +756,8 @@ describe('miscellaneous', function() { res.success(); }); - let obj = new Parse.Object('GameScore'); - let acl = new Parse.ACL(); + const obj = new Parse.Object('GameScore'); + const acl = new Parse.ACL(); acl.setPublicReadAccess(true); acl.setPublicWriteAccess(true); obj.setACL(acl); @@ -779,13 +779,13 @@ describe('miscellaneous', function() { let triggerTime = 0; // Register a mock beforeSave hook Parse.Cloud.afterSave('GameScore', function(req, res) { - let object = req.object; + const object = req.object; if (triggerTime == 0) { - let acl = object.getACL(); + const acl = object.getACL(); expect(acl.getPublicReadAccess()).toBeTruthy(); expect(acl.getPublicWriteAccess()).toBeTruthy(); } else if (triggerTime == 1) { - let acl = object.getACL(); + const acl = object.getACL(); expect(acl.getPublicReadAccess()).toBeFalsy(); expect(acl.getPublicWriteAccess()).toBeTruthy(); } else { @@ -795,8 +795,8 @@ describe('miscellaneous', function() { res.success(); }); - let obj = new Parse.Object('GameScore'); - let acl = new Parse.ACL(); + const obj = new Parse.Object('GameScore'); + const acl = new Parse.ACL(); acl.setPublicReadAccess(true); acl.setPublicWriteAccess(true); obj.setACL(acl); @@ -815,7 +815,7 @@ describe('miscellaneous', function() { }); it('should return the updated fields on PUT', done => { - let obj = new Parse.Object('GameScore'); + const obj = new Parse.Object('GameScore'); obj.save({a:'hello', c: 1, d: ['1'], e:['1'], f:['1','2']}).then(() => { var headers = { 'Content-Type': 'application/json', @@ -1037,7 +1037,7 @@ describe('miscellaneous', function() { }); it('can handle date params in cloud functions (#2214)', done => { - let date = new Date(); + const date = new Date(); Parse.Cloud.define('dateFunc', (request, response) => { expect(request.params.date.__type).toEqual('Date'); expect(request.params.date.iso).toEqual(date.toISOString()); @@ -1133,27 +1133,27 @@ describe('miscellaneous', function() { }); it('dedupes an installation properly and returns updatedAt', (done) => { - let headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; - let data = { + const data = { 'installationId': 'lkjsahdfkjhsdfkjhsdfkjhsdf', 'deviceType': 'embedded' }; - let requestOptions = { + const requestOptions = { headers: headers, url: 'http://localhost:8378/1/installations', body: JSON.stringify(data) }; request.post(requestOptions, (error, response, body) => { expect(error).toBe(null); - let b = JSON.parse(body); + const b = JSON.parse(body); expect(typeof b.objectId).toEqual('string'); request.post(requestOptions, (error, response, body) => { expect(error).toBe(null); - let b = JSON.parse(body); + const b = JSON.parse(body); expect(typeof b.updatedAt).toEqual('string'); done(); }); @@ -1161,17 +1161,17 @@ describe('miscellaneous', function() { }); it('android login providing empty authData block works', (done) => { - let headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; - let data = { + const data = { username: 'pulse1989', password: 'password1234', authData: {} }; - let requestOptions = { + const requestOptions = { headers: headers, url: 'http://localhost:8378/1/users', body: JSON.stringify(data) @@ -1181,7 +1181,7 @@ describe('miscellaneous', function() { requestOptions.url = 'http://localhost:8378/1/login'; request.get(requestOptions, (error, response, body) => { expect(error).toBe(null); - let b = JSON.parse(body); + const b = JSON.parse(body); expect(typeof b['sessionToken']).toEqual('string'); done(); }); @@ -1189,25 +1189,25 @@ describe('miscellaneous', function() { }); it('gets relation fields', (done) => { - let object = new Parse.Object('AnObject'); - let relatedObject = new Parse.Object('RelatedObject'); + const object = new Parse.Object('AnObject'); + const relatedObject = new Parse.Object('RelatedObject'); Parse.Object.saveAll([object, relatedObject]).then(() => { object.relation('related').add(relatedObject); return object.save(); }).then(() => { - let headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; - let requestOptions = { + const requestOptions = { headers: headers, url: 'http://localhost:8378/1/classes/AnObject', json: true }; request.get(requestOptions, (err, res, body) => { expect(body.results.length).toBe(1); - let result = body.results[0]; + const result = body.results[0]; expect(result.related).toEqual({ __type: "Relation", className: 'RelatedObject' @@ -1221,20 +1221,20 @@ describe('miscellaneous', function() { }); it('properly returns incremented values (#1554)', (done) => { - let headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' }; - let requestOptions = { + const requestOptions = { headers: headers, url: 'http://localhost:8378/1/classes/AnObject', json: true }; - let object = new Parse.Object('AnObject'); + const object = new Parse.Object('AnObject'); function runIncrement(amount) { - let options = Object.assign({}, requestOptions, { + const options = Object.assign({}, requestOptions, { body: { "key": { __op: 'Increment', @@ -1266,7 +1266,7 @@ describe('miscellaneous', function() { }) it('ignores _RevocableSession "header" send by JS SDK', (done) => { - let object = new Parse.Object('AnObject'); + const object = new Parse.Object('AnObject'); object.set('a', 'b'); object.save().then(() => { request.post({ @@ -1285,7 +1285,7 @@ describe('miscellaneous', function() { expect(body.error).toBeUndefined(); expect(body.results).not.toBeUndefined(); expect(body.results.length).toBe(1); - let result = body.results[0]; + const result = body.results[0]; expect(result.a).toBe('b'); done(); }) @@ -1293,7 +1293,7 @@ describe('miscellaneous', function() { }); it('doesnt convert interior keys of objects that use special names', done => { - let obj = new Parse.Object('Obj'); + const obj = new Parse.Object('Obj'); obj.set('val', { createdAt: 'a', updatedAt: 1 }); obj.save() .then(obj => new Parse.Query('Obj').get(obj.id)) @@ -1361,10 +1361,10 @@ describe('miscellaneous', function() { }); it('does not change inner objects if the key has the same name as a geopoint field on the class, and the value is an array of length 2, or if the key has the same name as a file field on the class, and the value is a string', done => { - let file = new Parse.File('myfile.txt', { base64: 'eAo=' }); + const file = new Parse.File('myfile.txt', { base64: 'eAo=' }); file.save() .then(f => { - let obj = new Parse.Object('O'); + const obj = new Parse.Object('O'); obj.set('fileField', f); obj.set('geoField', new Parse.GeoPoint(0, 0)); obj.set('innerObj', { @@ -1387,17 +1387,17 @@ describe('miscellaneous', function() { }); it('purge all objects in class', (done) => { - let object = new Parse.Object('TestObject'); + const object = new Parse.Object('TestObject'); object.set('foo', 'bar'); - let object2 = new Parse.Object('TestObject'); + const object2 = new Parse.Object('TestObject'); object2.set('alice', 'wonderland'); Parse.Object.saveAll([object, object2]) .then(() => { - let query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); return query.count() }).then((count) => { expect(count).toBe(2); - let headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-Master-Key': 'test' @@ -1408,7 +1408,7 @@ describe('miscellaneous', function() { json: true }, (err) => { expect(err).toBe(null); - let query = new Parse.Query(TestObject); + const query = new Parse.Query(TestObject); return query.count().then((count) => { expect(count).toBe(0); done(); @@ -1418,7 +1418,7 @@ describe('miscellaneous', function() { }); it('fail on purge all objects in class without master key', (done) => { - let headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' @@ -1437,7 +1437,7 @@ describe('miscellaneous', function() { }); it('purge all objects in _Role also purge cache', (done) => { - let headers = { + const headers = { 'Content-Type': 'application/json', 'X-Parse-Application-Id': 'test', 'X-Parse-Master-Key': 'test' @@ -1445,26 +1445,26 @@ describe('miscellaneous', function() { var user, object; createTestUser().then((x) => { user = x; - let acl = new Parse.ACL(); + const acl = new Parse.ACL(); acl.setPublicReadAccess(true); acl.setPublicWriteAccess(false); - let role = new Parse.Object('_Role'); + const role = new Parse.Object('_Role'); role.set('name', 'TestRole'); role.setACL(acl); - let users = role.relation('users'); + const users = role.relation('users'); users.add(user); return role.save({}, { useMasterKey: true }); }).then(() => { - let query = new Parse.Query('_Role'); + const query = new Parse.Query('_Role'); return query.find({ useMasterKey: true }); }).then((x) => { expect(x.length).toEqual(1); - let relation = x[0].relation('users').query(); + const relation = x[0].relation('users').query(); return relation.first({ useMasterKey: true }); }).then((x) => { expect(x.id).toEqual(user.id); object = new Parse.Object('TestObject'); - let acl = new Parse.ACL(); + const acl = new Parse.ACL(); acl.setPublicReadAccess(false); acl.setPublicWriteAccess(false); acl.setRoleReadAccess('TestRole', true); @@ -1472,7 +1472,7 @@ describe('miscellaneous', function() { object.setACL(acl); return object.save(); }).then(() => { - let query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); return query.find({ sessionToken: user.getSessionToken() }); }).then((x) => { expect(x.length).toEqual(1); @@ -1483,7 +1483,7 @@ describe('miscellaneous', function() { json: true }); }).then(() => { - let query = new Parse.Query('TestObject'); + const query = new Parse.Query('TestObject'); return query.get(object.id, { sessionToken: user.getSessionToken() }); }).then(() => { fail('Should not succeed'); @@ -1502,7 +1502,7 @@ describe('miscellaneous', function() { response.success(); }); - let object = new Parse.Object('MyObject'); + const object = new Parse.Object('MyObject'); object.set('key', 'value'); object.save().then(() => { return object.save({'secret': 'should not update schema'}); @@ -1520,7 +1520,7 @@ describe('miscellaneous', function() { json: true }); }).then((res) => { - let fields = res.fields; + const fields = res.fields; expect(fields.secret).toBeUndefined(); done(); }, (err) => { @@ -1532,7 +1532,7 @@ describe('miscellaneous', function() { describe_only_db('mongo')('legacy _acl', () => { it('should have _acl when locking down (regression for #2465)', (done) => { - let headers = { + const headers = { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest' } @@ -1546,13 +1546,13 @@ describe_only_db('mongo')('legacy _acl', () => { }, json: true }).then(() => { - let config = new Config('test'); - let adapter = config.database.adapter; + const config = new Config('test'); + const adapter = config.database.adapter; return adapter._adaptiveCollection("Report") .then(collection => collection.find({})) }).then((results) => { expect(results.length).toBe(1); - let result = results[0]; + const result = results[0]; expect(result.name).toEqual('My Report'); expect(result._wperm).toEqual([]); expect(result._rperm).toEqual([]); diff --git a/spec/ParseFile.spec.js b/spec/ParseFile.spec.js index 5441ca4028..600c4bae59 100644 --- a/spec/ParseFile.spec.js +++ b/spec/ParseFile.spec.js @@ -563,7 +563,7 @@ describe('Parse.File testing', () => { var query = new Parse.Query('FileTest'); return query.first(); }).then(result => { - let fileAgain = result.get('file'); + const fileAgain = result.get('file'); expect(fileAgain.url()).toMatch(/123.txt$/); done(); }).catch((e) => { @@ -587,7 +587,7 @@ describe('Parse.File testing', () => { var query = new Parse.Query('FileTest'); return query.first(); }).then(result => { - let fileAgain = result.get('file'); + const fileAgain = result.get('file'); expect(fileAgain.url().indexOf('https://mydomain/parse')).toBe(0); done(); }).catch((e) => { diff --git a/spec/ParseGlobalConfig.spec.js b/spec/ParseGlobalConfig.spec.js index 8440f3ae97..c39c5c44e1 100644 --- a/spec/ParseGlobalConfig.spec.js +++ b/spec/ParseGlobalConfig.spec.js @@ -1,12 +1,12 @@ 'use strict'; var request = require('request'); -let Config = require('../src/Config'); +const Config = require('../src/Config'); describe('a GlobalConfig', () => { beforeEach(done => { - let config = new Config('test'); - let query = on_db('mongo', () => { + const config = new Config('test'); + const query = on_db('mongo', () => { // Legacy is with an int... return { objectId: 1 }; }, () => { @@ -104,7 +104,7 @@ describe('a GlobalConfig', () => { }); it('failed getting config when it is missing', (done) => { - let config = new Config('test'); + const config = new Config('test'); config.database.adapter.deleteObjectsByQuery( '_GlobalConfig', { fields: { params: { __type: 'String' } } }, diff --git a/spec/ParseHooks.spec.js b/spec/ParseHooks.spec.js index 899a2a4fd9..0747981c5d 100644 --- a/spec/ParseHooks.spec.js +++ b/spec/ParseHooks.spec.js @@ -8,7 +8,7 @@ var bodyParser = require('body-parser'); var port = 12345; var hookServerURL = "http://localhost:"+port; -let AppCache = require('../src/cache').AppCache; +const AppCache = require('../src/cache').AppCache; var app = express(); app.use(bodyParser.json({ 'type': '*/*' })) diff --git a/spec/ParseInstallation.spec.js b/spec/ParseInstallation.spec.js index fd3fb55a8c..a34e6d676b 100644 --- a/spec/ParseInstallation.spec.js +++ b/spec/ParseInstallation.spec.js @@ -2,15 +2,15 @@ // These tests check the Installations functionality of the REST API. // Ported from installation_collection_test.go -let auth = require('../src/Auth'); -let Config = require('../src/Config'); -let Parse = require('parse/node').Parse; -let rest = require('../src/rest'); -let request = require("request"); +const auth = require('../src/Auth'); +const Config = require('../src/Config'); +const Parse = require('parse/node').Parse; +const rest = require('../src/rest'); +const request = require("request"); let config; let database; -let defaultColumns = require('../src/Controllers/SchemaController').defaultColumns; +const defaultColumns = require('../src/Controllers/SchemaController').defaultColumns; const installationSchema = { fields: Object.assign({}, defaultColumns._Default, defaultColumns._Installation) }; @@ -130,7 +130,7 @@ describe('Installations', () => { }; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => { - let query = new Parse.Query(Parse.Installation); + const query = new Parse.Query(Parse.Installation); return query.find() }).then(() => { fail('Should not succeed!'); @@ -151,7 +151,7 @@ describe('Installations', () => { }; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => { - let query = new Parse.Query(Parse.Installation); + const query = new Parse.Query(Parse.Installation); return query.find({useMasterKey: true}); }).then((results) => { expect(results.length).toEqual(1); @@ -842,15 +842,15 @@ describe('Installations', () => { }); it('allows you to get your own installation (regression test for #1718)', done => { - let installId = '12345678-abcd-abcd-abcd-123456789abc'; - let device = 'android'; - let input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; rest.create(config, auth.nobody(config), '_Installation', input) .then(createResult => { - let headers = { + const headers = { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', }; @@ -871,15 +871,15 @@ describe('Installations', () => { }); it('allows you to update installation from header (#2090)', done => { - let installId = '12345678-abcd-abcd-abcd-123456789abc'; - let device = 'android'; - let input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; rest.create(config, auth.nobody(config), '_Installation', input) .then(() => { - let headers = { + const headers = { 'X-Parse-Application-Id': 'test', 'X-Parse-REST-API-Key': 'rest', 'X-Parse-Installation-Id': installId @@ -905,15 +905,15 @@ describe('Installations', () => { }); it('allows you to update installation with masterKey', done => { - let installId = '12345678-abcd-abcd-abcd-123456789abc'; - let device = 'android'; - let input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; rest.create(config, auth.nobody(config), '_Installation', input) .then(createResult => { - let installationObj = Parse.Installation.createWithoutData(createResult.response.objectId); + const installationObj = Parse.Installation.createWithoutData(createResult.response.objectId); installationObj.set('customField', 'custom value'); return installationObj.save(null, {useMasterKey: true}); }).then(updateResult => { @@ -928,14 +928,14 @@ describe('Installations', () => { }); it('should properly handle installation save #2780', done => { - let installId = '12345678-abcd-abcd-abcd-123456789abc'; - let device = 'android'; - let input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; rest.create(config, auth.nobody(config), '_Installation', input).then(() => { - let query = new Parse.Query(Parse.Installation); + const query = new Parse.Query(Parse.Installation); query.equalTo('installationId', installId); query.first({useMasterKey: true}).then((installation) => { return installation.save({ @@ -951,14 +951,14 @@ describe('Installations', () => { }); it('should properly reject updating installationId', done => { - let installId = '12345678-abcd-abcd-abcd-123456789abc'; - let device = 'android'; - let input = { + const installId = '12345678-abcd-abcd-abcd-123456789abc'; + const device = 'android'; + const input = { 'installationId': installId, 'deviceType': device }; rest.create(config, auth.nobody(config), '_Installation', input).then(() => { - let query = new Parse.Query(Parse.Installation); + const query = new Parse.Query(Parse.Installation); query.equalTo('installationId', installId); query.first({useMasterKey: true}).then((installation) => { return installation.save({ diff --git a/spec/ParseLiveQueryServer.spec.js b/spec/ParseLiveQueryServer.spec.js index 50a4133a2d..c89ba276b8 100644 --- a/spec/ParseLiveQueryServer.spec.js +++ b/spec/ParseLiveQueryServer.spec.js @@ -358,7 +358,7 @@ describe('ParseLiveQueryServer', function() { expect(args[0]).toBe(parseWebSocket); expect(JSON.stringify(args[1])).toBe(updateRequest); expect(parseLiveQueryServer._handleUnsubscribe).toHaveBeenCalled(); - let unsubArgs = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args; + const unsubArgs = parseLiveQueryServer._handleUnsubscribe.calls.mostRecent().args; expect(unsubArgs.length).toBe(3); expect(unsubArgs[2]).toBe(false); expect(parseLiveQueryServer._handleSubscribe).toHaveBeenCalled(); diff --git a/spec/ParseObject.spec.js b/spec/ParseObject.spec.js index 35e8b288b1..b959d3b8b3 100644 --- a/spec/ParseObject.spec.js +++ b/spec/ParseObject.spec.js @@ -596,8 +596,8 @@ describe('Parse.Object testing', () => { var query = new Parse.Query('X'); return query.get(x1.id); }).then((x3) => { - let stuff = x3.get('stuff'); - let expected = [1, 2, 4]; + const stuff = x3.get('stuff'); + const expected = [1, 2, 4]; expect(stuff.length).toBe(expected.length); for (var i of stuff) { expect(expected.indexOf(i) >= 0).toBe(true); @@ -628,12 +628,12 @@ describe('Parse.Object testing', () => { var query = new Parse.Query('X'); return query.get(x1.id); }).then((x3) => { - let stuff = x3.get('stuff'); - let target = [1, {'hello': 'world'}, {'foo': 'bar'}, {'bar': 'baz'}]; + const stuff = x3.get('stuff'); + const target = [1, {'hello': 'world'}, {'foo': 'bar'}, {'bar': 'baz'}]; expect(stuff.length).toEqual(target.length); let found = 0; - for (let thing in target) { - for (let st in stuff) { + for (const thing in target) { + for (const st in stuff) { if (st == thing) { found++; } @@ -1861,15 +1861,15 @@ describe('Parse.Object testing', () => { }); it('should have undefined includes when object is missing', (done) => { - let obj1 = new Parse.Object("AnObject"); - let obj2 = new Parse.Object("AnObject"); + const obj1 = new Parse.Object("AnObject"); + const obj2 = new Parse.Object("AnObject"); Parse.Object.saveAll([obj1, obj2]).then(() => { obj1.set("obj", obj2); // Save the pointer, delete the pointee return obj1.save().then(() => { return obj2.destroy() }); }).then(() => { - let query = new Parse.Query("AnObject"); + const query = new Parse.Query("AnObject"); query.include("obj"); return query.find(); }).then((res) => { @@ -1877,7 +1877,7 @@ describe('Parse.Object testing', () => { if (res[0]) { expect(res[0].get("obj")).toBe(undefined); } - let query = new Parse.Query("AnObject"); + const query = new Parse.Query("AnObject"); return query.find(); }).then((res) => { expect(res.length).toBe(1); @@ -1896,16 +1896,16 @@ describe('Parse.Object testing', () => { }); it('should have undefined includes when object is missing on deeper path', (done) => { - let obj1 = new Parse.Object("AnObject"); - let obj2 = new Parse.Object("AnObject"); - let obj3 = new Parse.Object("AnObject"); + const obj1 = new Parse.Object("AnObject"); + const obj2 = new Parse.Object("AnObject"); + const obj3 = new Parse.Object("AnObject"); Parse.Object.saveAll([obj1, obj2, obj3]).then(() => { obj1.set("obj", obj2); obj2.set("obj", obj3); // Save the pointer, delete the pointee return Parse.Object.saveAll([obj1, obj2]).then(() => { return obj3.destroy() }); }).then(() => { - let query = new Parse.Query("AnObject"); + const query = new Parse.Query("AnObject"); query.include("obj.obj"); return query.get(obj1.id); }).then((res) => { @@ -1919,9 +1919,9 @@ describe('Parse.Object testing', () => { }); it('should handle includes on null arrays #2752', (done) => { - let obj1 = new Parse.Object("AnObject"); - let obj2 = new Parse.Object("AnotherObject"); - let obj3 = new Parse.Object("NestedObject"); + const obj1 = new Parse.Object("AnObject"); + const obj2 = new Parse.Object("AnotherObject"); + const obj3 = new Parse.Object("NestedObject"); obj3.set({ "foo": "bar" }) @@ -1933,13 +1933,13 @@ describe('Parse.Object testing', () => { obj1.set("objects", [null, null, obj2]); return obj1.save(); }).then(() => { - let query = new Parse.Query("AnObject"); + const query = new Parse.Query("AnObject"); query.include("objects.key"); return query.find(); }).then((res) => { - let obj = res[0]; + const obj = res[0]; expect(obj.get("objects")).not.toBe(undefined); - let array = obj.get("objects"); + const array = obj.get("objects"); expect(Array.isArray(array)).toBe(true); expect(array[0]).toBe(null); expect(array[1]).toBe(null); @@ -1952,8 +1952,8 @@ describe('Parse.Object testing', () => { }); it('should handle select and include #2786', (done) => { - let score = new Parse.Object("GameScore"); - let player = new Parse.Object("Player"); + const score = new Parse.Object("GameScore"); + const player = new Parse.Object("Player"); score.set({ "score": 1234 }); @@ -1963,14 +1963,14 @@ describe('Parse.Object testing', () => { player.set("other", "value"); return player.save(); }).then(() => { - let query = new Parse.Query("Player"); + const query = new Parse.Query("Player"); query.include("gameScore"); query.select("gameScore"); return query.find(); }).then((res) => { - let obj = res[0]; - let gameScore = obj.get("gameScore"); - let other = obj.get("other"); + const obj = res[0]; + const gameScore = obj.get("gameScore"); + const other = obj.get("other"); expect(other).toBeUndefined(); expect(gameScore).not.toBeUndefined(); expect(gameScore.get("score")).toBe(1234); diff --git a/spec/ParsePubSub.spec.js b/spec/ParsePubSub.spec.js index 737ed28135..17d523b16a 100644 --- a/spec/ParsePubSub.spec.js +++ b/spec/ParsePubSub.spec.js @@ -59,7 +59,7 @@ describe('ParsePubSub', function() { }); it('can create publisher/sub with custom adapter', function() { - let adapter = { + const adapter = { createPublisher: jasmine.createSpy('createPublisher'), createSubscriber: jasmine.createSpy('createSubscriber') } @@ -82,7 +82,7 @@ describe('ParsePubSub', function() { }); it('can create publisher/sub with custom function adapter', function() { - let adapter = { + const adapter = { createPublisher: jasmine.createSpy('createPublisher'), createSubscriber: jasmine.createSpy('createSubscriber') } diff --git a/spec/ParseQuery.spec.js b/spec/ParseQuery.spec.js index 030deed921..b0cc180250 100644 --- a/spec/ParseQuery.spec.js +++ b/spec/ParseQuery.spec.js @@ -114,7 +114,7 @@ describe('Parse.Query testing', () => { // Only cake3 is liked only by user1 return query.find().then(function(results){ equal(results.length, 1); - let cake = results[0]; + const cake = results[0]; expect(cake.id).toBe(cake3.id); }); }).then(function(){ @@ -864,7 +864,7 @@ describe('Parse.Query testing', () => { return new BoxedNumber({ number: num, string: strings[i] }); }; - let objects = [3, 1, 3, 2].map(makeBoxedNumber); + const objects = [3, 1, 3, 2].map(makeBoxedNumber); Parse.Object.saveAll(objects) .then(() => { var query = new Parse.Query(BoxedNumber); @@ -1566,26 +1566,26 @@ describe('Parse.Query testing', () => { }); it('properly includes array', (done) => { - let objects = []; + const objects = []; let total = 0; while(objects.length != 5) { - let object = new Parse.Object('AnObject'); + const object = new Parse.Object('AnObject'); object.set('key', objects.length); total += objects.length; objects.push(object); } Parse.Object.saveAll(objects).then(() => { - let object = new Parse.Object("AContainer"); + const object = new Parse.Object("AContainer"); object.set('objects', objects); return object.save(); }).then(() => { - let query = new Parse.Query('AContainer'); + const query = new Parse.Query('AContainer'); query.include('objects'); return query.find() }).then((results) => { expect(results.length).toBe(1); - let res = results[0]; - let objects = res.get('objects'); + const res = results[0]; + const objects = res.get('objects'); expect(objects.length).toBe(5); objects.forEach((object) => { total -= object.get('key'); @@ -1599,32 +1599,32 @@ describe('Parse.Query testing', () => { }); it('properly includes array of mixed objects', (done) => { - let objects = []; + const objects = []; let total = 0; while(objects.length != 5) { - let object = new Parse.Object('AnObject'); + const object = new Parse.Object('AnObject'); object.set('key', objects.length); total += objects.length; objects.push(object); } while(objects.length != 10) { - let object = new Parse.Object('AnotherObject'); + const object = new Parse.Object('AnotherObject'); object.set('key', objects.length); total += objects.length; objects.push(object); } Parse.Object.saveAll(objects).then(() => { - let object = new Parse.Object("AContainer"); + const object = new Parse.Object("AContainer"); object.set('objects', objects); return object.save(); }).then(() => { - let query = new Parse.Query('AContainer'); + const query = new Parse.Query('AContainer'); query.include('objects'); return query.find() }).then((results) => { expect(results.length).toBe(1); - let res = results[0]; - let objects = res.get('objects'); + const res = results[0]; + const objects = res.get('objects'); expect(objects.length).toBe(10); objects.forEach((object) => { total -= object.get('key'); @@ -1638,20 +1638,20 @@ describe('Parse.Query testing', () => { }); it('properly nested array of mixed objects with bad ids', (done) => { - let objects = []; + const objects = []; let total = 0; while(objects.length != 5) { - let object = new Parse.Object('AnObject'); + const object = new Parse.Object('AnObject'); object.set('key', objects.length); objects.push(object); } while(objects.length != 10) { - let object = new Parse.Object('AnotherObject'); + const object = new Parse.Object('AnotherObject'); object.set('key', objects.length); objects.push(object); } Parse.Object.saveAll(objects).then(() => { - let object = new Parse.Object("AContainer"); + const object = new Parse.Object("AContainer"); for (var i=0; i { object.set('objects', objects); return object.save(); }).then(() => { - let query = new Parse.Query('AContainer'); + const query = new Parse.Query('AContainer'); query.include('objects'); return query.find() }).then((results) => { expect(results.length).toBe(1); - let res = results[0]; - let objects = res.get('objects'); + const res = results[0]; + const objects = res.get('objects'); expect(objects.length).toBe(5); objects.forEach((object) => { total -= object.get('key'); @@ -1683,25 +1683,25 @@ describe('Parse.Query testing', () => { }); it('properly fetches nested pointers', (done) => { - let color = new Parse.Object('Color'); + const color = new Parse.Object('Color'); color.set('hex','#133733'); - let circle = new Parse.Object('Circle'); + const circle = new Parse.Object('Circle'); circle.set('radius', 1337); Parse.Object.saveAll([color, circle]).then(() => { circle.set('color', color); - let badCircle = new Parse.Object('Circle'); + const badCircle = new Parse.Object('Circle'); badCircle.id = 'badId'; - let complexFigure = new Parse.Object('ComplexFigure'); + const complexFigure = new Parse.Object('ComplexFigure'); complexFigure.set('consistsOf', [circle, badCircle]); return complexFigure.save(); }).then(() => { - let q = new Parse.Query('ComplexFigure'); + const q = new Parse.Query('ComplexFigure'); q.include('consistsOf.color'); return q.find() }).then((results) => { expect(results.length).toBe(1); - let figure = results[0]; + const figure = results[0]; expect(figure.get('consistsOf').length).toBe(1); expect(figure.get('consistsOf')[0].get('color').get('hex')).toBe('#133733'); done(); @@ -2357,15 +2357,15 @@ describe('Parse.Query testing', () => { }); it('supports include on the wrong key type (#2262)', function(done) { - let childObject = new Parse.Object('TestChildObject'); + const childObject = new Parse.Object('TestChildObject'); childObject.set('hello', 'world'); childObject.save().then(() => { - let obj = new Parse.Object('TestObject'); + const obj = new Parse.Object('TestObject'); obj.set('foo', 'bar'); obj.set('child', childObject); return obj.save(); }).then(() => { - let q = new Parse.Query('TestObject'); + const q = new Parse.Query('TestObject'); q.include('child'); q.include('child.parent'); q.include('createdAt'); @@ -2485,13 +2485,13 @@ describe('Parse.Query testing', () => { } }) container.set('objects', pointers); - let container2 = new Parse.Object('Container'); + const container2 = new Parse.Object('Container'); container2.set('objects', pointers.slice(2, 3)); return Parse.Object.saveAll([container, container2]); }).then(() => { - let inQuery = new Parse.Query('ContainedObject'); + const inQuery = new Parse.Query('ContainedObject'); inQuery.greaterThanOrEqualTo('index', 1); - let query = new Parse.Query('Container'); + const query = new Parse.Query('Container'); query.matchesQuery('objects', inQuery); return query.find(); }).then((results) => { @@ -2507,16 +2507,16 @@ describe('Parse.Query testing', () => { }) it('query with two OR subqueries (regression test #1259)', done => { - let relatedObject = new Parse.Object('Class2'); + const relatedObject = new Parse.Object('Class2'); relatedObject.save().then(relatedObject => { - let anObject = new Parse.Object('Class1'); - let relation = anObject.relation('relation'); + const anObject = new Parse.Object('Class1'); + const relation = anObject.relation('relation'); relation.add(relatedObject); return anObject.save(); }).then(anObject => { - let q1 = anObject.relation('relation').query(); + const q1 = anObject.relation('relation').query(); q1.doesNotExist('nonExistantKey1'); - let q2 = anObject.relation('relation').query(); + const q2 = anObject.relation('relation').query(); q2.doesNotExist('nonExistantKey2'); Parse.Query.or(q1, q2).find().then(results => { expect(results.length).toEqual(1); @@ -2529,14 +2529,14 @@ describe('Parse.Query testing', () => { }); it('objectId containedIn with multiple large array', done => { - let obj = new Parse.Object('MyClass'); + const obj = new Parse.Object('MyClass'); obj.save().then(obj => { - let longListOfStrings = []; + const longListOfStrings = []; for (let i = 0; i < 130; i++) { longListOfStrings.push(i.toString()); } longListOfStrings.push(obj.id); - let q = new Parse.Query('MyClass'); + const q = new Parse.Query('MyClass'); q.containedIn('objectId', longListOfStrings); q.containedIn('objectId', longListOfStrings); return q.find(); @@ -2703,13 +2703,13 @@ describe('Parse.Query testing', () => { objects.push(obj) } Parse.Object.saveAll(objects).then(() => { - let q0 = new Parse.Query('Object'); + const q0 = new Parse.Query('Object'); q0.equalTo('x', 0); - let q1 = new Parse.Query('Object'); + const q1 = new Parse.Query('Object'); q1.equalTo('x', 1); - let q2 = new Parse.Query('Object'); + const q2 = new Parse.Query('Object'); q2.equalTo('x', 2); - let or01 = Parse.Query.or(q0,q1); + const or01 = Parse.Query.or(q0,q1); return Parse.Query.or(or01, q2).find(); }).then((results) => { expect(results.length).toBe(3); diff --git a/spec/ParseRelation.spec.js b/spec/ParseRelation.spec.js index 0f97b78569..6adbe38450 100644 --- a/spec/ParseRelation.spec.js +++ b/spec/ParseRelation.spec.js @@ -249,35 +249,35 @@ describe('Parse.Relation testing', () => { }); it("queries on relation fields with multiple containedIn (regression test for #1271)", (done) => { - let ChildObject = Parse.Object.extend("ChildObject"); - let childObjects = []; + 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(() => { - let ParentObject = Parse.Object.extend("ParentObject"); - let parent = new ParentObject(); + const ParentObject = Parse.Object.extend("ParentObject"); + const parent = new ParentObject(); parent.set("x", 4); - let parent1Children = parent.relation("child"); + const parent1Children = parent.relation("child"); parent1Children.add(childObjects[0]); parent1Children.add(childObjects[1]); parent1Children.add(childObjects[2]); - let parent2 = new ParentObject(); + const parent2 = new ParentObject(); parent2.set("x", 3); - let parent2Children = parent2.relation("child"); + const parent2Children = parent2.relation("child"); parent2Children.add(childObjects[4]); parent2Children.add(childObjects[5]); parent2Children.add(childObjects[6]); - let parent2OtherChildren = parent2.relation("otherChild"); + const parent2OtherChildren = parent2.relation("otherChild"); parent2OtherChildren.add(childObjects[0]); parent2OtherChildren.add(childObjects[1]); parent2OtherChildren.add(childObjects[2]); return Parse.Object.saveAll([parent, parent2]); }).then(() => { - let objectsWithChild0InBothChildren = new Parse.Query(ParentObject); + const objectsWithChild0InBothChildren = new Parse.Query(ParentObject); objectsWithChild0InBothChildren.containedIn("child", [childObjects[0]]); objectsWithChild0InBothChildren.containedIn("otherChild", [childObjects[0]]); return objectsWithChild0InBothChildren.find(); @@ -285,7 +285,7 @@ describe('Parse.Relation testing', () => { //No parent has child 0 in both it's "child" and "otherChild" field; expect(objectsWithChild0InBothChildren.length).toEqual(0); }).then(() => { - let objectsWithChild4andOtherChild1 = new Parse.Query(ParentObject); + const objectsWithChild4andOtherChild1 = new Parse.Query(ParentObject); objectsWithChild4andOtherChild1.containedIn("child", [childObjects[4]]); objectsWithChild4andOtherChild1.containedIn("otherChild", [childObjects[1]]); return objectsWithChild4andOtherChild1.find(); @@ -510,24 +510,24 @@ describe('Parse.Relation testing', () => { }); it('should properly get related objects with unfetched queries', (done) => { - let objects = []; - let owners = []; - let allObjects = []; + const objects = []; + const owners = []; + const allObjects = []; // Build 10 Objects and 10 owners while (objects.length != 10) { - let object = new Parse.Object('AnObject'); + const object = new Parse.Object('AnObject'); object.set({ index: objects.length, even: objects.length % 2 == 0 }); objects.push(object); - let owner = new Parse.Object('AnOwner'); + const owner = new Parse.Object('AnOwner'); owners.push(owner); allObjects.push(object); allObjects.push(owner); } - let anotherOwner = new Parse.Object('AnotherOwner'); + const anotherOwner = new Parse.Object('AnotherOwner'); return Parse.Object.saveAll(allObjects.concat([anotherOwner])).then(() => { // put all the AnObject into the anotherOwner relationKey @@ -539,13 +539,13 @@ describe('Parse.Relation testing', () => { return Parse.Object.saveAll(owners.concat([anotherOwner])); }).then(() => { // Query on the relation of another owner - let object = new Parse.Object('AnotherOwner'); + const object = new Parse.Object('AnotherOwner'); object.id = anotherOwner.id; - let relationQuery = object.relation('relationKey').query(); + const relationQuery = object.relation('relationKey').query(); // Just get the even ones relationQuery.equalTo('even', true); // Make the query on anOwner - let query = new Parse.Query('AnOwner'); + const query = new Parse.Query('AnOwner'); // where key match the relation query. query.matchesQuery('key', relationQuery); query.include('key'); @@ -558,13 +558,13 @@ describe('Parse.Relation testing', () => { return Promise.resolve(); }).then(() => { // Query on the relation of another owner - let object = new Parse.Object('AnotherOwner'); + const object = new Parse.Object('AnotherOwner'); object.id = anotherOwner.id; - let relationQuery = object.relation('relationKey').query(); + const relationQuery = object.relation('relationKey').query(); // Just get the even ones relationQuery.equalTo('even', true); // Make the query on anOwner - let query = new Parse.Query('AnOwner'); + const query = new Parse.Query('AnOwner'); // where key match the relation query. query.doesNotMatchQuery('key', relationQuery); query.include('key'); @@ -586,19 +586,19 @@ describe('Parse.Relation testing', () => { new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), ]; - let persons = [ + const persons = [ new PersonObject({ name: "Bob", hometown: "Djibouti" }), new PersonObject({ name: "Tom", hometown: "Ouagadougou" }), new PersonObject({ name: "Billy", hometown: "Detroit" }), ]; - let owner = new OwnerObject({name: 'Joe'}); - let allObjects = [owner].concat(restaurants).concat(persons); + const owner = new OwnerObject({name: 'Joe'}); + const allObjects = [owner].concat(restaurants).concat(persons); expect(allObjects.length).toEqual(6); Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() { owner.relation('restaurants').add(restaurants); return owner.save() }).then(() => { - let unfetchedOwner = new OwnerObject(); + const unfetchedOwner = new OwnerObject(); unfetchedOwner.id = owner.id; var query = unfetchedOwner.relation('restaurants').query(); query.greaterThan("ratings", 4); @@ -624,19 +624,19 @@ describe('Parse.Relation testing', () => { new RestaurantObject({ ratings: 5, location: "Djibouti" }), new RestaurantObject({ ratings: 3, location: "Ouagadougou" }), ]; - let persons = [ + const persons = [ new PersonObject({ name: "Bob", hometown: "Djibouti" }), new PersonObject({ name: "Tom", hometown: "Ouagadougou" }), new PersonObject({ name: "Billy", hometown: "Detroit" }), ]; - let owner = new OwnerObject({name: 'Joe'}); - let allObjects = [owner].concat(restaurants).concat(persons); + const owner = new OwnerObject({name: 'Joe'}); + const allObjects = [owner].concat(restaurants).concat(persons); expect(allObjects.length).toEqual(6); Parse.Object.saveAll([owner].concat(restaurants).concat(persons)).then(function() { owner.relation('restaurants').add(restaurants); return owner.save() }).then(() => { - let unfetchedOwner = new OwnerObject(); + const unfetchedOwner = new OwnerObject(); unfetchedOwner.id = owner.id; var query = unfetchedOwner.relation('restaurants').query(); query.greaterThan("ratings", 4); @@ -657,21 +657,21 @@ describe('Parse.Relation testing', () => { }); it('relations are not bidirectional (regression test for #871)', done => { - let PersonObject = Parse.Object.extend("Person"); - let p1 = new PersonObject(); - let p2 = new PersonObject(); + const PersonObject = Parse.Object.extend("Person"); + const p1 = new PersonObject(); + const p2 = new PersonObject(); Parse.Object.saveAll([p1, p2]).then(results => { - let p1 = results[0]; - let p2 = results[1]; - let relation = p1.relation('relation'); + const p1 = results[0]; + const p2 = results[1]; + const relation = p1.relation('relation'); relation.add(p2); p1.save().then(() => { - let query = new Parse.Query(PersonObject); + const query = new Parse.Query(PersonObject); query.equalTo('relation', p1); query.find().then(results => { expect(results.length).toEqual(0); - let query = new Parse.Query(PersonObject); + const query = new Parse.Query(PersonObject); query.equalTo('relation', p2); query.find().then(results => { expect(results.length).toEqual(1); @@ -685,12 +685,12 @@ describe('Parse.Relation testing', () => { it('can query roles in Cloud Code (regession test #1489)', done => { Parse.Cloud.define('isAdmin', (request, response) => { - let query = new Parse.Query(Parse.Role); + const query = new Parse.Query(Parse.Role); query.equalTo('name', 'admin'); query.first({ useMasterKey: true }) .then(role => { - let relation = new Parse.Relation(role, 'users'); - let admins = relation.query(); + const relation = new Parse.Relation(role, 'users'); + const admins = relation.query(); admins.equalTo('username', request.user.get('username')); admins.first({ useMasterKey: true }) .then(user => { @@ -712,16 +712,16 @@ describe('Parse.Relation testing', () => { }); }); - let adminUser = new Parse.User(); + const adminUser = new Parse.User(); adminUser.set('username', 'name'); adminUser.set('password', 'pass'); adminUser.signUp() .then(adminUser => { - let adminACL = new Parse.ACL(); + const adminACL = new Parse.ACL(); adminACL.setPublicReadAccess(true); // Create admin role - let adminRole = new Parse.Role('admin', adminACL); + const adminRole = new Parse.Role('admin', adminACL); adminRole.getUsers().add(adminUser); adminRole.save() .then(() => { @@ -739,13 +739,13 @@ describe('Parse.Relation testing', () => { }); it('can be saved without error', done => { - let obj1 = new Parse.Object('PPAP'); + const obj1 = new Parse.Object('PPAP'); obj1.save() .then(() => { - let newRelation = obj1.relation('aRelation'); + const newRelation = obj1.relation('aRelation'); newRelation.add(obj1); obj1.save().then(() => { - let relation = obj1.get('aRelation'); + const relation = obj1.get('aRelation'); obj1.set('aRelation', relation); obj1.save().then(() => { done(); diff --git a/spec/ParseRole.spec.js b/spec/ParseRole.spec.js index 4ef3713fdb..24a14bd6e0 100644 --- a/spec/ParseRole.spec.js +++ b/spec/ParseRole.spec.js @@ -13,7 +13,7 @@ describe('Parse Role testing', () => { createTestUser().then((x) => { user = x; - let acl = new Parse.ACL(); + const acl = new Parse.ACL(); acl.setPublicReadAccess(true); acl.setPublicWriteAccess(false); role = new Parse.Object('_Role'); @@ -193,11 +193,11 @@ describe('Parse Role testing', () => { }); it("Should properly resolve roles", (done) => { - let admin = new Parse.Role("Admin", new Parse.ACL()); - let moderator = new Parse.Role("Moderator", new Parse.ACL()); - let superModerator = new Parse.Role("SuperModerator", new Parse.ACL()); - let contentManager = new Parse.Role('ContentManager', new Parse.ACL()); - let superContentManager = new Parse.Role('SuperContentManager', new Parse.ACL()); + const admin = new Parse.Role("Admin", new Parse.ACL()); + 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}).then(() => { contentManager.getRoles().add([moderator, superContentManager]); moderator.getRoles().add([admin, superModerator]); @@ -207,7 +207,7 @@ describe('Parse Role testing', () => { var auth = new Auth({ config: new Config("test"), isMaster: true }); // For each role, fetch their sibling, what they inherit // return with result and roleId for later comparison - let promises = [admin, moderator, contentManager, superModerator].map((role) => { + const promises = [admin, moderator, contentManager, superModerator].map((role) => { return auth._getAllRolesNamesForRoleIds([role.id]).then((result) => { return Parse.Promise.as({ id: role.id, @@ -220,8 +220,8 @@ describe('Parse Role testing', () => { return Parse.Promise.when(promises); }).then((results) => { results.forEach((result) => { - let id = result.id; - let roleNames = result.roleNames; + const id = result.id; + const roleNames = result.roleNames; if (id == admin.id) { expect(roleNames.length).toBe(2); expect(roleNames.indexOf("Moderator")).not.toBe(-1); diff --git a/spec/ParseServerRESTController.spec.js b/spec/ParseServerRESTController.spec.js index 96a0e8bac2..ffbfa04077 100644 --- a/spec/ParseServerRESTController.spec.js +++ b/spec/ParseServerRESTController.spec.js @@ -73,7 +73,7 @@ describe('ParseServerRESTController', () => { let userId; Parse.User.signUp('user', 'pass').then((user) => { userId = user.id; - let sessionToken = user.getSessionToken(); + const sessionToken = user.getSessionToken(); return RESTController.request("GET", "/users/me", undefined, {sessionToken}); }).then((res) => { // Result is in JSON format @@ -106,7 +106,7 @@ describe('ParseServerRESTController', () => { it('ensures no session token is created on creating users', (done) => { RESTController.request("POST", "/classes/_User", {username: "hello", password: "world"}).then((user) => { expect(user.sessionToken).toBeUndefined(); - let query = new Parse.Query('_Session'); + const query = new Parse.Query('_Session'); return query.find({useMasterKey: true}); }).then(sessions => { expect(sessions.length).toBe(0); @@ -120,7 +120,7 @@ describe('ParseServerRESTController', () => { it('ensures a session token is created when passing installationId != cloud', (done) => { RESTController.request("POST", "/classes/_User", {username: "hello", password: "world"}, {installationId: 'my-installation'}).then((user) => { expect(user.sessionToken).not.toBeUndefined(); - let query = new Parse.Query('_Session'); + const query = new Parse.Query('_Session'); return query.find({useMasterKey: true}); }).then(sessions => { expect(sessions.length).toBe(1); diff --git a/spec/ParseUser.spec.js b/spec/ParseUser.spec.js index bd301a3aca..b0fcc4e02f 100644 --- a/spec/ParseUser.spec.js +++ b/spec/ParseUser.spec.js @@ -141,8 +141,8 @@ describe('Parse.User testing', () => { }); it('should respect ACL without locking user out', (done) => { - let user = new Parse.User(); - let ACL = new Parse.ACL(); + const user = new Parse.User(); + const ACL = new Parse.ACL(); ACL.setPublicReadAccess(false); ACL.setPublicWriteAccess(false); user.setUsername('asdf'); @@ -163,7 +163,7 @@ describe('Parse.User testing', () => { expect(perms[user.id].write).toBe(true); expect(perms['*']).toBeUndefined(); // Try to lock out user - let newACL = new Parse.ACL(); + const newACL = new Parse.ACL(); newACL.setReadAccess(user.id, false); newACL.setWriteAccess(user.id, false); user.setACL(newACL); @@ -190,13 +190,13 @@ describe('Parse.User testing', () => { }); it("user login with files", (done) => { - let file = new Parse.File("yolo.txt", [1,2,3], "text/plain"); + const file = new Parse.File("yolo.txt", [1,2,3], "text/plain"); file.save().then((file) => { return Parse.User.signUp("asdf", "zxcv", { "file" : file }); }).then(() => { return Parse.User.logIn("asdf", "zxcv"); }).then((user) => { - let fileAgain = user.get('file'); + const fileAgain = user.get('file'); ok(fileAgain.name()); ok(fileAgain.url()); done(); @@ -1153,11 +1153,11 @@ describe('Parse.User testing', () => { it('returns authData when authed and logged in with provider (regression test for #1498)', done => { Parse.Object.enableSingleInstance(); - let provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith('facebook', { success: user => { - let userQuery = new Parse.Query(Parse.User); + const userQuery = new Parse.Query(Parse.User); userQuery.get(user.id) .then(user => { expect(user.get('authData')).not.toBeUndefined(); @@ -1169,18 +1169,18 @@ describe('Parse.User testing', () => { }); it('log in with provider with files', done => { - let provider = getMockFacebookProvider(); + const provider = getMockFacebookProvider(); Parse.User._registerAuthenticationProvider(provider); - let file = new Parse.File("yolo.txt", [1, 2, 3], "text/plain"); + const file = new Parse.File("yolo.txt", [1, 2, 3], "text/plain"); file.save().then(file => { - let user = new Parse.User(); + const user = new Parse.User(); user.set('file', file); return user._linkWith('facebook', {}); }).then(user => { expect(user._isLinked("facebook")).toBeTruthy(); return Parse.User._logInWith('facebook', {}); }).then(user => { - let fileAgain = user.get('file'); + const fileAgain = user.get('file'); expect(fileAgain.name()).toMatch(/yolo.txt$/); expect(fileAgain.url()).toMatch(/yolo.txt$/); }).then(() => { @@ -1535,7 +1535,7 @@ describe('Parse.User testing', () => { strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked("facebook"), "User should be linked to facebook"); Parse.User._registerAuthenticationProvider(mockProvider); - let objectId = model.id; + const objectId = model.id; model._linkWith("myoauth", { success: function(model) { expect(model.id).toEqual(objectId); @@ -1571,7 +1571,7 @@ describe('Parse.User testing', () => { Parse.User._logInWith("facebook", { success: function(model) { Parse.User._registerAuthenticationProvider(mockProvider); - let objectId = model.id; + const objectId = model.id; model._linkWith("myoauth", { success: function() { Parse.User._registerAuthenticationProvider(secondProvider); @@ -1612,7 +1612,7 @@ describe('Parse.User testing', () => { strictEqual(provider.authData.expiration_date, provider.synchronizedExpiration); ok(model._isLinked("facebook"), "User should be linked to facebook"); Parse.User._registerAuthenticationProvider(mockProvider); - let objectId = model.id; + const objectId = model.id; model._linkWith("myoauth", { success: function(model) { expect(model.id).toEqual(objectId); @@ -1650,7 +1650,7 @@ describe('Parse.User testing', () => { Parse.User._logInWith("facebook", { success: function() { Parse.User.logOut().then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('user'); user.setPassword('password'); return user.signUp().then(() => { @@ -1675,7 +1675,7 @@ describe('Parse.User testing', () => { Parse.User._registerAuthenticationProvider(provider); Parse.User._logInWith("facebook", { success: function(model) { - let userId = model.id; + const userId = model.id; Parse.User.logOut().then(() => { request.post({ url:Parse.serverURL+'/classes/_User', @@ -1722,7 +1722,7 @@ describe('Parse.User testing', () => { it('should have authData in beforeSave and afterSave', (done) => { Parse.Cloud.beforeSave('_User', (request, response) => { - let authData = request.object.get('authData'); + const authData = request.object.get('authData'); expect(authData).not.toBeUndefined(); if (authData) { expect(authData.facebook.id).toEqual('8675309'); @@ -1734,7 +1734,7 @@ describe('Parse.User testing', () => { }); Parse.Cloud.afterSave('_User', (request, response) => { - let authData = request.object.get('authData'); + const authData = request.object.get('authData'); expect(authData).not.toBeUndefined(); if (authData) { expect(authData.facebook.id).toEqual('8675309'); @@ -2326,7 +2326,7 @@ describe('Parse.User testing', () => { }); it_exclude_dbs(['postgres'])('should cleanup null authData keys (regression test for #935)', (done) => { - let database = new Config(Parse.applicationId).database; + const database = new Config(Parse.applicationId).database; database.create('_User', { username: 'user', _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie', @@ -2349,7 +2349,7 @@ describe('Parse.User testing', () => { }) }) }).then((user) => { - let authData = user.authData; + const authData = user.authData; expect(user.username).toEqual('user'); expect(authData).toBeUndefined(); done(); @@ -2360,7 +2360,7 @@ describe('Parse.User testing', () => { }); it_exclude_dbs(['postgres'])('should not serve null authData keys', (done) => { - let database = new Config(Parse.applicationId).database; + const database = new Config(Parse.applicationId).database; database.create('_User', { username: 'user', _hashed_password: '$2a$10$8/wZJyEuiEaobBBqzTG.jeY.XSFJd0rzaN//ososvEI4yLqI.4aie', @@ -2370,7 +2370,7 @@ describe('Parse.User testing', () => { .equalTo('username', 'user') .first({useMasterKey: true}); }).then((user) => { - let authData = user.get('authData'); + const authData = user.get('authData'); expect(user.get('username')).toEqual('user'); expect(authData).toBeUndefined(); done(); @@ -2570,7 +2570,7 @@ describe('Parse.User testing', () => { expect(req.object.get('username')).toEqual('User'); res.success(); }); - let user = new Parse.User() + const user = new Parse.User() user.setUsername('User'); user.setPassword('pass'); user.signUp().then(()=> { @@ -2587,7 +2587,7 @@ describe('Parse.User testing', () => { expect(req.user.get('han')).toEqual('solo'); res.success({}); }); - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('harrison'); user.setPassword('ford'); user.signUp().then(() => { @@ -2645,19 +2645,19 @@ describe('Parse.User testing', () => { }); it('should not create extraneous session tokens', (done) => { - let config = new Config(Parse.applicationId); + const config = new Config(Parse.applicationId); config.database.loadSchema().then((s) => { // Lock down the _User class for creation return s.addClassIfNotExists('_User', {}, {create: {}}) }).then(() => { - let user = new Parse.User(); + const user = new Parse.User(); return user.save({'username': 'user', 'password': 'pass'}); }).then(() => { fail('should not be able to save the user'); }, () => { return Promise.resolve(); }).then(() => { - let q = new Parse.Query('_Session'); + const q = new Parse.Query('_Session'); return q.find({useMasterKey: true}) }).then((res) => { // We should have no session created @@ -2713,7 +2713,7 @@ describe('Parse.User testing', () => { }, (err, res, body) => { Parse.User.become(body.sessionToken) .then(user => { - let obj = new Parse.Object('TestObject'); + const obj = new Parse.Object('TestObject'); obj.setACL(new Parse.ACL(user)); return obj.save() .then(() => { @@ -2751,7 +2751,7 @@ describe('Parse.User testing', () => { }, (err, res, body) => { Parse.User.become(body.sessionToken) .then(user => { - let obj = new Parse.Object('TestObject'); + const obj = new Parse.Object('TestObject'); obj.setACL(new Parse.ACL(user)); return obj.save() .then(() => { @@ -2769,7 +2769,7 @@ describe('Parse.User testing', () => { }); it('should not fail querying non existing relations', done => { - let user = new Parse.User(); + const user = new Parse.User(); user.set({ username: 'hello', password: 'world' diff --git a/spec/PointerPermissions.spec.js b/spec/PointerPermissions.spec.js index bde5b497ef..9eeae17e79 100644 --- a/spec/PointerPermissions.spec.js +++ b/spec/PointerPermissions.spec.js @@ -8,9 +8,9 @@ describe('Pointer Permissions', () => { }); it('should work with find', (done) => { - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -19,8 +19,8 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); - let obj2 = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); + const obj2 = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { obj.set('owner', user); @@ -33,7 +33,7 @@ describe('Pointer Permissions', () => { }).then(() => { return Parse.User.logIn('user1', 'password'); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.find(); }).then((res) => { expect(res.length).toBe(1); @@ -47,9 +47,9 @@ describe('Pointer Permissions', () => { it('should work with write', (done) => { - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -58,8 +58,8 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); - let obj2 = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); + const obj2 = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { obj.set('owner', user); @@ -91,7 +91,7 @@ describe('Pointer Permissions', () => { fail('User should be able to update'); return Promise.resolve(); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.find(); }, () => { fail('should login with user 2'); @@ -112,9 +112,9 @@ describe('Pointer Permissions', () => { }); it('should let a proper user find', (done) => { - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -123,8 +123,8 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); - let obj2 = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); + const obj2 = new Parse.Object('AnObject'); user.signUp().then(() => { return user2.signUp() }).then(() => { @@ -137,18 +137,18 @@ describe('Pointer Permissions', () => { return schema.updateClass('AnObject', {}, {find: {}, get:{}, readUserFields: ['owner']}) }); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.find(); }).then((res) => { expect(res.length).toBe(0); }).then(() => { return Parse.User.logIn('user2', 'password'); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.find(); }).then((res) => { expect(res.length).toBe(0); - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.get(obj.id); }).then(() => { fail('User 2 should not get the obj1 object'); @@ -159,7 +159,7 @@ describe('Pointer Permissions', () => { }).then(() => { return Parse.User.logIn('user1', 'password'); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.find(); }).then((res) => { expect(res.length).toBe(1); @@ -172,13 +172,13 @@ describe('Pointer Permissions', () => { }); it('should not allow creating objects', (done) => { - let config = new Config(Parse.applicationId); - let user = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); user.set({ username: 'user1', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); user.save().then(() => { return config.database.loadSchema().then((schema) => { return schema.addClassIfNotExists('AnObject', {owner: {type:'Pointer', targetClass: '_User'}}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']}); @@ -198,9 +198,9 @@ describe('Pointer Permissions', () => { }); it('should handle multiple writeUserFields', done => { - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -209,7 +209,7 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]) .then(() => { obj.set('owner', user); @@ -224,7 +224,7 @@ describe('Pointer Permissions', () => { .then(() => obj.save({hello: 'fromUser2'})) .then(() => Parse.User.logOut()) .then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.first(); }) .then(result => { @@ -237,7 +237,7 @@ describe('Pointer Permissions', () => { }); it('should prevent creating pointer permission on missing field', (done) => { - let config = new Config(Parse.applicationId); + const config = new Config(Parse.applicationId); config.database.loadSchema().then((schema) => { return schema.addClassIfNotExists('AnObject', {}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']}); }).then(() => { @@ -250,7 +250,7 @@ describe('Pointer Permissions', () => { }); it('should prevent creating pointer permission on bad field', (done) => { - let config = new Config(Parse.applicationId); + const config = new Config(Parse.applicationId); config.database.loadSchema().then((schema) => { return schema.addClassIfNotExists('AnObject', {owner: {type: 'String'}}, {create: {}, writeUserFields: ['owner'], readUserFields: ['owner']}); }).then(() => { @@ -263,8 +263,8 @@ describe('Pointer Permissions', () => { }); it('should prevent creating pointer permission on bad field', (done) => { - let config = new Config(Parse.applicationId); - let object = new Parse.Object('AnObject'); + const config = new Config(Parse.applicationId); + const object = new Parse.Object('AnObject'); object.set('owner', 'value'); object.save().then(() => { return config.database.loadSchema(); @@ -288,9 +288,9 @@ describe('Pointer Permissions', () => { The owner is another user than the ACL */ - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -299,9 +299,9 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { - let ACL = new Parse.ACL(); + const ACL = new Parse.ACL(); ACL.setReadAccess(user, true); ACL.setWriteAccess(user, true); obj.setACL(ACL); @@ -333,9 +333,9 @@ describe('Pointer Permissions', () => { PointerPerm: "owner" ACL: logged in user has access */ - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -344,9 +344,9 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { - let ACL = new Parse.ACL(); + const ACL = new Parse.ACL(); ACL.setReadAccess(user, true); ACL.setWriteAccess(user, true); obj.setACL(ACL); @@ -378,9 +378,9 @@ describe('Pointer Permissions', () => { PointerPerm: "owner" ACL: logged in user has access */ - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -389,9 +389,9 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { - let ACL = new Parse.ACL(); + const ACL = new Parse.ACL(); ACL.setWriteAccess(user, true); ACL.setWriteAccess(user2, true); obj.setACL(ACL); @@ -425,9 +425,9 @@ describe('Pointer Permissions', () => { The owner is another user than the ACL */ - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -436,9 +436,9 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { - let ACL = new Parse.ACL(); + const ACL = new Parse.ACL(); ACL.setReadAccess(user, true); ACL.setWriteAccess(user, true); obj.setACL(ACL); @@ -470,9 +470,9 @@ describe('Pointer Permissions', () => { PointerPerm: "owner" : read ACL: logged in user has access */ - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -481,9 +481,9 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { - let ACL = new Parse.ACL(); + const ACL = new Parse.ACL(); ACL.setReadAccess(user, true); ACL.setWriteAccess(user, true); ACL.setReadAccess(user2, true); @@ -517,9 +517,9 @@ describe('Pointer Permissions', () => { PointerPerm: "owner" : read // proper owner ACL: logged in user has not access */ - let config = new Config(Parse.applicationId); - let user = new Parse.User(); - let user2 = new Parse.User(); + const config = new Config(Parse.applicationId); + const user = new Parse.User(); + const user2 = new Parse.User(); user.set({ username: 'user1', password: 'password' @@ -528,9 +528,9 @@ describe('Pointer Permissions', () => { username: 'user2', password: 'password' }); - let obj = new Parse.Object('AnObject'); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, user2]).then(() => { - let ACL = new Parse.ACL(); + const ACL = new Parse.ACL(); ACL.setReadAccess(user, true); ACL.setWriteAccess(user, true); obj.setACL(ACL); @@ -556,8 +556,8 @@ describe('Pointer Permissions', () => { }); it('should let master key find objects', (done) => { - let config = new Config(Parse.applicationId); - let object = new Parse.Object('AnObject'); + const config = new Config(Parse.applicationId); + const object = new Parse.Object('AnObject'); object.set('hello', 'world'); return object.save().then(() => { return config.database.loadSchema().then((schema) => { @@ -565,7 +565,7 @@ describe('Pointer Permissions', () => { return schema.updateClass('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {find: {}, get: {}, readUserFields: ['owner']}); }); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.find(); }).then(() => { @@ -573,7 +573,7 @@ describe('Pointer Permissions', () => { expect(err.code).toBe(101); return Promise.resolve(); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.find({useMasterKey: true}); }).then((objects) => { expect(objects.length).toBe(1); @@ -585,8 +585,8 @@ describe('Pointer Permissions', () => { }); it('should let master key get objects', (done) => { - let config = new Config(Parse.applicationId); - let object = new Parse.Object('AnObject'); + const config = new Config(Parse.applicationId); + const object = new Parse.Object('AnObject'); object.set('hello', 'world'); return object.save().then(() => { return config.database.loadSchema().then((schema) => { @@ -594,7 +594,7 @@ describe('Pointer Permissions', () => { return schema.updateClass('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {find: {}, get: {}, readUserFields: ['owner']}); }); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.get(object.id); }).then(() => { @@ -602,7 +602,7 @@ describe('Pointer Permissions', () => { expect(err.code).toBe(101); return Promise.resolve(); }).then(() => { - let q = new Parse.Query('AnObject'); + const q = new Parse.Query('AnObject'); return q.get(object.id, {useMasterKey: true}); }).then((objectAgain) => { expect(objectAgain).not.toBeUndefined(); @@ -616,8 +616,8 @@ describe('Pointer Permissions', () => { it('should let master key update objects', (done) => { - let config = new Config(Parse.applicationId); - let object = new Parse.Object('AnObject'); + const config = new Config(Parse.applicationId); + const object = new Parse.Object('AnObject'); object.set('hello', 'world'); return object.save().then(() => { return config.database.loadSchema().then((schema) => { @@ -643,8 +643,8 @@ describe('Pointer Permissions', () => { }); it('should let master key delete objects', (done) => { - let config = new Config(Parse.applicationId); - let object = new Parse.Object('AnObject'); + const config = new Config(Parse.applicationId); + const object = new Parse.Object('AnObject'); object.set('hello', 'world'); return object.save().then(() => { return config.database.loadSchema().then((schema) => { @@ -669,7 +669,7 @@ describe('Pointer Permissions', () => { }); it('should fail with invalid pointer perms', (done) => { - let config = new Config(Parse.applicationId); + const config = new Config(Parse.applicationId); config.database.loadSchema().then((schema) => { // Lock the update, and let only owner write return schema.addClassIfNotExists('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {delete: {}, writeUserFields: 'owner'}); @@ -680,7 +680,7 @@ describe('Pointer Permissions', () => { }); it('should fail with invalid pointer perms', (done) => { - let config = new Config(Parse.applicationId); + const config = new Config(Parse.applicationId); config.database.loadSchema().then((schema) => { // Lock the update, and let only owner write return schema.addClassIfNotExists('AnObject', {owner: {type: 'Pointer', targetClass: '_User'}}, {delete: {}, writeUserFields: ['owner', 'invalid']}); diff --git a/spec/PushController.spec.js b/spec/PushController.spec.js index b5339d0dd8..bfe6517354 100644 --- a/spec/PushController.spec.js +++ b/spec/PushController.spec.js @@ -5,7 +5,7 @@ var Config = require('../src/Config'); const successfulTransmissions = function(body, installations) { - let promises = installations.map((device) => { + const promises = installations.map((device) => { return Promise.resolve({ transmitted: true, device: device, @@ -17,7 +17,7 @@ const successfulTransmissions = function(body, installations) { const successfulIOS = function(body, installations) { - let promises = installations.map((device) => { + const promises = installations.map((device) => { return Promise.resolve({ transmitted: device.deviceType == "ios", device: device, @@ -138,7 +138,7 @@ describe('PushController', () => { }} var installations = []; while(installations.length != 10) { - let installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_"+installations.length); installation.set("deviceToken","device_token_"+installations.length) installation.set("badge", installations.length); @@ -148,7 +148,7 @@ describe('PushController', () => { } while(installations.length != 15) { - let installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_"+installations.length); installation.set("deviceToken","device_token_"+installations.length) installation.set("deviceType", "android"); @@ -279,16 +279,16 @@ describe('PushController', () => { var pushController = new PushController(pushAdapter, Parse.applicationId, defaultConfiguration.push); Parse.Object.saveAll(installations).then((installations) => { - let objectIds = installations.map(installation => { + const objectIds = installations.map(installation => { return installation.id; }) - let where = { + const where = { objectId: {'$in': objectIds.slice(0, 5)} } return pushController.sendPush(payload, where, config, auth); }).then(() => { expect(matchedInstallationsCount).toBe(5); - let query = new Parse.Query(Parse.Installation); + const query = new Parse.Query(Parse.Installation); query.equalTo('badge', 1); return query.find({useMasterKey: true}); }).then((installations) => { @@ -304,7 +304,7 @@ describe('PushController', () => { var installations = []; while(installations.length != 10) { - let installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_"+installations.length); installation.set("deviceToken","device_token_"+installations.length) installation.set("badge", installations.length); @@ -314,7 +314,7 @@ describe('PushController', () => { } while(installations.length != 15) { - let installation = new Parse.Object("_Installation"); + const installation = new Parse.Object("_Installation"); installation.set("installationId", "installation_"+installations.length); installation.set("deviceToken","device_token_"+installations.length) installation.set("deviceType", "android"); @@ -349,11 +349,11 @@ describe('PushController', () => { }, 1000); }); }).then(() => { - let query = new Parse.Query('_PushStatus'); + const query = new Parse.Query('_PushStatus'); return query.find({useMasterKey: true}); }).then((results) => { expect(results.length).toBe(1); - let result = results[0]; + const result = results[0]; expect(result.createdAt instanceof Date).toBe(true); expect(result.updatedAt instanceof Date).toBe(true); expect(result.id.length).toBe(10); @@ -371,7 +371,7 @@ describe('PushController', () => { 'android': 5 // android }); // Try to get it without masterKey - let query = new Parse.Query('_PushStatus'); + const query = new Parse.Query('_PushStatus'); return query.find(); }).then((results) => { expect(results.length).toBe(0); @@ -393,7 +393,7 @@ describe('PushController', () => { return ["ios"]; } } - let where = { 'channels': { + const where = { 'channels': { '$ins': ['Giants', 'Mets'] }}; var payload = {data: { @@ -409,10 +409,10 @@ describe('PushController', () => { fail('should not succeed'); done(); }).catch(() => { - let query = new Parse.Query('_PushStatus'); + const query = new Parse.Query('_PushStatus'); query.find({useMasterKey: true}).then((results) => { expect(results.length).toBe(1); - let pushStatus = results[0]; + const pushStatus = results[0]; expect(pushStatus.get('status')).toBe('failed'); done(); }); @@ -439,7 +439,7 @@ describe('PushController', () => { isMaster: true } - let where = { + const where = { 'deviceToken': { '$inQuery': { 'where': { @@ -480,7 +480,7 @@ describe('PushController', () => { isMaster: true } - let where = { + const where = { 'deviceToken': { '$inQuery': { 'where': { diff --git a/spec/RestQuery.spec.js b/spec/RestQuery.spec.js index 745bf35915..87adce3992 100644 --- a/spec/RestQuery.spec.js +++ b/spec/RestQuery.spec.js @@ -173,7 +173,7 @@ describe('rest query', () => { 'X-Parse-REST-API-Key': 'rest' }; - let p0 = rp.get({ + const p0 = rp.get({ headers: headers, url: 'http://localhost:8378/1/classes/TestParameterEncode?' + querystring.stringify({ @@ -181,19 +181,19 @@ describe('rest query', () => { limit: 1 }).replace('=', '%3D'), }).then(fail, (response) => { - let error = response.error; + const error = response.error; var b = JSON.parse(error); expect(b.code).toEqual(Parse.Error.INVALID_QUERY); }); - let p1 = rp.get({ + const p1 = rp.get({ headers: headers, url: 'http://localhost:8378/1/classes/TestParameterEncode?' + querystring.stringify({ limit: 1 }).replace('=', '%3D'), }).then(fail, (response) => { - let error = response.error; + const error = response.error; var b = JSON.parse(error); expect(b.code).toEqual(Parse.Error.INVALID_QUERY); }); @@ -235,21 +235,21 @@ describe('rest query', () => { }); it('makes sure null pointers are handed correctly #2189', done => { - let object = new Parse.Object('AnObject'); - let anotherObject = new Parse.Object('AnotherObject'); + const object = new Parse.Object('AnObject'); + const anotherObject = new Parse.Object('AnotherObject'); anotherObject.save().then(() => { object.set('values', [null, null, anotherObject]); return object.save(); }).then(() => { - let query = new Parse.Query('AnObject'); + const query = new Parse.Query('AnObject'); query.include('values'); return query.first(); }).then((result) => { - let values = result.get('values'); + const values = result.get('values'); expect(values.length).toBe(3); let anotherObjectFound = false; let nullCounts = 0; - for(let value of values) { + for(const value of values) { if (value === null) { nullCounts++; } else if (value instanceof Parse.Object) { diff --git a/spec/RevocableSessionsUpgrade.spec.js b/spec/RevocableSessionsUpgrade.spec.js index 8589a73f17..0fccf51565 100644 --- a/spec/RevocableSessionsUpgrade.spec.js +++ b/spec/RevocableSessionsUpgrade.spec.js @@ -22,7 +22,7 @@ describe_only_db('mongo')('revocable sessions', () => { }); it('should upgrade legacy session token', done => { - let user = Parse.Object.fromJSON({ + const user = Parse.Object.fromJSON({ className: '_User', objectId: '1234567890', sessionToken: sessionToken @@ -49,7 +49,7 @@ describe_only_db('mongo')('revocable sessions', () => { }); it('should be able to become with revocable session token', done => { - let user = Parse.Object.fromJSON({ + const user = Parse.Object.fromJSON({ className: '_User', objectId: '1234567890', sessionToken: sessionToken diff --git a/spec/Schema.spec.js b/spec/Schema.spec.js index ca7b1fb65a..f80b7eb7fe 100644 --- a/spec/Schema.spec.js +++ b/spec/Schema.spec.js @@ -824,9 +824,9 @@ describe('SchemaController', () => { }); it('yields a proper schema mismatch error (#2661)', done => { - let anObject = new Parse.Object('AnObject'); - let anotherObject = new Parse.Object('AnotherObject'); - let someObject = new Parse.Object('SomeObject'); + const anObject = new Parse.Object('AnObject'); + const anotherObject = new Parse.Object('AnotherObject'); + const someObject = new Parse.Object('SomeObject'); Parse.Object.saveAll([anObject, anotherObject, someObject]).then(() => { anObject.set('pointer', anotherObject); return anObject.save(); @@ -844,8 +844,8 @@ describe('SchemaController', () => { }); it('yields a proper schema mismatch error bis (#2661)', done => { - let anObject = new Parse.Object('AnObject'); - let someObject = new Parse.Object('SomeObject'); + const anObject = new Parse.Object('AnObject'); + const someObject = new Parse.Object('SomeObject'); Parse.Object.saveAll([anObject, someObject]).then(() => { anObject.set('number', 1); return anObject.save(); @@ -863,8 +863,8 @@ describe('SchemaController', () => { }); it('yields a proper schema mismatch error ter (#2661)', done => { - let anObject = new Parse.Object('AnObject'); - let someObject = new Parse.Object('SomeObject'); + const anObject = new Parse.Object('AnObject'); + const someObject = new Parse.Object('SomeObject'); Parse.Object.saveAll([anObject, someObject]).then(() => { anObject.set('pointer', someObject); return anObject.save(); @@ -889,7 +889,7 @@ describe('SchemaController', () => { } function validateSchemaDataStructure(schemaData) { Object.keys(schemaData).forEach(className => { - let schema = schemaData[className]; + const schema = schemaData[className]; // Hooks has className... if (className != '_Hooks') { expect(schema.hasOwnProperty('className')).toBe(false); @@ -921,7 +921,7 @@ describe('Class Level Permissions for requiredAuth', () => { }); function createUser() { - let user = new Parse.User(); + const user = new Parse.User(); user.set("username", "hello"); user.set("password", "world"); return user.signUp(null); @@ -987,7 +987,7 @@ describe('Class Level Permissions for requiredAuth', () => { }).then(() => { return createUser(); }).then(() => { - let stuff = new Parse.Object('Stuff'); + const stuff = new Parse.Object('Stuff'); stuff.set('foo', 'bar'); return stuff.save(); }).then(() => { @@ -1010,7 +1010,7 @@ describe('Class Level Permissions for requiredAuth', () => { } }); }).then(() => { - let stuff = new Parse.Object('Stuff'); + const stuff = new Parse.Object('Stuff'); stuff.set('foo', 'bar'); return stuff.save(); }).then(() => { @@ -1044,10 +1044,10 @@ describe('Class Level Permissions for requiredAuth', () => { }).then(() => { return createUser(); }).then(() => { - let stuff = new Parse.Object('Stuff'); + const stuff = new Parse.Object('Stuff'); stuff.set('foo', 'bar'); return stuff.save().then(() => { - let query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.get(stuff.id); }); }).then((gotStuff) => { @@ -1083,10 +1083,10 @@ describe('Class Level Permissions for requiredAuth', () => { } }); }).then(() => { - let stuff = new Parse.Object('Stuff'); + const stuff = new Parse.Object('Stuff'); stuff.set('foo', 'bar'); return stuff.save().then(() => { - let query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.get(stuff.id); }); }).then(() => { @@ -1121,15 +1121,15 @@ describe('Class Level Permissions for requiredAuth', () => { } }); }).then(() => { - let stuff = new Parse.Object('Stuff'); + const stuff = new Parse.Object('Stuff'); stuff.set('foo', 'bar'); return stuff.save().then(() => { - let query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.get(stuff.id); }) }).then((result) => { expect(result.get('foo')).toEqual('bar'); - let query = new Parse.Query('Stuff'); + const query = new Parse.Query('Stuff'); return query.find(); }).then(() => { fail("Should not succeed!"); diff --git a/spec/TwitterAuth.spec.js b/spec/TwitterAuth.spec.js index c763393913..8cec73e494 100644 --- a/spec/TwitterAuth.spec.js +++ b/spec/TwitterAuth.spec.js @@ -1,4 +1,4 @@ -let twitter = require('../src/Adapters/Auth/twitter'); +const twitter = require('../src/Adapters/Auth/twitter'); describe('Twitter Auth', () => { it('should use the proper configuration', () => { diff --git a/spec/Uniqueness.spec.js b/spec/Uniqueness.spec.js index 36f0c6ad66..c7a159092d 100644 --- a/spec/Uniqueness.spec.js +++ b/spec/Uniqueness.spec.js @@ -1,19 +1,19 @@ 'use strict'; const Parse = require("parse/node"); -let Config = require('../src/Config'); +const Config = require('../src/Config'); describe('Uniqueness', function() { it('fail when create duplicate value in unique field', done => { - let obj = new Parse.Object('UniqueField'); + const obj = new Parse.Object('UniqueField'); obj.set('unique', 'value'); obj.save().then(() => { expect(obj.id).not.toBeUndefined(); - let config = new Config('test'); + const config = new Config('test'); return config.database.adapter.ensureUniqueness('UniqueField', { fields: { unique: { __type: 'String' } } }, ['unique']) }) .then(() => { - let obj = new Parse.Object('UniqueField'); + const obj = new Parse.Object('UniqueField'); obj.set('unique', 'value'); return obj.save() }).then(() => { @@ -26,18 +26,18 @@ describe('Uniqueness', function() { }); it('unique indexing works on pointer fields', done => { - let obj = new Parse.Object('UniquePointer'); + const obj = new Parse.Object('UniquePointer'); obj.save({ string: 'who cares' }) .then(() => obj.save({ ptr: obj })) .then(() => { - let config = new Config('test'); + const config = new Config('test'); return config.database.adapter.ensureUniqueness('UniquePointer', { fields: { string: { __type: 'String' }, ptr: { __type: 'Pointer', targetClass: 'UniquePointer' } } }, ['ptr']); }) .then(() => { - let newObj = new Parse.Object('UniquePointer') + const newObj = new Parse.Object('UniquePointer') newObj.set('ptr', obj) return newObj.save() }) @@ -52,13 +52,13 @@ describe('Uniqueness', function() { }); it('fails when attempting to ensure uniqueness of fields that are not currently unique', done => { - let o1 = new Parse.Object('UniqueFail'); + const o1 = new Parse.Object('UniqueFail'); o1.set('key', 'val'); - let o2 = new Parse.Object('UniqueFail'); + const o2 = new Parse.Object('UniqueFail'); o2.set('key', 'val'); Parse.Object.saveAll([o1, o2]) .then(() => { - let config = new Config('test'); + const config = new Config('test'); return config.database.adapter.ensureUniqueness('UniqueFail', { fields: { key: { __type: 'String' } } }, ['key']); }) .catch(error => { @@ -68,28 +68,28 @@ describe('Uniqueness', function() { }); it_exclude_dbs(['postgres'])('can do compound uniqueness', done => { - let config = new Config('test'); + const config = new Config('test'); config.database.adapter.ensureUniqueness('CompoundUnique', { fields: { k1: { __type: 'String' }, k2: { __type: 'String' } } }, ['k1', 'k2']) .then(() => { - let o1 = new Parse.Object('CompoundUnique'); + const o1 = new Parse.Object('CompoundUnique'); o1.set('k1', 'v1'); o1.set('k2', 'v2'); return o1.save(); }) .then(() => { - let o2 = new Parse.Object('CompoundUnique'); + const o2 = new Parse.Object('CompoundUnique'); o2.set('k1', 'v1'); o2.set('k2', 'not a dupe'); return o2.save(); }) .then(() => { - let o3 = new Parse.Object('CompoundUnique'); + const o3 = new Parse.Object('CompoundUnique'); o3.set('k1', 'not a dupe'); o3.set('k2', 'v2'); return o3.save(); }) .then(() => { - let o4 = new Parse.Object('CompoundUnique'); + const o4 = new Parse.Object('CompoundUnique'); o4.set('k1', 'v1'); o4.set('k2', 'v2'); return o4.save(); diff --git a/spec/ValidationAndPasswordsReset.spec.js b/spec/ValidationAndPasswordsReset.spec.js index 3976d39ebc..f32813fb7b 100644 --- a/spec/ValidationAndPasswordsReset.spec.js +++ b/spec/ValidationAndPasswordsReset.spec.js @@ -1,8 +1,8 @@ "use strict"; -let MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions'); -let request = require('request'); -let Config = require("../src/Config"); +const MockEmailAdapterWithOptions = require('./MockEmailAdapterWithOptions'); +const request = require('request'); +const Config = require("../src/Config"); describe("Custom Pages, Email Verification, Password Reset", () => { it("should set the custom pages", (done) => { @@ -251,7 +251,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }), }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set("email", "testInvalidConfig@parse.com"); @@ -338,7 +338,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }), }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set("email", "testInvalidConfig@parse.com"); @@ -370,7 +370,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }), }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set("email", "testInvalidConfig@parse.com"); @@ -401,7 +401,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }), }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set("email", "testInvalidConfig@parse.com"); @@ -429,7 +429,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { emailAdapter: undefined, }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set("email", "testInvalidConfig@parse.com"); @@ -461,7 +461,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }), }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("zxcv"); user.set("email", "testInvalidConfig@parse.com"); @@ -480,7 +480,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { }); it('succeeds sending a password reset username if appName, publicServerURL, and email adapter are prodvided', done => { - let adapter = MockEmailAdapterWithOptions({ + const adapter = MockEmailAdapterWithOptions({ fromAddress: 'parse@example.com', apiKey: 'k', domain: 'd', @@ -500,7 +500,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { emailAdapter: adapter }) .then(() => { - let user = new Parse.User(); + const user = new Parse.User(); user.setPassword("asdf"); user.setUsername("testValidConfig@parse.com"); user.signUp(null) @@ -819,7 +819,7 @@ describe("Custom Pages, Email Verification, Password Reset", () => { expect(response.body).toEqual('Found. Redirecting to http://localhost:8378/1/apps/password_reset_success.html?username=zxcv'); Parse.User.logIn("zxcv", "hello").then(function(){ - let config = new Config('test'); + const config = new Config('test'); config.database.adapter.find('_User', { fields: {} }, { 'username': 'zxcv' }, { limit: 1 }) .then(results => { // _perishable_token should be unset after reset password diff --git a/spec/WinstonLoggerAdapter.spec.js b/spec/WinstonLoggerAdapter.spec.js index b150620ae3..839fd58c7b 100644 --- a/spec/WinstonLoggerAdapter.spec.js +++ b/spec/WinstonLoggerAdapter.spec.js @@ -60,14 +60,14 @@ describe('verbose logs', () => { reconfigureServer({ verbose: true }) .then(() => createTestUser()) .then(() => { - let winstonLoggerAdapter = new WinstonLoggerAdapter(); + const winstonLoggerAdapter = new WinstonLoggerAdapter(); return winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), size: 100, level: 'verbose' }); }).then((results) => { - let logString = JSON.stringify(results); + const logString = JSON.stringify(results); expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0); expect(logString.match(/moon-y/g)).toBe(null); @@ -79,13 +79,13 @@ describe('verbose logs', () => { headers: headers, url: 'http://localhost:8378/1/login?username=test&password=moon-y' }, () => { - let winstonLoggerAdapter = new WinstonLoggerAdapter(); + const winstonLoggerAdapter = new WinstonLoggerAdapter(); return winstonLoggerAdapter.query({ from: new Date(Date.now() - 500), size: 100, level: 'verbose' }).then((results) => { - let logString = JSON.stringify(results); + const logString = JSON.stringify(results); expect(logString.match(/\*\*\*\*\*\*\*\*/g).length).not.toBe(0); expect(logString.match(/moon-y/g)).toBe(null); done(); diff --git a/spec/batch.spec.js b/spec/batch.spec.js index c4ae81f0af..5d30caab46 100644 --- a/spec/batch.spec.js +++ b/spec/batch.spec.js @@ -9,35 +9,35 @@ const publicServerURLNaked = 'http://domain.com/'; describe('batch', () => { it('should return the proper url', () => { - let internalURL = batch.makeBatchRoutingPathFunction(originalURL)('/parse/classes/Object'); + const internalURL = batch.makeBatchRoutingPathFunction(originalURL)('/parse/classes/Object'); expect(internalURL).toEqual('/classes/Object'); }); it('should return the proper url same public/local endpoint', () => { - let originalURL = '/parse/batch'; - let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURL)('/parse/classes/Object'); + const originalURL = '/parse/batch'; + const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURL)('/parse/classes/Object'); expect(internalURL).toEqual('/classes/Object'); }); it('should return the proper url with different public/local mount', () => { - let originalURL = '/parse/batch'; - let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL1, publicServerURL)('/parse/classes/Object'); + const originalURL = '/parse/batch'; + const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL1, publicServerURL)('/parse/classes/Object'); expect(internalURL).toEqual('/classes/Object'); }); it('should return the proper url with naked public', () => { - let originalURL = '/batch'; - let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURLNaked)('/classes/Object'); + const originalURL = '/batch'; + const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURL, publicServerURLNaked)('/classes/Object'); expect(internalURL).toEqual('/classes/Object'); }); it('should return the proper url with naked local', () => { - let originalURL = '/parse/batch'; - let internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURLNaked, publicServerURL)('/parse/classes/Object'); + const originalURL = '/parse/batch'; + const internalURL = batch.makeBatchRoutingPathFunction(originalURL, serverURLNaked, publicServerURL)('/parse/classes/Object'); expect(internalURL).toEqual('/classes/Object'); }); diff --git a/spec/helper.js b/spec/helper.js index d7edb9cc78..ff6efd5326 100644 --- a/spec/helper.js +++ b/spec/helper.js @@ -114,7 +114,7 @@ if (process.env.PARSE_SERVER_TEST_CACHE === 'redis') { defaultConfiguration.cacheAdapter = new RedisCacheAdapter(); } -let openConnections = {}; +const openConnections = {}; // Set up a default API server for testing with default configuration. var app = express(); @@ -125,7 +125,7 @@ app.use('/1', () => { }); var server = app.listen(port); server.on('connection', connection => { - let key = `${connection.remoteAddress}:${connection.remotePort}`; + const key = `${connection.remoteAddress}:${connection.remotePort}`; openConnections[key] = connection; connection.on('close', () => { delete openConnections[key] }); }); @@ -134,7 +134,7 @@ const reconfigureServer = changedConfiguration => { return new Promise((resolve, reject) => { server.close(() => { try { - let newConfiguration = Object.assign({}, defaultConfiguration, changedConfiguration, { + const newConfiguration = Object.assign({}, defaultConfiguration, changedConfiguration, { __indexBuildCompletionCallbackForTests: indexBuildPromise => indexBuildPromise.then(resolve, reject) }); cache.clear(); @@ -147,7 +147,7 @@ const reconfigureServer = changedConfiguration => { }); server = app.listen(port); server.on('connection', connection => { - let key = `${connection.remoteAddress}:${connection.remotePort}`; + const key = `${connection.remoteAddress}:${connection.remotePort}`; openConnections[key] = connection; connection.on('close', () => { delete openConnections[key] }); }); @@ -203,7 +203,7 @@ beforeEach(done => { }); afterEach(function(done) { - let afterLogOut = () => { + const afterLogOut = () => { if (Object.keys(openConnections).length > 0) { fail('There were open connections to the server left after the test finished'); } diff --git a/spec/index.spec.js b/spec/index.spec.js index d2b7b74687..74c207f7a4 100644 --- a/spec/index.spec.js +++ b/spec/index.spec.js @@ -207,7 +207,7 @@ describe('server', () => { it('can create a parse-server v2', done => { let objId; let server - let parseServer = ParseServer.ParseServer(Object.assign({}, + const parseServer = ParseServer.ParseServer(Object.assign({}, defaultConfiguration, { appId: "anOtherTestApp", masterKey: "anOtherTestMasterKey", @@ -216,16 +216,16 @@ describe('server', () => { promise .then(() => { expect(Parse.applicationId).toEqual("anOtherTestApp"); - let app = express(); + const app = express(); app.use('/parse', parseServer); server = app.listen(12667); - let obj = new Parse.Object("AnObject"); + const obj = new Parse.Object("AnObject"); return obj.save() }) .then(obj => { objId = obj.id; - let q = new Parse.Query("AnObject"); + const q = new Parse.Query("AnObject"); return q.first(); }) .then(obj => { diff --git a/spec/rest.spec.js b/spec/rest.spec.js index 0270cfc9b8..7b481fae81 100644 --- a/spec/rest.spec.js +++ b/spec/rest.spec.js @@ -7,7 +7,7 @@ var rest = require('../src/rest'); var request = require('request'); var config = new Config('test'); -let database = config.database; +const database = config.database; describe('rest create', () => { @@ -28,7 +28,7 @@ describe('rest create', () => { }); it('handles array, object, date', (done) => { - let now = new Date(); + const now = new Date(); var obj = { array: [1, 2, 3], object: {foo: 'bar'}, @@ -52,23 +52,23 @@ describe('rest create', () => { }); it('handles object and subdocument', done => { - let obj = { subdoc: {foo: 'bar', wu: 'tan'} }; + const obj = { subdoc: {foo: 'bar', wu: 'tan'} }; rest.create(config, auth.nobody(config), 'MyClass', obj) .then(() => database.adapter.find('MyClass', { fields: {} }, {}, {})) .then(results => { expect(results.length).toEqual(1); - let mob = results[0]; + const mob = results[0]; expect(typeof mob.subdoc).toBe('object'); expect(mob.subdoc.foo).toBe('bar'); expect(mob.subdoc.wu).toBe('tan'); expect(typeof mob.objectId).toEqual('string'); - let obj = { 'subdoc.wu': 'clan' }; + const obj = { 'subdoc.wu': 'clan' }; return rest.update(config, auth.nobody(config), 'MyClass', mob.objectId, obj) }) .then(() => database.adapter.find('MyClass', { fields: {} }, {}, {})) .then(results => { expect(results.length).toEqual(1); - let mob = results[0]; + const mob = results[0]; expect(typeof mob.subdoc).toBe('object'); expect(mob.subdoc.foo).toBe('bar'); expect(mob.subdoc.wu).toBe('clan'); @@ -267,7 +267,7 @@ describe('rest create', () => { }); it('stores pointers', done => { - let obj = { + const obj = { foo: 'bar', aPointer: { __type: 'Pointer', @@ -282,7 +282,7 @@ describe('rest create', () => { }}, {}, {})) .then(results => { expect(results.length).toEqual(1); - let output = results[0]; + const output = results[0]; expect(typeof output.foo).toEqual('string'); expect(typeof output._p_aPointer).toEqual('undefined'); expect(output._p_aPointer).toBeUndefined(); diff --git a/spec/schemas.spec.js b/spec/schemas.spec.js index 13daa1f99c..3e9561e455 100644 --- a/spec/schemas.spec.js +++ b/spec/schemas.spec.js @@ -23,7 +23,7 @@ var hasAllPODobject = () => { return obj; }; -let defaultClassLevelPermissions = { +const defaultClassLevelPermissions = { find: { '*': true }, @@ -1008,7 +1008,7 @@ describe('schemas', () => { it('should fail setting schema permissions with invalid key', done => { - let object = new Parse.Object('AClass'); + const object = new Parse.Object('AClass'); object.save().then(() => { request.put({ url: 'http://localhost:8378/1/schemas/AClass', @@ -1056,7 +1056,7 @@ describe('schemas', () => { } }, (error) => { expect(error).toEqual(null); - let object = new Parse.Object('AClass'); + const object = new Parse.Object('AClass'); object.set('hello', 'world'); return object.save().then(() => { fail('should not be able to add a field'); @@ -1085,7 +1085,7 @@ describe('schemas', () => { } }, (error) => { expect(error).toEqual(null); - let object = new Parse.Object('AClass'); + const object = new Parse.Object('AClass'); object.set('hello', 'world'); return object.save().then(() => { done(); @@ -1249,15 +1249,15 @@ describe('schemas', () => { } it('validate CLP 1', done => { - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('user'); user.setPassword('user'); - let admin = new Parse.User(); + const admin = new Parse.User(); admin.setUsername('admin'); admin.setPassword('admin'); - let role = new Parse.Role('admin', new Parse.ACL()); + const role = new Parse.Role('admin', new Parse.ACL()); setPermissionsOnClass('AClass', { 'find': { @@ -1270,11 +1270,11 @@ describe('schemas', () => { return role.save(null, {useMasterKey: true}); }).then(() => { return Parse.User.logIn('user', 'user').then(() => { - let obj = new Parse.Object('AClass'); + const obj = new Parse.Object('AClass'); return obj.save(null, {useMasterKey: true}); }) }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then(() => { fail('Use should hot be able to find!') }, (err) => { @@ -1284,7 +1284,7 @@ describe('schemas', () => { }).then(() => { return Parse.User.logIn('admin', 'admin'); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find(); }).then((results) => { expect(results.length).toBe(1); @@ -1296,15 +1296,15 @@ describe('schemas', () => { }); it('validate CLP 2', done => { - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('user'); user.setPassword('user'); - let admin = new Parse.User(); + const admin = new Parse.User(); admin.setUsername('admin'); admin.setPassword('admin'); - let role = new Parse.Role('admin', new Parse.ACL()); + const role = new Parse.Role('admin', new Parse.ACL()); setPermissionsOnClass('AClass', { 'find': { @@ -1317,11 +1317,11 @@ describe('schemas', () => { return role.save(null, {useMasterKey: true}); }).then(() => { return Parse.User.logIn('user', 'user').then(() => { - let obj = new Parse.Object('AClass'); + const obj = new Parse.Object('AClass'); return obj.save(null, {useMasterKey: true}); }) }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then(() => { fail('User should not be able to find!') }, (err) => { @@ -1337,7 +1337,7 @@ describe('schemas', () => { } }, true); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then((result) => { expect(result.length).toBe(1); }, () => { @@ -1347,7 +1347,7 @@ describe('schemas', () => { }).then(() => { return Parse.User.logIn('admin', 'admin'); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find(); }).then((results) => { expect(results.length).toBe(1); @@ -1359,15 +1359,15 @@ describe('schemas', () => { }); it('validate CLP 3', done => { - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('user'); user.setPassword('user'); - let admin = new Parse.User(); + const admin = new Parse.User(); admin.setUsername('admin'); admin.setPassword('admin'); - let role = new Parse.Role('admin', new Parse.ACL()); + const role = new Parse.Role('admin', new Parse.ACL()); setPermissionsOnClass('AClass', { 'find': { @@ -1380,11 +1380,11 @@ describe('schemas', () => { return role.save(null, {useMasterKey: true}); }).then(() => { return Parse.User.logIn('user', 'user').then(() => { - let obj = new Parse.Object('AClass'); + const obj = new Parse.Object('AClass'); return obj.save(null, {useMasterKey: true}); }) }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then(() => { fail('User should not be able to find!') }, (err) => { @@ -1395,7 +1395,7 @@ describe('schemas', () => { // delete all CLP return setPermissionsOnClass('AClass', null, true); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then((result) => { expect(result.length).toBe(1); }, () => { @@ -1405,7 +1405,7 @@ describe('schemas', () => { }).then(() => { return Parse.User.logIn('admin', 'admin'); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find(); }).then((results) => { expect(results.length).toBe(1); @@ -1417,15 +1417,15 @@ describe('schemas', () => { }); it('validate CLP 4', done => { - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('user'); user.setPassword('user'); - let admin = new Parse.User(); + const admin = new Parse.User(); admin.setUsername('admin'); admin.setPassword('admin'); - let role = new Parse.Role('admin', new Parse.ACL()); + const role = new Parse.Role('admin', new Parse.ACL()); setPermissionsOnClass('AClass', { 'find': { @@ -1438,11 +1438,11 @@ describe('schemas', () => { return role.save(null, {useMasterKey: true}); }).then(() => { return Parse.User.logIn('user', 'user').then(() => { - let obj = new Parse.Object('AClass'); + const obj = new Parse.Object('AClass'); return obj.save(null, {useMasterKey: true}); }) }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then(() => { fail('User should not be able to find!') }, (err) => { @@ -1461,7 +1461,7 @@ describe('schemas', () => { return Promise.resolve(); }) }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then(() => { fail('User should not be able to find!') }, (err) => { @@ -1471,7 +1471,7 @@ describe('schemas', () => { }).then(() => { return Parse.User.logIn('admin', 'admin'); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find(); }).then((results) => { expect(results.length).toBe(1); @@ -1483,25 +1483,25 @@ describe('schemas', () => { }); it('validate CLP 5', done => { - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('user'); user.setPassword('user'); - let user2 = new Parse.User(); + const user2 = new Parse.User(); user2.setUsername('user2'); user2.setPassword('user2'); - let admin = new Parse.User(); + const admin = new Parse.User(); admin.setUsername('admin'); admin.setPassword('admin'); - let role = new Parse.Role('admin', new Parse.ACL()); + const role = new Parse.Role('admin', new Parse.ACL()); Promise.resolve().then(() => { return Parse.Object.saveAll([user, user2, admin, role], {useMasterKey: true}); }).then(()=> { role.relation('users').add(admin); return role.save(null, {useMasterKey: true}).then(() => { - let perm = { + const perm = { find: {} }; // let the user find @@ -1510,11 +1510,11 @@ describe('schemas', () => { }) }).then(() => { return Parse.User.logIn('user', 'user').then(() => { - let obj = new Parse.Object('AClass'); + const obj = new Parse.Object('AClass'); return obj.save(); }) }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find().then((res) => { expect(res.length).toEqual(1); }, () => { @@ -1524,7 +1524,7 @@ describe('schemas', () => { }).then(() => { return Parse.User.logIn('admin', 'admin'); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find(); }).then(() => { fail("should not be able to read!"); @@ -1535,7 +1535,7 @@ describe('schemas', () => { }).then(() => { return Parse.User.logIn('user2', 'user2'); }).then(() => { - let query = new Parse.Query('AClass'); + const query = new Parse.Query('AClass'); return query.find(); }).then(() => { fail("should not be able to read!"); @@ -1557,13 +1557,13 @@ describe('schemas', () => { delete: {'*': true}, addField:{'*': true} }).then(() => { - let obj = new Parse.Object('AnObject'); - let anotherObject = new Parse.Object('AnotherObject'); + const obj = new Parse.Object('AnObject'); + const anotherObject = new Parse.Object('AnotherObject'); return obj.save({ anotherObject }) }).then(() => { - let query = new Parse.Query('AnObject'); + const query = new Parse.Query('AnObject'); query.include('anotherObject'); return query.find(); }).then((res) => { @@ -1625,11 +1625,11 @@ describe('schemas', () => { }); it("regression test for #1991", done => { - let user = new Parse.User(); + const user = new Parse.User(); user.setUsername('user'); user.setPassword('user'); - let role = new Parse.Role('admin', new Parse.ACL()); - let obj = new Parse.Object('AnObject'); + const role = new Parse.Role('admin', new Parse.ACL()); + const obj = new Parse.Object('AnObject'); Parse.Object.saveAll([user, role]).then(() => { role.relation('users').add(user); return role.save(null, {useMasterKey: true}); @@ -1648,7 +1648,7 @@ describe('schemas', () => { }).then(() => { return obj.destroy(); }).then(() => { - let query = new Parse.Query('AnObject'); + const query = new Parse.Query('AnObject'); return query.find(); }).then((results) => { expect(results.length).toBe(0); @@ -1661,8 +1661,8 @@ describe('schemas', () => { }); it('regression test for #2246', done => { - let profile = new Parse.Object('UserProfile'); - let user = new Parse.User(); + const profile = new Parse.Object('UserProfile'); + const user = new Parse.User(); function initialize() { return user.save({ username: 'user', @@ -1684,7 +1684,7 @@ describe('schemas', () => { }).then(() => { return Parse.User.logIn('user', 'password') }).then(() => { - let query = new Parse.Query('_User'); + const query = new Parse.Query('_User'); query.include('userProfile'); return query.get(user.id); }).then((user) => { diff --git a/src/AccountLockout.js b/src/AccountLockout.js index 7b56076336..17430e4b9c 100644 --- a/src/AccountLockout.js +++ b/src/AccountLockout.js @@ -11,7 +11,7 @@ export class AccountLockout { * set _failed_login_count to value */ _setFailedLoginCount(value) { - let query = { + const query = { username: this._user.username }; diff --git a/src/Adapters/Auth/index.js b/src/Adapters/Auth/index.js index c6bc0e0b22..a12136d1a2 100755 --- a/src/Adapters/Auth/index.js +++ b/src/Adapters/Auth/index.js @@ -57,11 +57,11 @@ function authDataValidator(adapter, appIds, options) { module.exports = function(authOptions = {}, enableAnonymousUsers = true) { let _enableAnonymousUsers = enableAnonymousUsers; - let setEnableAnonymousUsers = function(enable) { + const setEnableAnonymousUsers = function(enable) { _enableAnonymousUsers = enable; } // To handle the test cases on configuration - let getValidatorForProvider = function(provider) { + const getValidatorForProvider = function(provider) { if (provider === 'anonymous' && !_enableAnonymousUsers) { return; diff --git a/src/Adapters/Auth/twitter.js b/src/Adapters/Auth/twitter.js index 0eec82a6b9..87a0a738f8 100644 --- a/src/Adapters/Auth/twitter.js +++ b/src/Adapters/Auth/twitter.js @@ -28,7 +28,7 @@ function validateAppId() { function handleMultipleConfigurations(authData, options) { if (Array.isArray(options)) { - let consumer_key = authData.consumer_key; + const consumer_key = authData.consumer_key; if (!consumer_key) { logger.error('Twitter Auth', 'Multiple twitter configurations are available, by no consumer_key was sent by the client.'); throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Twitter auth is invalid for this user.'); diff --git a/src/Adapters/Cache/InMemoryCache.js b/src/Adapters/Cache/InMemoryCache.js index 2d44292a0a..38a0e0f39a 100644 --- a/src/Adapters/Cache/InMemoryCache.js +++ b/src/Adapters/Cache/InMemoryCache.js @@ -10,7 +10,7 @@ export class InMemoryCache { } get(key) { - let record = this.cache[key]; + const record = this.cache[key]; if (record == null) { return null; } diff --git a/src/Adapters/Cache/InMemoryCacheAdapter.js b/src/Adapters/Cache/InMemoryCacheAdapter.js index a0832ed521..d540c18dd9 100644 --- a/src/Adapters/Cache/InMemoryCacheAdapter.js +++ b/src/Adapters/Cache/InMemoryCacheAdapter.js @@ -8,7 +8,7 @@ export class InMemoryCacheAdapter { get(key) { return new Promise((resolve) => { - let record = this.cache.get(key); + const record = this.cache.get(key); if (record == null) { return resolve(null); } diff --git a/src/Adapters/Files/GridStoreAdapter.js b/src/Adapters/Files/GridStoreAdapter.js index 82cc73937c..6814297036 100644 --- a/src/Adapters/Files/GridStoreAdapter.js +++ b/src/Adapters/Files/GridStoreAdapter.js @@ -30,7 +30,7 @@ export class GridStoreAdapter extends FilesAdapter { // Returns a promise createFile(filename: string, data) { return this._connect().then(database => { - let gridStore = new GridStore(database, filename, 'w'); + const gridStore = new GridStore(database, filename, 'w'); return gridStore.open(); }).then(gridStore => { return gridStore.write(data); @@ -41,7 +41,7 @@ export class GridStoreAdapter extends FilesAdapter { deleteFile(filename: string) { return this._connect().then(database => { - let gridStore = new GridStore(database, filename, 'r'); + const gridStore = new GridStore(database, filename, 'r'); return gridStore.open(); }).then((gridStore) => { return gridStore.unlink(); @@ -54,7 +54,7 @@ export class GridStoreAdapter extends FilesAdapter { return this._connect().then(database => { return GridStore.exist(database, filename) .then(() => { - let gridStore = new GridStore(database, filename, 'r'); + const gridStore = new GridStore(database, filename, 'r'); return gridStore.open(); }); }).then(gridStore => { @@ -69,7 +69,7 @@ export class GridStoreAdapter extends FilesAdapter { getFileStream(filename: string) { return this._connect().then(database => { return GridStore.exist(database, filename).then(() => { - let gridStore = new GridStore(database, filename, 'r'); + const gridStore = new GridStore(database, filename, 'r'); return gridStore.open(); }); }); diff --git a/src/Adapters/Logger/WinstonLogger.js b/src/Adapters/Logger/WinstonLogger.js index 8ec4382515..4be388489f 100644 --- a/src/Adapters/Logger/WinstonLogger.js +++ b/src/Adapters/Logger/WinstonLogger.js @@ -9,9 +9,9 @@ const logger = new winston.Logger(); const additionalTransports = []; function updateTransports(options) { - let transports = Object.assign({}, logger.transports); + const transports = Object.assign({}, logger.transports); if (options) { - let silent = options.silent; + const silent = options.silent; delete options.silent; if (_.isNull(options.dirname)) { delete transports['parse-server']; @@ -84,8 +84,8 @@ export function addTransport(transport) { } export function removeTransport(transport) { - let transportName = typeof transport == 'string' ? transport : transport.name; - let transports = Object.assign({}, logger.transports); + const transportName = typeof transport == 'string' ? transport : transport.name; + const transports = Object.assign({}, logger.transports); delete transports[transportName]; logger.configure({ transports: _.values(transports) diff --git a/src/Adapters/Logger/WinstonLoggerAdapter.js b/src/Adapters/Logger/WinstonLoggerAdapter.js index c95e962616..70616bbd56 100644 --- a/src/Adapters/Logger/WinstonLoggerAdapter.js +++ b/src/Adapters/Logger/WinstonLoggerAdapter.js @@ -28,11 +28,11 @@ export class WinstonLoggerAdapter extends LoggerAdapter { options = {}; } // defaults to 7 days prior - let from = options.from || new Date(Date.now() - (7 * MILLISECONDS_IN_A_DAY)); - let until = options.until || new Date(); - let limit = options.size || 10; - let order = options.order || 'desc'; - let level = options.level || 'info'; + const from = options.from || new Date(Date.now() - (7 * MILLISECONDS_IN_A_DAY)); + const until = options.until || new Date(); + const limit = options.size || 10; + const order = options.order || 'desc'; + const level = options.level || 'info'; const queryOptions = { from, diff --git a/src/Adapters/PubSub/EventEmitterPubSub.js b/src/Adapters/PubSub/EventEmitterPubSub.js index 7318d082f0..f81388192b 100644 --- a/src/Adapters/PubSub/EventEmitterPubSub.js +++ b/src/Adapters/PubSub/EventEmitterPubSub.js @@ -1,6 +1,6 @@ import events from 'events'; -let emitter = new events.EventEmitter(); +const emitter = new events.EventEmitter(); class Publisher { emitter: any; @@ -25,7 +25,7 @@ class Subscriber extends events.EventEmitter { } subscribe(channel: string): void { - let handler = (message) => { + const handler = (message) => { this.emit('message', channel, message); } this.subscriptions.set(channel, handler); @@ -49,7 +49,7 @@ function createSubscriber(): any { return new Subscriber(emitter); } -let EventEmitterPubSub = { +const EventEmitterPubSub = { createPublisher, createSubscriber } diff --git a/src/Adapters/Storage/Mongo/MongoCollection.js b/src/Adapters/Storage/Mongo/MongoCollection.js index 37b30bc9ea..bf21df5dac 100644 --- a/src/Adapters/Storage/Mongo/MongoCollection.js +++ b/src/Adapters/Storage/Mongo/MongoCollection.js @@ -1,5 +1,5 @@ -let mongodb = require('mongodb'); -let Collection = mongodb.Collection; +const mongodb = require('mongodb'); +const Collection = mongodb.Collection; export default class MongoCollection { _mongoCollection:Collection; @@ -21,7 +21,7 @@ export default class MongoCollection { throw error; } // Figure out what key needs an index - let key = error.message.match(/field=([A-Za-z_0-9]+) /)[1]; + const key = error.message.match(/field=([A-Za-z_0-9]+) /)[1]; if (!key) { throw error; } @@ -50,7 +50,7 @@ export default class MongoCollection { } count(query, { skip, limit, sort, maxTimeMS } = {}) { - let countOperation = this._mongoCollection.count(query, { skip, limit, sort, maxTimeMS }); + const countOperation = this._mongoCollection.count(query, { skip, limit, sort, maxTimeMS }); return countOperation; } diff --git a/src/Adapters/Storage/Mongo/MongoSchemaCollection.js b/src/Adapters/Storage/Mongo/MongoSchemaCollection.js index 1a6f028876..e6dbd4ae18 100644 --- a/src/Adapters/Storage/Mongo/MongoSchemaCollection.js +++ b/src/Adapters/Storage/Mongo/MongoSchemaCollection.js @@ -73,7 +73,7 @@ function mongoSchemaToParseSchema(mongoSchema) { } function _mongoSchemaQueryFromNameQuery(name: string, query) { - let object = { _id: name }; + const object = { _id: name }; if (query) { Object.keys(query).forEach(key => { object[key] = query[key]; diff --git a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js index 940e371208..6f1fc59fc9 100644 --- a/src/Adapters/Storage/Mongo/MongoStorageAdapter.js +++ b/src/Adapters/Storage/Mongo/MongoStorageAdapter.js @@ -15,8 +15,8 @@ import Parse from 'parse/node'; import _ from 'lodash'; import defaults from '../../../defaults'; -let mongodb = require('mongodb'); -let MongoClient = mongodb.MongoClient; +const mongodb = require('mongodb'); +const MongoClient = mongodb.MongoClient; const MongoSchemaCollectionName = '_SCHEMA'; @@ -53,14 +53,14 @@ const convertParseSchemaToMongoSchema = ({...schema}) => { // Returns { code, error } if invalid, or { result }, an object // suitable for inserting into _SCHEMA collection, otherwise. const mongoSchemaFromFieldsAndClassNameAndCLP = (fields, className, classLevelPermissions) => { - let mongoObject = { + const mongoObject = { _id: className, objectId: 'string', updatedAt: 'string', createdAt: 'string' }; - for (let fieldName in fields) { + for (const fieldName in fields) { mongoObject[fieldName] = MongoSchemaCollection.parseFieldTypeToMongoFieldType(fields[fieldName]); } @@ -157,7 +157,7 @@ export class MongoStorageAdapter { createClass(className, schema) { schema = convertParseSchemaToMongoSchema(schema); - let mongoObject = mongoSchemaFromFieldsAndClassNameAndCLP(schema.fields, className, schema.classLevelPermissions); + const mongoObject = mongoSchemaFromFieldsAndClassNameAndCLP(schema.fields, className, schema.classLevelPermissions); mongoObject._id = className; return this._schemaCollection() .then(schemaCollection => schemaCollection._collection.insertOne(mongoObject)) @@ -282,7 +282,7 @@ export class MongoStorageAdapter { schema = convertParseSchemaToMongoSchema(schema); return this._adaptiveCollection(className) .then(collection => { - let mongoWhere = transformWhere(className, query, schema); + const mongoWhere = transformWhere(className, query, schema); return collection.deleteMany(mongoWhere) }) .then(({ result }) => { @@ -327,9 +327,9 @@ export class MongoStorageAdapter { // Executes a find. Accepts: className, query in Parse format, and { skip, limit, sort }. find(className, schema, query, { skip, limit, sort, keys }) { schema = convertParseSchemaToMongoSchema(schema); - let mongoWhere = transformWhere(className, query, schema); - let mongoSort = _.mapKeys(sort, (value, fieldName) => transformKey(className, fieldName, schema)); - let mongoKeys = _.reduce(keys, (memo, key) => { + const mongoWhere = transformWhere(className, query, schema); + const mongoSort = _.mapKeys(sort, (value, fieldName) => transformKey(className, fieldName, schema)); + const mongoKeys = _.reduce(keys, (memo, key) => { memo[transformKey(className, key, schema)] = 1; return memo; }, {}); @@ -351,8 +351,8 @@ export class MongoStorageAdapter { // which is why we use sparse indexes. ensureUniqueness(className, schema, fieldNames) { schema = convertParseSchemaToMongoSchema(schema); - let indexCreationRequest = {}; - let mongoFieldNames = fieldNames.map(fieldName => transformKey(className, fieldName, schema)); + const indexCreationRequest = {}; + const mongoFieldNames = fieldNames.map(fieldName => transformKey(className, fieldName, schema)); mongoFieldNames.forEach(fieldName => { indexCreationRequest[fieldName] = 1; }); diff --git a/src/Adapters/Storage/Mongo/MongoTransform.js b/src/Adapters/Storage/Mongo/MongoTransform.js index 771e47d099..6b1fe1ce43 100644 --- a/src/Adapters/Storage/Mongo/MongoTransform.js +++ b/src/Adapters/Storage/Mongo/MongoTransform.js @@ -243,9 +243,9 @@ function transformQueryKeyValue(className, key, value, schema) { // restWhere is the "where" clause in REST API form. // Returns the mongo form of the query. function transformWhere(className, restWhere, schema) { - let mongoWhere = {}; - for (let restKey in restWhere) { - let out = transformQueryKeyValue(className, restKey, restWhere[restKey], schema); + const mongoWhere = {}; + for (const restKey in restWhere) { + const out = transformQueryKeyValue(className, restKey, restWhere[restKey], schema); mongoWhere[out.key] = out.value; } return mongoWhere; @@ -331,12 +331,12 @@ const parseObjectKeyValueToMongoObjectKeyValue = (restKey, restValue, schema) => const parseObjectToMongoObjectForCreate = (className, restCreate, schema) => { restCreate = addLegacyACL(restCreate); - let mongoCreate = {} - for (let restKey in restCreate) { + const mongoCreate = {} + for (const restKey in restCreate) { if (restCreate[restKey] && restCreate[restKey].__type === 'Relation') { continue; } - let { key, value } = parseObjectKeyValueToMongoObjectKeyValue( + const { key, value } = parseObjectKeyValueToMongoObjectKeyValue( restKey, restCreate[restKey], schema @@ -361,8 +361,8 @@ const parseObjectToMongoObjectForCreate = (className, restCreate, schema) => { // Main exposed method to help update old objects. const transformUpdate = (className, restUpdate, parseFormatSchema) => { - let mongoUpdate = {}; - let acl = addLegacyACL(restUpdate); + const mongoUpdate = {}; + const acl = addLegacyACL(restUpdate); if (acl._rperm || acl._wperm || acl._acl) { mongoUpdate.$set = {}; if (acl._rperm) { @@ -398,8 +398,8 @@ const transformUpdate = (className, restUpdate, parseFormatSchema) => { // Add the legacy _acl format. const addLegacyACL = restObject => { - let restObjectCopy = {...restObject}; - let _acl = {}; + const restObjectCopy = {...restObject}; + const _acl = {}; if (restObject._wperm) { restObject._wperm.forEach(entry => { @@ -532,12 +532,12 @@ function transformConstraint(constraint, inArray) { case '$in': case '$nin': { - let arr = constraint[key]; + const arr = constraint[key]; if (!(arr instanceof Array)) { throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad ' + key + ' value'); } answer[key] = arr.map(value => { - let result = inArray ? transformInteriorAtom(value) : transformTopLevelAtom(value); + const result = inArray ? transformInteriorAtom(value) : transformTopLevelAtom(value); if (result === CannotTransform) { throw new Parse.Error(Parse.Error.INVALID_JSON, `bad atom: ${value}`); } @@ -546,7 +546,7 @@ function transformConstraint(constraint, inArray) { break; } case '$all': { - let arr = constraint[key]; + const arr = constraint[key]; if (!(arr instanceof Array)) { throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad ' + key + ' value'); @@ -761,7 +761,7 @@ const mongoObjectToParseObject = (className, mongoObject, schema) => { return BytesCoder.databaseToJSON(mongoObject); } - let restObject = {}; + const restObject = {}; if (mongoObject._rperm || mongoObject._wperm) { restObject._rperm = mongoObject._rperm || []; restObject._wperm = mongoObject._wperm || []; @@ -861,7 +861,7 @@ const mongoObjectToParseObject = (className, mongoObject, schema) => { } const relationFieldNames = Object.keys(schema.fields).filter(fieldName => schema.fields[fieldName].type === 'Relation'); - let relationFields = {}; + const relationFields = {}; relationFieldNames.forEach(relationFieldName => { relationFields[relationFieldName] = { __type: 'Relation', diff --git a/src/Adapters/Storage/Postgres/PostgresClient.js b/src/Adapters/Storage/Postgres/PostgresClient.js index 59316b9e2a..0f4b3c8d52 100644 --- a/src/Adapters/Storage/Postgres/PostgresClient.js +++ b/src/Adapters/Storage/Postgres/PostgresClient.js @@ -2,7 +2,6 @@ const pgp = require('pg-promise')(); const parser = require('./PostgresConfigParser'); export function createClient(uri, databaseOptions) { - let client; let dbOptions = {}; databaseOptions = databaseOptions || {}; @@ -14,7 +13,7 @@ export function createClient(uri, databaseOptions) { dbOptions[key] = databaseOptions[key]; } - client = pgp(dbOptions); + const client = pgp(dbOptions); if (dbOptions.pgOptions) { for (const key in dbOptions.pgOptions) { diff --git a/src/Adapters/Storage/Postgres/PostgresStorageAdapter.js b/src/Adapters/Storage/Postgres/PostgresStorageAdapter.js index eae4b37fb8..194c693886 100644 --- a/src/Adapters/Storage/Postgres/PostgresStorageAdapter.js +++ b/src/Adapters/Storage/Postgres/PostgresStorageAdapter.js @@ -11,7 +11,7 @@ const logger = require('../../../logger'); const debug = function(){ let args = [...arguments]; args = ['PG: '+arguments[0]].concat(args.slice(1, args.length)); - let log = logger.getLogger(); + const log = logger.getLogger(); log.debug.apply(log, args); } @@ -116,8 +116,8 @@ const toPostgresSchema = (schema) => { const handleDotFields = (object) => { Object.keys(object).forEach(fieldName => { if (fieldName.indexOf('.') > -1) { - let components = fieldName.split('.'); - let first = components.shift(); + const components = fieldName.split('.'); + const first = components.shift(); object[first] = object[first] || {}; let currentObj = object[first]; let next; @@ -156,7 +156,7 @@ const validateKeys = (object) => { // Returns the list of join tables on a schema const joinTablesForSchema = (schema) => { - let list = []; + const list = []; if (schema) { Object.keys(schema.fields).forEach((field) => { if (schema.fields[field].type === 'Relation') { @@ -168,17 +168,17 @@ const joinTablesForSchema = (schema) => { } const buildWhereClause = ({ schema, query, index }) => { - let patterns = []; + const patterns = []; let values = []; - let sorts = []; + const sorts = []; schema = toPostgresSchema(schema); - for (let fieldName in query) { - let isArrayField = schema.fields + for (const fieldName in query) { + const isArrayField = schema.fields && schema.fields[fieldName] && schema.fields[fieldName].type === 'Array'; - let initialPatternsLength = patterns.length; - let fieldValue = query[fieldName]; + const initialPatternsLength = patterns.length; + const fieldValue = query[fieldName]; // nothingin the schema, it's gonna blow up if (!schema.fields[fieldName]) { @@ -189,7 +189,7 @@ const buildWhereClause = ({ schema, query, index }) => { } if (fieldName.indexOf('.') >= 0) { - let components = fieldName.split('.').map((cmpt, index) => { + const components = fieldName.split('.').map((cmpt, index) => { if (index === 0) { return `"${cmpt}"`; } @@ -211,17 +211,17 @@ const buildWhereClause = ({ schema, query, index }) => { values.push(fieldName, fieldValue); index += 2; } else if (fieldName === '$or' || fieldName === '$and') { - let clauses = []; - let clauseValues = []; + const clauses = []; + const clauseValues = []; fieldValue.forEach((subQuery) => { - let clause = buildWhereClause({ schema, query: subQuery, index }); + const clause = buildWhereClause({ schema, query: subQuery, index }); if (clause.pattern.length > 0) { clauses.push(clause.pattern); clauseValues.push(...clause.values); index += clause.values.length; } }); - let orOrAnd = fieldName === '$or' ? ' OR ' : ' AND '; + const orOrAnd = fieldName === '$or' ? ' OR ' : ' AND '; patterns.push(`(${clauses.join(orOrAnd)})`); values.push(...clauseValues); } @@ -254,7 +254,7 @@ const buildWhereClause = ({ schema, query, index }) => { isArrayField && schema.fields[fieldName].contents && schema.fields[fieldName].contents.type === 'String') { - let inPatterns = []; + const inPatterns = []; let allowNull = false; values.push(fieldName); fieldValue.$in.forEach((listElem, listIndex) => { @@ -274,13 +274,13 @@ const buildWhereClause = ({ schema, query, index }) => { } else if (isInOrNin) { var createConstraint = (baseArray, notIn) => { if (baseArray.length > 0) { - let not = notIn ? ' NOT ' : ''; + const not = notIn ? ' NOT ' : ''; if (isArrayField) { patterns.push(`${not} array_contains($${index}:name, $${index+1})`); values.push(fieldName, JSON.stringify(baseArray)); index += 2; } else { - let inPatterns = []; + const inPatterns = []; values.push(fieldName); baseArray.forEach((listElem, listIndex) => { values.push(listElem); @@ -320,9 +320,9 @@ const buildWhereClause = ({ schema, query, index }) => { } if (fieldValue.$nearSphere) { - let point = fieldValue.$nearSphere; - let distance = fieldValue.$maxDistance; - let distanceInKM = distance*6371*1000; + const point = fieldValue.$nearSphere; + const distance = fieldValue.$maxDistance; + const distanceInKM = distance*6371*1000; patterns.push(`ST_distance_sphere($${index}:name::geometry, POINT($${index+1}, $${index+2})::geometry) <= $${index+3}`); sorts.push(`ST_distance_sphere($${index}:name::geometry, POINT($${index+1}, $${index+2})::geometry) ASC`) values.push(fieldName, point.longitude, point.latitude, distanceInKM); @@ -330,11 +330,11 @@ const buildWhereClause = ({ schema, query, index }) => { } if (fieldValue.$within && fieldValue.$within.$box) { - let box = fieldValue.$within.$box; - let left = box[0].longitude; - let bottom = box[0].latitude; - let right = box[1].longitude; - let top = box[1].latitude; + const box = fieldValue.$within.$box; + const left = box[0].longitude; + const bottom = box[0].latitude; + const right = box[1].longitude; + const top = box[1].latitude; patterns.push(`$${index}:name::point <@ $${index+1}::box`); values.push(fieldName, `((${left}, ${bottom}), (${right}, ${top}))`); @@ -344,7 +344,7 @@ const buildWhereClause = ({ schema, query, index }) => { if (fieldValue.$regex) { let regex = fieldValue.$regex; let operator = '~'; - let opts = fieldValue.$options; + const opts = fieldValue.$options; if (opts) { if (opts.indexOf('i') >= 0) { operator = '~*'; @@ -381,7 +381,7 @@ const buildWhereClause = ({ schema, query, index }) => { Object.keys(ParseToPosgresComparator).forEach(cmp => { if (fieldValue[cmp]) { - let pgComparator = ParseToPosgresComparator[cmp]; + const pgComparator = ParseToPosgresComparator[cmp]; patterns.push(`$${index}:name ${pgComparator} $${index + 1}`); values.push(fieldName, toPostgresValue(fieldValue[cmp])); index += 2; @@ -461,9 +461,9 @@ export class PostgresStorageAdapter { createTable(className, schema, conn) { conn = conn || this._client; debug('createTable', className, schema); - let valuesArray = []; - let patternsArray = []; - let fields = Object.assign({}, schema.fields); + const valuesArray = []; + const patternsArray = []; + const fields = Object.assign({}, schema.fields); if (className === '_User') { fields._email_verify_token_expires_at = {type: 'Date'}; fields._email_verify_token = {type: 'String'}; @@ -475,9 +475,9 @@ export class PostgresStorageAdapter { fields._password_history = { type: 'Array'}; } let index = 2; - let relations = []; + const relations = []; Object.keys(fields).forEach((fieldName) => { - let parseType = fields[fieldName]; + const parseType = fields[fieldName]; // Skip when it's a relation // We'll create the tables later if (parseType.type === 'Relation') { @@ -557,7 +557,7 @@ export class PostgresStorageAdapter { // and resolves with false if it wasn't (eg. a join table). Rejects if deletion was impossible. deleteClass(className) { return Promise.resolve().then(() => { - let operations = [[`DROP TABLE IF EXISTS $1:name`, [className]], + const operations = [[`DROP TABLE IF EXISTS $1:name`, [className]], [`DELETE FROM "_SCHEMA" WHERE "className"=$1`, [className]]]; return this._client.tx(t=>t.batch(operations.map(statement=>t.none(statement[0], statement[1])))); }).then(() => { @@ -568,11 +568,11 @@ export class PostgresStorageAdapter { // Delete all data known to this adapter. Used for testing. deleteAllClasses() { - let now = new Date().getTime(); + const now = new Date().getTime(); debug('deleteAllClasses'); return this._client.any('SELECT * FROM "_SCHEMA"') .then(results => { - let joins = results.reduce((list, schema) => { + const joins = results.reduce((list, schema) => { return list.concat(joinTablesForSchema(schema.schema)); }, []); const classes = ['_SCHEMA','_PushStatus','_JobStatus','_Hooks','_GlobalConfig', ...results.map(result => result.className), ...joins]; @@ -607,7 +607,7 @@ export class PostgresStorageAdapter { return Promise.resolve() .then(() => { fieldNames = fieldNames.reduce((list, fieldName) => { - let field = schema.fields[fieldName] + const field = schema.fields[fieldName] if (field.type !== 'Relation') { list.push(fieldName); } @@ -615,13 +615,13 @@ export class PostgresStorageAdapter { return list; }, []); - let values = [className, ...fieldNames]; - let columns = fieldNames.map((name, idx) => { + const values = [className, ...fieldNames]; + const columns = fieldNames.map((name, idx) => { return `$${idx+2}:name`; }).join(','); - let doBatch = (t) => { - let batch = [ + const doBatch = (t) => { + const batch = [ t.none('UPDATE "_SCHEMA" SET "schema"=$ WHERE "className"=$', {schema, className}) ]; if (values.length > 1) { @@ -663,9 +663,9 @@ export class PostgresStorageAdapter { createObject(className, schema, object) { debug('createObject', className, object); let columnsArray = []; - let valuesArray = []; + const valuesArray = []; schema = toPostgresSchema(schema); - let geoPoints = {}; + const geoPoints = {}; object = handleDotFields(object); @@ -747,9 +747,9 @@ export class PostgresStorageAdapter { }); columnsArray = columnsArray.concat(Object.keys(geoPoints)); - let initialValues = valuesArray.map((val, index) => { + const initialValues = valuesArray.map((val, index) => { let termination = ''; - let fieldName = columnsArray[index]; + const fieldName = columnsArray[index]; if (['_rperm','_wperm'].indexOf(fieldName) >= 0) { termination = '::text[]'; } else if (schema.fields[fieldName] && schema.fields[fieldName].type === 'Array') { @@ -757,18 +757,18 @@ export class PostgresStorageAdapter { } return `$${index + 2 + columnsArray.length}${termination}`; }); - let geoPointsInjects = Object.keys(geoPoints).map((key) => { - let value = geoPoints[key]; + const geoPointsInjects = Object.keys(geoPoints).map((key) => { + const value = geoPoints[key]; valuesArray.push(value.longitude, value.latitude); - let l = valuesArray.length + columnsArray.length; + const l = valuesArray.length + columnsArray.length; return `POINT($${l}, $${l+1})`; }); - let columnsPattern = columnsArray.map((col, index) => `$${index + 2}:name`).join(','); - let valuesPattern = initialValues.concat(geoPointsInjects).join(',') + const columnsPattern = columnsArray.map((col, index) => `$${index + 2}:name`).join(','); + const valuesPattern = initialValues.concat(geoPointsInjects).join(',') - let qs = `INSERT INTO $1:name (${columnsPattern}) VALUES (${valuesPattern})` - let values = [className, ...columnsArray, ...valuesArray] + const qs = `INSERT INTO $1:name (${columnsPattern}) VALUES (${valuesPattern})` + const values = [className, ...columnsArray, ...valuesArray] debug(qs, values); return this._client.any(qs, values) .then(() => ({ ops: [object] })) @@ -786,14 +786,14 @@ export class PostgresStorageAdapter { // If there is some other error, reject with INTERNAL_SERVER_ERROR. deleteObjectsByQuery(className, schema, query) { debug('deleteObjectsByQuery', className, query); - let values = [className]; - let index = 2; - let where = buildWhereClause({ schema, index, query }) + const values = [className]; + const index = 2; + const where = buildWhereClause({ schema, index, query }) values.push(...where.values); if (Object.keys(query).length === 0) { where.pattern = 'TRUE'; } - let qs = `WITH deleted AS (DELETE FROM $1:name WHERE ${where.pattern} RETURNING *) SELECT count(*) FROM deleted`; + const qs = `WITH deleted AS (DELETE FROM $1:name WHERE ${where.pattern} RETURNING *) SELECT count(*) FROM deleted`; debug(qs, values); return this._client.one(qs, values , a => +a.count) .then(count => { @@ -813,8 +813,8 @@ export class PostgresStorageAdapter { // Apply the update to all objects that match the given Parse Query. updateObjectsByQuery(className, schema, query, update) { debug('updateObjectsByQuery', className, query, update); - let updatePatterns = []; - let values = [className] + const updatePatterns = []; + const values = [className] let index = 2; schema = toPostgresSchema(schema); @@ -822,19 +822,19 @@ export class PostgresStorageAdapter { update = handleDotFields(update); // Resolve authData first, // So we don't end up with multiple key updates - for (let fieldName in update) { - let authDataMatch = fieldName.match(/^_auth_data_([a-zA-Z0-9_]+)$/); + for (const fieldName in update) { + const authDataMatch = fieldName.match(/^_auth_data_([a-zA-Z0-9_]+)$/); if (authDataMatch) { var provider = authDataMatch[1]; - let value = update[fieldName]; + const value = update[fieldName]; delete update[fieldName]; update['authData'] = update['authData'] || {}; update['authData'][provider] = value; } } - for (let fieldName in update) { - let fieldValue = update[fieldName]; + for (const fieldName in update) { + const fieldValue = update[fieldName]; if (fieldValue === null) { updatePatterns.push(`$${index}:name = NULL`); values.push(fieldName); @@ -842,15 +842,15 @@ export class PostgresStorageAdapter { } else if (fieldName == 'authData') { // This recursively sets the json_object // Only 1 level deep - let generate = (jsonb, key, value) => { + const generate = (jsonb, key, value) => { return `json_object_set_key(COALESCE(${jsonb}, '{}'::jsonb), ${key}, ${value})::jsonb`; } - let lastKey = `$${index}:name`; - let fieldNameIndex = index; + const lastKey = `$${index}:name`; + const fieldNameIndex = index; index+=1; values.push(fieldName); - let update = Object.keys(fieldValue).reduce((lastKey, key) => { - let str = generate(lastKey, `$${index}::text`, `$${index+1}::jsonb`) + const update = Object.keys(fieldValue).reduce((lastKey, key) => { + const str = generate(lastKey, `$${index}::text`, `$${index+1}::jsonb`) index+=2; let value = fieldValue[key]; if (value) { @@ -941,12 +941,12 @@ export class PostgresStorageAdapter { } else if (Array.isArray(fieldValue) && schema.fields[fieldName] && schema.fields[fieldName].type === 'Array') { - let expectedType = parseTypeToPostgresType(schema.fields[fieldName]); + const expectedType = parseTypeToPostgresType(schema.fields[fieldName]); if (expectedType === 'text[]') { updatePatterns.push(`$${index}:name = $${index + 1}::text[]`); } else { let type = 'text'; - for (let elt of fieldValue) { + for (const elt of fieldValue) { if (typeof elt == 'object') { type = 'json'; break; @@ -962,10 +962,10 @@ export class PostgresStorageAdapter { } } - let where = buildWhereClause({ schema, index, query }) + const where = buildWhereClause({ schema, index, query }) values.push(...where.values); - let qs = `UPDATE $1:name SET ${updatePatterns.join(',')} WHERE ${where.pattern} RETURNING *`; + const qs = `UPDATE $1:name SET ${updatePatterns.join(',')} WHERE ${where.pattern} RETURNING *`; debug('update: ', qs, values); return this._client.any(qs, values); // TODO: This is unsafe, verification is needed, or a different query method; } @@ -973,7 +973,7 @@ export class PostgresStorageAdapter { // Hopefully, we can get rid of this. It's only used for config and hooks. upsertOneObject(className, schema, query, update) { debug('upsertOneObject', {className, query, update}); - let createValue = Object.assign({}, query, update); + const createValue = Object.assign({}, query, update); return this.createObject(className, schema, createValue).catch((err) => { // ignore duplicate value errors as it's upsert if (err.code === Parse.Error.DUPLICATE_VALUE) { @@ -988,7 +988,7 @@ export class PostgresStorageAdapter { const hasLimit = limit !== undefined; const hasSkip = skip !== undefined; let values = [className]; - let where = buildWhereClause({ schema, query, index: 2 }) + const where = buildWhereClause({ schema, query, index: 2 }) values.push(...where.values); const wherePattern = where.pattern.length > 0 ? `WHERE ${where.pattern}` : ''; @@ -1003,7 +1003,7 @@ export class PostgresStorageAdapter { let sortPattern = ''; if (sort) { - let sorting = Object.keys(sort).map((key) => { + const sorting = Object.keys(sort).map((key) => { // Using $idx pattern gives: non-integer constant in ORDER BY if (sort[key] === 1) { return `"${key}" ASC`; @@ -1085,7 +1085,7 @@ export class PostgresStorageAdapter { object._password_changed_at = { __type: 'Date', iso: object._password_changed_at.toISOString() }; } - for (let fieldName in object) { + for (const fieldName in object) { if (object[fieldName] === null) { delete object[fieldName]; } @@ -1125,8 +1125,8 @@ export class PostgresStorageAdapter { // Executes a count. count(className, schema, query) { debug('count', className, query); - let values = [className]; - let where = buildWhereClause({ schema, query, index: 2 }); + const values = [className]; + const where = buildWhereClause({ schema, query, index: 2 }); values.push(...where.values); const wherePattern = where.pattern.length > 0 ? `WHERE ${where.pattern}` : ''; @@ -1140,7 +1140,7 @@ export class PostgresStorageAdapter { } performInitialization({ VolatileClassesSchemas }) { - let now = new Date().getTime(); + const now = new Date().getTime(); debug('performInitialization'); let promises = VolatileClassesSchemas.map((schema) => { return this.createTable(schema.className, schema).catch((err) =>{ diff --git a/src/Auth.js b/src/Auth.js index f3dca78c31..150fa7ad77 100644 --- a/src/Auth.js +++ b/src/Auth.js @@ -44,7 +44,7 @@ function nobody(config) { var getAuthForSessionToken = function({ config, sessionToken, installationId } = {}) { return config.cacheController.user.get(sessionToken).then((userJSON) => { if (userJSON) { - let cachedUser = Parse.Object.fromJSON(userJSON); + const cachedUser = Parse.Object.fromJSON(userJSON); return Promise.resolve(new Auth({config, isMaster: false, installationId, user: cachedUser})); } @@ -71,7 +71,7 @@ var getAuthForSessionToken = function({ config, sessionToken, installationId } = obj['className'] = '_User'; obj['sessionToken'] = sessionToken; config.cacheController.user.put(sessionToken, obj); - let userObject = Parse.Object.fromJSON(obj); + const userObject = Parse.Object.fromJSON(obj); return new Auth({config, isMaster: false, installationId, user: userObject}); }); }); @@ -87,9 +87,9 @@ var getAuthForLegacySessionToken = function({config, sessionToken, installationI if (results.length !== 1) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid legacy session token'); } - let obj = results[0]; + const obj = results[0]; obj.className = '_User'; - let userObject = Parse.Object.fromJSON(obj); + const userObject = Parse.Object.fromJSON(obj); return new Auth({config, isMaster: false, installationId, user: userObject}); }); } @@ -162,7 +162,7 @@ Auth.prototype._loadRoles = function() { // Given a list of roleIds, find all the parent roles, returns a promise with all names Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queriedRoles = {}) { - let ins = roleIDs.filter((roleID) => { + const ins = roleIDs.filter((roleID) => { return queriedRoles[roleID] !== true; }).map((roleID) => { // mark as queried @@ -185,7 +185,7 @@ Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queri } else { restWhere = { 'roles': { '$in': ins }} } - let query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {}); + const query = new RestQuery(this.config, master(this.config), '_Role', restWhere, {}); return query.execute().then((response) => { var results = response.results; // Nothing found @@ -193,7 +193,7 @@ Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queri return Promise.resolve(names); } // Map the results with all Ids and names - let resultMap = results.reduce((memo, role) => { + const resultMap = results.reduce((memo, role) => { memo.names.push(role.name); memo.ids.push(role.objectId); return memo; diff --git a/src/ClientSDK.js b/src/ClientSDK.js index 4eebf203e5..9a23b0c6ff 100644 --- a/src/ClientSDK.js +++ b/src/ClientSDK.js @@ -9,8 +9,8 @@ function compatible(compatibleSDK) { if (!clientSDK) { return true; } - let clientVersion = clientSDK.version; - let compatiblityVersion = compatibleSDK[clientSDK.sdk]; + const clientVersion = clientSDK.version; + const compatiblityVersion = compatibleSDK[clientSDK.sdk]; return semver.satisfies(clientVersion, compatiblityVersion); } } @@ -22,8 +22,8 @@ function supportsForwardDelete(clientSDK) { } function fromString(version) { - let versionRE = /([-a-zA-Z]+)([0-9\.]+)/; - let match = version.toLowerCase().match(versionRE); + const versionRE = /([-a-zA-Z]+)([0-9\.]+)/; + const match = version.toLowerCase().match(versionRE); if (match && match.length === 3) { return { sdk: match[1], diff --git a/src/Config.js b/src/Config.js index 67cc33453b..ed0b51248b 100644 --- a/src/Config.js +++ b/src/Config.js @@ -18,7 +18,7 @@ function removeTrailingSlash(str) { export class Config { constructor(applicationId: string, mount: string) { - let cacheInfo = AppCache.get(applicationId); + const cacheInfo = AppCache.get(applicationId); if (!cacheInfo) { return; } diff --git a/src/Controllers/AdaptableController.js b/src/Controllers/AdaptableController.js index 3f8616048e..ca943c3ac7 100644 --- a/src/Controllers/AdaptableController.js +++ b/src/Controllers/AdaptableController.js @@ -42,14 +42,14 @@ export class AdaptableController { throw new Error(this.constructor.name+" requires an adapter"); } - let Type = this.expectedAdapterType(); + const Type = this.expectedAdapterType(); // Allow skipping for testing if (!Type) { return; } // Makes sure the prototype matches - let mismatches = Object.getOwnPropertyNames(Type.prototype).reduce((obj, key) => { + const mismatches = Object.getOwnPropertyNames(Type.prototype).reduce((obj, key) => { const adapterType = typeof adapter[key]; const expectedType = typeof Type.prototype[key]; if (adapterType !== expectedType) { diff --git a/src/Controllers/CacheController.js b/src/Controllers/CacheController.js index a6c88e9362..78e102e470 100644 --- a/src/Controllers/CacheController.js +++ b/src/Controllers/CacheController.js @@ -20,17 +20,17 @@ export class SubCache { } get(key) { - let cacheKey = joinKeys(this.prefix, key); + const cacheKey = joinKeys(this.prefix, key); return this.cache.get(cacheKey); } put(key, value, ttl) { - let cacheKey = joinKeys(this.prefix, key); + const cacheKey = joinKeys(this.prefix, key); return this.cache.put(cacheKey, value, ttl); } del(key) { - let cacheKey = joinKeys(this.prefix, key); + const cacheKey = joinKeys(this.prefix, key); return this.cache.del(cacheKey); } @@ -50,17 +50,17 @@ export class CacheController extends AdaptableController { } get(key) { - let cacheKey = joinKeys(this.appId, key); + const cacheKey = joinKeys(this.appId, key); return this.adapter.get(cacheKey).then(null, () => Promise.resolve(null)); } put(key, value, ttl) { - let cacheKey = joinKeys(this.appId, key); + const cacheKey = joinKeys(this.appId, key); return this.adapter.put(cacheKey, value, ttl); } del(key) { - let cacheKey = joinKeys(this.appId, key); + const cacheKey = joinKeys(this.appId, key); return this.adapter.del(cacheKey); } diff --git a/src/Controllers/DatabaseController.js b/src/Controllers/DatabaseController.js index 393a6e71c0..e21b28c486 100644 --- a/src/Controllers/DatabaseController.js +++ b/src/Controllers/DatabaseController.js @@ -9,14 +9,14 @@ import logger from '../logger'; import * as SchemaController from './SchemaController'; function addWriteACL(query, acl) { - let newQuery = _.cloneDeep(query); + const newQuery = _.cloneDeep(query); //Can't be any existing '_wperm' query, we don't allow client queries on that, no need to $and newQuery._wperm = { "$in" : [null, ...acl]}; return newQuery; } function addReadACL(query, acl) { - let newQuery = _.cloneDeep(query); + const newQuery = _.cloneDeep(query); //Can't be any existing '_rperm' query, we don't allow client queries on that, no need to $and newQuery._rperm = { "$in" : [null, "*", ...acl]}; return newQuery; @@ -31,7 +31,7 @@ const transformObjectACL = ({ ACL, ...result }) => { result._wperm = []; result._rperm = []; - for (let entry in ACL) { + for (const entry in ACL) { if (ACL[entry].read) { result._rperm.push(entry); } @@ -139,7 +139,7 @@ DatabaseController.prototype.redirectClassNameForKey = function(className, key) // batch request, that could confuse other users of the schema. DatabaseController.prototype.validateObject = function(className, object, query, { acl }) { let schema; - let isMaster = acl === undefined; + const isMaster = acl === undefined; var aclGroup = acl || []; return this.loadSchema().then(s => { schema = s; @@ -241,7 +241,7 @@ DatabaseController.prototype.update = function(className, query, update, { throw new Parse.Error(Parse.Error.INVALID_KEY_NAME, `Invalid field name for update: ${fieldName}`); } }); - for (let updateOperation in update) { + for (const updateOperation in update) { if (Object.keys(updateOperation).some(innerKey => innerKey.includes('$') || innerKey.includes('.'))) { throw new Parse.Error(Parse.Error.INVALID_NESTED_KEY, "Nested keys should not contain the '$' or '.' characters"); } @@ -270,12 +270,12 @@ DatabaseController.prototype.update = function(className, query, update, { }; function sanitizeDatabaseResult(originalObject, result) { - let response = {}; + const response = {}; if (!result) { return Promise.resolve(response); } Object.keys(originalObject).forEach(key => { - let keyUpdate = originalObject[key]; + const keyUpdate = originalObject[key]; // determine if that was an op if (keyUpdate && typeof keyUpdate === 'object' && keyUpdate.__op && ['Add', 'AddUnique', 'Remove', 'Increment'].indexOf(keyUpdate.__op) > -1) { @@ -300,7 +300,7 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI return; } if (op.__op == 'AddRelation') { - for (let object of op.objects) { + for (const object of op.objects) { pending.push(this.addRelation(key, className, objectId, object.objectId)); @@ -309,7 +309,7 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI } if (op.__op == 'RemoveRelation') { - for (let object of op.objects) { + for (const object of op.objects) { pending.push(this.removeRelation(key, className, objectId, object.objectId)); @@ -324,10 +324,10 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI } }; - for (let key in update) { + for (const key in update) { process(update[key], key); } - for (let key of deleteMe) { + for (const key of deleteMe) { delete update[key]; } return Promise.all(pending); @@ -337,7 +337,7 @@ DatabaseController.prototype.handleRelationUpdates = function(className, objectI // Returns a promise that resolves successfully iff the add was successful. const relationSchema = { fields: { relatedId: { type: 'String' }, owningId: { type: 'String' } } }; DatabaseController.prototype.addRelation = function(key, fromClassName, fromId, toId) { - let doc = { + const doc = { relatedId: toId, owningId : fromId }; @@ -410,7 +410,7 @@ DatabaseController.prototype.destroy = function(className, query, { acl } = {}) }; const flattenUpdateOperatorsForCreate = object => { - for (let key in object) { + for (const key in object) { if (object[key] && object[key].__op) { switch (object[key].__op) { case 'Increment': @@ -469,7 +469,7 @@ const transformAuthData = (className, object, schema) => { // Returns a promise that resolves successfully iff the object saved. DatabaseController.prototype.create = function(className, object, { acl } = {}) { // Make a copy of the object, so we don't mutate the incoming data. - let originalObject = object; + const originalObject = object; object = transformObjectACL(object); object.createdAt = { iso: object.createdAt, __type: 'Date' }; @@ -496,13 +496,13 @@ DatabaseController.prototype.create = function(className, object, { acl } = {}) }; DatabaseController.prototype.canAddField = function(schema, className, object, aclGroup) { - let classSchema = schema.data[className]; + const classSchema = schema.data[className]; if (!classSchema) { return Promise.resolve(); } - let fields = Object.keys(object); - let schemaFields = Object.keys(classSchema); - let newKeys = fields.filter((field) => { + const fields = Object.keys(object); + const schemaFields = Object.keys(classSchema); + const newKeys = fields.filter((field) => { return schemaFields.indexOf(field) < 0; }) if (newKeys.length > 0) { @@ -543,7 +543,7 @@ DatabaseController.prototype.reduceInRelation = function(className, query, schem // Search for an in-relation or equal-to-relation // Make it sequential for now, not sure of paralleization side effects if (query['$or']) { - let ors = query['$or']; + const ors = query['$or']; return Promise.all(ors.map((aQuery, index) => { return this.reduceInRelation(className, aQuery, schema).then((aQuery) => { query['$or'][index] = aQuery; @@ -553,14 +553,14 @@ DatabaseController.prototype.reduceInRelation = function(className, query, schem }); } - let promises = Object.keys(query).map((key) => { + const promises = Object.keys(query).map((key) => { if (query[key] && (query[key]['$in'] || query[key]['$ne'] || query[key]['$nin'] || query[key].__type == 'Pointer')) { - let t = schema.getExpectedType(className, key); + const t = schema.getExpectedType(className, key); if (!t || t.type !== 'Relation') { return Promise.resolve(query); } // Build the list of queries - let queries = Object.keys(query[key]).map((constraintKey) => { + const queries = Object.keys(query[key]).map((constraintKey) => { let relatedIds; let isNegation = false; if (constraintKey === 'objectId') { @@ -586,7 +586,7 @@ DatabaseController.prototype.reduceInRelation = function(className, query, schem delete query[key]; // execute each query independnently to build the list of // $in / $nin - let promises = queries.map((q) => { + const promises = queries.map((q) => { if (!q) { return Promise.resolve(); } @@ -637,12 +637,12 @@ DatabaseController.prototype.reduceRelationKeys = function(className, query) { }; DatabaseController.prototype.addInObjectIdsIds = function(ids = null, query) { - let idsFromString = typeof query.objectId === 'string' ? [query.objectId] : null; - let idsFromEq = query.objectId && query.objectId['$eq'] ? [query.objectId['$eq']] : null; - let idsFromIn = query.objectId && query.objectId['$in'] ? query.objectId['$in'] : null; + const idsFromString = typeof query.objectId === 'string' ? [query.objectId] : null; + const idsFromEq = query.objectId && query.objectId['$eq'] ? [query.objectId['$eq']] : null; + const idsFromIn = query.objectId && query.objectId['$in'] ? query.objectId['$in'] : null; - let allIds = [idsFromString, idsFromEq, idsFromIn, ids].filter(list => list !== null); - let totalLength = allIds.reduce((memo, list) => memo + list.length, 0); + const allIds = [idsFromString, idsFromEq, idsFromIn, ids].filter(list => list !== null); + const totalLength = allIds.reduce((memo, list) => memo + list.length, 0); let idsIntersection = []; if (totalLength > 125) { @@ -665,7 +665,7 @@ DatabaseController.prototype.addInObjectIdsIds = function(ids = null, query) { } DatabaseController.prototype.addNotInObjectIdsIds = function(ids = [], query) { - let idsFromNin = query.objectId && query.objectId['$nin'] ? query.objectId['$nin'] : []; + const idsFromNin = query.objectId && query.objectId['$nin'] ? query.objectId['$nin'] : []; let allIds = [...idsFromNin,...ids].filter(list => list !== null); // make a set and spread to remove duplicates @@ -707,8 +707,8 @@ DatabaseController.prototype.find = function(className, query, { keys, op } = {}) { - let isMaster = acl === undefined; - let aclGroup = acl || []; + const isMaster = acl === undefined; + const aclGroup = acl || []; op = op || (typeof query.objectId == 'string' && Object.keys(query).length === 1 ? 'get' : 'find'); let classExists = true; return this.loadSchema() @@ -846,9 +846,9 @@ DatabaseController.prototype.addPointerPermissions = function(schema, className, if (schema.testBaseCLP(className, aclGroup, operation)) { return query; } - let perms = schema.perms[className]; - let field = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields'; - let userACL = aclGroup.filter((acl) => { + const perms = schema.perms[className]; + const field = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields'; + const userACL = aclGroup.filter((acl) => { return acl.indexOf('role:') != 0 && acl != '*'; }); // the ACL should have exactly 1 user @@ -858,16 +858,16 @@ DatabaseController.prototype.addPointerPermissions = function(schema, className, if (userACL.length != 1) { return; } - let userId = userACL[0]; - let userPointer = { + const userId = userACL[0]; + const userPointer = { "__type": "Pointer", "className": "_User", "objectId": userId }; - let permFields = perms[field]; - let ors = permFields.map((key) => { - let q = { + const permFields = perms[field]; + const ors = permFields.map((key) => { + const q = { [key]: userPointer }; return {'$and': [q, query]}; @@ -886,17 +886,17 @@ DatabaseController.prototype.addPointerPermissions = function(schema, className, DatabaseController.prototype.performInitialization = function() { const requiredUserFields = { fields: { ...SchemaController.defaultColumns._Default, ...SchemaController.defaultColumns._User } }; - let userClassPromise = this.loadSchema() + const userClassPromise = this.loadSchema() .then(schema => schema.enforceClassExists('_User')) - let usernameUniqueness = userClassPromise + const usernameUniqueness = userClassPromise .then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['username'])) .catch(error => { logger.warn('Unable to ensure uniqueness for usernames: ', error); return Promise.reject(error); }); - let emailUniqueness = userClassPromise + const emailUniqueness = userClassPromise .then(() => this.adapter.ensureUniqueness('_User', requiredUserFields, ['email'])) .catch(error => { logger.warn('Unable to ensure uniqueness for user email addresses: ', error); @@ -904,7 +904,7 @@ DatabaseController.prototype.performInitialization = function() { }); // Create tables for volatile classes - let adapterInit = this.adapter.performInitialization({ VolatileClassesSchemas: SchemaController.VolatileClassesSchemas }); + const adapterInit = this.adapter.performInitialization({ VolatileClassesSchemas: SchemaController.VolatileClassesSchemas }); return Promise.all([usernameUniqueness, emailUniqueness, adapterInit]); } diff --git a/src/Controllers/FilesController.js b/src/Controllers/FilesController.js index d6e06a79b6..e8bcbc71d9 100644 --- a/src/Controllers/FilesController.js +++ b/src/Controllers/FilesController.js @@ -15,7 +15,7 @@ export class FilesController extends AdaptableController { createFile(config, filename, data, contentType) { - let extname = path.extname(filename); + const extname = path.extname(filename); const hasExtension = extname.length > 0; @@ -53,13 +53,13 @@ export class FilesController extends AdaptableController { if (typeof object !== 'object') { return; } - for (let key in object) { - let fileObject = object[key]; + for (const key in object) { + const fileObject = object[key]; if (fileObject && fileObject['__type'] === 'File') { if (fileObject['url']) { continue; } - let filename = fileObject['name']; + const filename = fileObject['name']; // all filenames starting with "tfss-" should be from files.parsetfss.com // all filenames starting with a "-" seperated UUID should be from files.parse.com // all other filenames have been migrated or created from Parse Server diff --git a/src/Controllers/HooksController.js b/src/Controllers/HooksController.js index 7dc8d53a25..2cd22efbb8 100644 --- a/src/Controllers/HooksController.js +++ b/src/Controllers/HooksController.js @@ -157,7 +157,7 @@ export class HooksController { function wrapToHTTPRequest(hook, key) { return (req, res) => { - let jsonBody = {}; + const jsonBody = {}; for (var i in req) { jsonBody[i] = req[i]; } @@ -169,7 +169,7 @@ function wrapToHTTPRequest(hook, key) { jsonBody.original = req.original.toJSON(); jsonBody.original.className = req.original.className; } - let jsonRequest: any = { + const jsonRequest: any = { headers: { 'Content-Type': 'application/json' }, diff --git a/src/Controllers/LiveQueryController.js b/src/Controllers/LiveQueryController.js index 850981df52..ce31a1d82a 100644 --- a/src/Controllers/LiveQueryController.js +++ b/src/Controllers/LiveQueryController.js @@ -20,7 +20,7 @@ export class LiveQueryController { if (!this.hasLiveQuery(className)) { return; } - let req = this._makePublisherRequest(currentObject, originalObject); + const req = this._makePublisherRequest(currentObject, originalObject); this.liveQueryPublisher.onCloudCodeAfterSave(req); } @@ -28,7 +28,7 @@ export class LiveQueryController { if (!this.hasLiveQuery(className)) { return; } - let req = this._makePublisherRequest(currentObject, originalObject); + const req = this._makePublisherRequest(currentObject, originalObject); this.liveQueryPublisher.onCloudCodeAfterDelete(req); } @@ -37,7 +37,7 @@ export class LiveQueryController { } _makePublisherRequest(currentObject: any, originalObject: any): any { - let req = { + const req = { object: currentObject }; if (currentObject) { diff --git a/src/Controllers/LoggerController.js b/src/Controllers/LoggerController.js index e3c053ecc8..6fb86ba88c 100644 --- a/src/Controllers/LoggerController.js +++ b/src/Controllers/LoggerController.js @@ -45,7 +45,7 @@ export class LoggerController extends AdaptableController { } if (e.body) { - for (let key of Object.keys(e.body)) { + for (const key of Object.keys(e.body)) { if (key === 'password') { e.body[key] = '********'; break; @@ -111,12 +111,12 @@ export class LoggerController extends AdaptableController { } static parseOptions(options = {}) { - let from = LoggerController.validDateTime(options.from) || + const from = LoggerController.validDateTime(options.from) || new Date(Date.now() - 7 * MILLISECONDS_IN_A_DAY); - let until = LoggerController.validDateTime(options.until) || new Date(); - let size = Number(options.size) || 10; - let order = options.order || LogOrder.DESCENDING; - let level = options.level || LogLevel.INFO; + const until = LoggerController.validDateTime(options.until) || new Date(); + const size = Number(options.size) || 10; + const order = options.order || LogOrder.DESCENDING; + const level = options.level || LogLevel.INFO; return { from, diff --git a/src/Controllers/PushController.js b/src/Controllers/PushController.js index aa3d909b36..d9c8775d27 100644 --- a/src/Controllers/PushController.js +++ b/src/Controllers/PushController.js @@ -57,7 +57,7 @@ export class PushController extends AdaptableController { return Promise.resolve(); } if (body.data && body.data.badge) { - let badge = body.data.badge; + const badge = body.data.badge; let restUpdate = {}; if (typeof badge == 'string' && badge.toLowerCase() === 'increment') { restUpdate = { badge: { __op: 'Increment', amount: 1 } } @@ -66,20 +66,20 @@ export class PushController extends AdaptableController { } else { throw "Invalid value for badge, expected number or 'Increment'"; } - let updateWhere = deepcopy(where); + const updateWhere = deepcopy(where); badgeUpdate = () => { updateWhere.deviceType = 'ios'; // Build a real RestQuery so we can use it in RestWrite - let restQuery = new RestQuery(config, master(config), '_Installation', updateWhere); + const restQuery = new RestQuery(config, master(config), '_Installation', updateWhere); return restQuery.buildRestWhere().then(() => { - let write = new RestWrite(config, master(config), '_Installation', restQuery.restWhere, restUpdate); + const write = new RestWrite(config, master(config), '_Installation', restQuery.restWhere, restUpdate); write.runOptions.many = true; return write.execute(); }); } } - let pushStatus = pushStatusHandler(config); + const pushStatus = pushStatusHandler(config); return Promise.resolve().then(() => { return pushStatus.setInitial(body, where); }).then(() => { @@ -105,7 +105,7 @@ export class PushController extends AdaptableController { sendToAdapter(body, installations, pushStatus) { if (body.data && body.data.badge && typeof body.data.badge == 'string' && body.data.badge.toLowerCase() == "increment") { // Collect the badges to reduce the # of calls - let badgeInstallationsMap = installations.reduce((map, installation) => { + const badgeInstallationsMap = installations.reduce((map, installation) => { let badge = installation.badge; if (installation.deviceType != "ios") { badge = UNSUPPORTED_BADGE_KEY; @@ -116,8 +116,8 @@ export class PushController extends AdaptableController { }, {}); // Map the on the badges count and return the send result - let promises = Object.keys(badgeInstallationsMap).map((badge) => { - let payload = deepcopy(body); + const promises = Object.keys(badgeInstallationsMap).map((badge) => { + const payload = deepcopy(body); if (badge == UNSUPPORTED_BADGE_KEY) { delete payload.data.badge; } else { diff --git a/src/Controllers/SchemaCache.js b/src/Controllers/SchemaCache.js index ca81db8bcb..2e75d8c4f2 100644 --- a/src/Controllers/SchemaCache.js +++ b/src/Controllers/SchemaCache.js @@ -76,7 +76,7 @@ export default class SchemaCache { if (!allKeys) { return; } - let promises = Object.keys(allKeys).map((key) => { + const promises = Object.keys(allKeys).map((key) => { return this.cache.del(key); }); return Promise.all(promises); diff --git a/src/Controllers/SchemaController.js b/src/Controllers/SchemaController.js index 19e83b8ca0..9eee5ca458 100644 --- a/src/Controllers/SchemaController.js +++ b/src/Controllers/SchemaController.js @@ -128,7 +128,7 @@ const requireAuthenticationRegex = /^requiresAuthentication$/ const permissionKeyRegex = Object.freeze([userIdRegex, roleRegex, publicRegex, requireAuthenticationRegex]); function verifyPermissionKey(key) { - let result = permissionKeyRegex.reduce((isGood, regEx) => { + const result = permissionKeyRegex.reduce((isGood, regEx) => { isGood = isGood || key.match(regEx) != null; return isGood; }, false); @@ -162,7 +162,7 @@ function validateCLP(perms, fields) { Object.keys(perms[operation]).forEach((key) => { verifyPermissionKey(key); - let perm = perms[operation][key]; + const perm = perms[operation][key]; if (perm !== true) { throw new Parse.Error(Parse.Error.INVALID_JSON, `'${perm}' is not a valid value for class level permissions ${operation}:${key}:${perm}`); } @@ -346,7 +346,7 @@ export default class SchemaController { // Inject the in-memory classes volatileClasses.forEach(className => { - let schema = injectDefaultSchema({ className }); + const schema = injectDefaultSchema({ className }); this.data[className] = schema.fields; this.perms[className] = schema.classLevelPermissions; }); @@ -439,9 +439,9 @@ export default class SchemaController { updateClass(className, submittedFields, classLevelPermissions, database) { return this.getOneSchema(className) .then(schema => { - let existingFields = schema.fields; + const existingFields = schema.fields; Object.keys(submittedFields).forEach(name => { - let field = submittedFields[name]; + const field = submittedFields[name]; if (existingFields[name] && field.__op !== 'Delete') { throw new Parse.Error(255, `Field ${name} exists, cannot update.`); } @@ -452,16 +452,16 @@ export default class SchemaController { delete existingFields._rperm; delete existingFields._wperm; - let newSchema = buildMergedSchemaObject(existingFields, submittedFields); - let validationError = this.validateSchemaData(className, newSchema, classLevelPermissions, Object.keys(existingFields)); + const newSchema = buildMergedSchemaObject(existingFields, submittedFields); + const validationError = this.validateSchemaData(className, newSchema, classLevelPermissions, Object.keys(existingFields)); if (validationError) { throw new Parse.Error(validationError.code, validationError.error); } // Finally we have checked to make sure the request is valid and we can start deleting fields. // Do all deletions first, then a single save to _SCHEMA collection to handle all additions. - let deletePromises = []; - let insertedFields = []; + const deletePromises = []; + const insertedFields = []; Object.keys(submittedFields).forEach(fieldName => { if (submittedFields[fieldName].__op === 'Delete') { const promise = this.deleteField(fieldName, className, database); @@ -474,7 +474,7 @@ export default class SchemaController { return Promise.all(deletePromises) // Delete Everything .then(() => this.reloadData({ clearCache: true })) // Reload our Schema, so we have all the new values .then(() => { - let promises = insertedFields.map(fieldName => { + const promises = insertedFields.map(fieldName => { const type = submittedFields[fieldName]; return this.enforceFieldExists(className, fieldName, type); }); @@ -542,7 +542,7 @@ export default class SchemaController { } validateSchemaData(className, fields, classLevelPermissions, existingFieldNames) { - for (let fieldName in fields) { + for (const fieldName in fields) { if (existingFieldNames.indexOf(fieldName) < 0) { if (!fieldNameIsValid(fieldName)) { return { @@ -561,11 +561,11 @@ export default class SchemaController { } } - for (let fieldName in defaultColumns[className]) { + for (const fieldName in defaultColumns[className]) { fields[fieldName] = defaultColumns[className][fieldName]; } - let geoPoints = Object.keys(fields).filter(key => fields[key] && fields[key].type === 'GeoPoint'); + const geoPoints = Object.keys(fields).filter(key => fields[key] && fields[key].type === 'GeoPoint'); if (geoPoints.length > 1) { return { code: Parse.Error.INCORRECT_TYPE, @@ -605,7 +605,7 @@ export default class SchemaController { } return this.reloadData().then(() => { - let expectedType = this.getExpectedType(className, fieldName); + const expectedType = this.getExpectedType(className, fieldName); if (typeof type === 'string') { type = { type }; } @@ -690,11 +690,11 @@ export default class SchemaController { validateObject(className, object, query) { let geocount = 0; let promise = this.enforceClassExists(className); - for (let fieldName in object) { + for (const fieldName in object) { if (object[fieldName] === undefined) { continue; } - let expected = getType(object[fieldName]); + const expected = getType(object[fieldName]); if (expected === 'GeoPoint') { geocount++; } @@ -722,12 +722,12 @@ export default class SchemaController { // Validates that all the properties are set for the object validateRequiredColumns(className, object, query) { - let columns = requiredColumns[className]; + const columns = requiredColumns[className]; if (!columns || columns.length == 0) { return Promise.resolve(this); } - let missingColumns = columns.filter(function(column){ + const missingColumns = columns.filter(function(column){ if (query && query.objectId) { if (object[column] && typeof object[column] === "object") { // Trying to delete a required column @@ -752,8 +752,8 @@ export default class SchemaController { if (!this.perms[className] || !this.perms[className][operation]) { return true; } - let classPerms = this.perms[className]; - let perms = classPerms[operation]; + const classPerms = this.perms[className]; + const perms = classPerms[operation]; // Handle the public scenario quickly if (perms['*']) { return true; @@ -774,8 +774,8 @@ export default class SchemaController { if (!this.perms[className] || !this.perms[className][operation]) { return true; } - let classPerms = this.perms[className]; - let perms = classPerms[operation]; + const classPerms = this.perms[className]; + const perms = classPerms[operation]; // If only for authenticated users // make sure we have an aclGroup @@ -797,7 +797,7 @@ export default class SchemaController { // No matching CLP, let's check the Pointer permissions // And handle those later - let permissionField = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields'; + const permissionField = ['get', 'find'].indexOf(operation) > -1 ? 'readUserFields' : 'writeUserFields'; // Reject create when write lockdown if (permissionField == 'writeUserFields' && operation == 'create') { @@ -831,7 +831,7 @@ export default class SchemaController { // Returns a promise for a new Schema. const load = (dbAdapter, schemaCache, options) => { - let schema = new SchemaController(dbAdapter, schemaCache); + const schema = new SchemaController(dbAdapter, schemaCache); return schema.reloadData(options).then(() => schema); } @@ -841,20 +841,20 @@ const load = (dbAdapter, schemaCache, options) => { // to mongoSchemaFromFieldsAndClassName. No validation is done here, it // is done in mongoSchemaFromFieldsAndClassName. function buildMergedSchemaObject(existingFields, putRequest) { - let newSchema = {}; - let sysSchemaField = Object.keys(defaultColumns).indexOf(existingFields._id) === -1 ? [] : Object.keys(defaultColumns[existingFields._id]); - for (let oldField in existingFields) { + const newSchema = {}; + const sysSchemaField = Object.keys(defaultColumns).indexOf(existingFields._id) === -1 ? [] : Object.keys(defaultColumns[existingFields._id]); + for (const oldField in existingFields) { if (oldField !== '_id' && oldField !== 'ACL' && oldField !== 'updatedAt' && oldField !== 'createdAt' && oldField !== 'objectId') { if (sysSchemaField.length > 0 && sysSchemaField.indexOf(oldField) !== -1) { continue; } - let fieldIsDeleted = putRequest[oldField] && putRequest[oldField].__op === 'Delete' + const fieldIsDeleted = putRequest[oldField] && putRequest[oldField].__op === 'Delete' if (!fieldIsDeleted) { newSchema[oldField] = existingFields[oldField]; } } } - for (let newField in putRequest) { + for (const newField in putRequest) { if (newField !== 'objectId' && putRequest[newField].__op !== 'Delete') { if (sysSchemaField.length > 0 && sysSchemaField.indexOf(newField) !== -1) { continue; @@ -879,7 +879,7 @@ function thenValidateRequiredColumns(schemaPromise, className, object, query) { // The output should be a valid schema value. // TODO: ensure that this is compatible with the format used in Open DB function getType(obj) { - let type = typeof obj; + const type = typeof obj; switch(type) { case 'boolean': return 'Boolean'; diff --git a/src/Controllers/UserController.js b/src/Controllers/UserController.js index a931eaae6e..48b4c7f00b 100644 --- a/src/Controllers/UserController.js +++ b/src/Controllers/UserController.js @@ -48,8 +48,8 @@ export class UserController extends AdaptableController { throw undefined; } - let query = {username: username, _email_verify_token: token}; - let updateFields = { emailVerified: true, _email_verify_token: {__op: 'Delete'}}; + const query = {username: username, _email_verify_token: token}; + const updateFields = { emailVerified: true, _email_verify_token: {__op: 'Delete'}}; // if the email verify token needs to be validated then // add additional query params and additional fields that need to be updated @@ -119,8 +119,8 @@ export class UserController extends AdaptableController { // We may need to fetch the user in case of update email this.getUserIfNeeded(user).then((user) => { const username = encodeURIComponent(user.username); - let link = `${this.config.verifyEmailURL}?token=${token}&username=${username}`; - let options = { + const link = `${this.config.verifyEmailURL}?token=${token}&username=${username}`; + const options = { appName: this.config.appName, link: link, user: inflate('_User', user), @@ -153,9 +153,9 @@ export class UserController extends AdaptableController { .then(user => { const token = encodeURIComponent(user._perishable_token); const username = encodeURIComponent(user.username); - let link = `${this.config.requestResetPasswordURL}?token=${token}&username=${username}` + const link = `${this.config.requestResetPasswordURL}?token=${token}&username=${username}` - let options = { + const options = { appName: this.config.appName, link: link, user: inflate('_User', user), @@ -188,22 +188,22 @@ export class UserController extends AdaptableController { } defaultVerificationEmail({link, user, appName, }) { - let text = "Hi,\n\n" + + const text = "Hi,\n\n" + "You are being asked to confirm the e-mail address " + user.get("email") + " with " + appName + "\n\n" + "" + "Click here to confirm it:\n" + link; - let to = user.get("email"); - let subject = 'Please verify your e-mail for ' + appName; + const to = user.get("email"); + const subject = 'Please verify your e-mail for ' + appName; return { text, to, subject }; } defaultResetPasswordEmail({link, user, appName, }) { - let text = "Hi,\n\n" + + const text = "Hi,\n\n" + "You requested to reset your password for " + appName + ".\n\n" + "" + "Click here to reset it:\n" + link; - let to = user.get("email") || user.get('username'); - let subject = 'Password Reset for ' + appName; + const to = user.get("email") || user.get('username'); + const subject = 'Password Reset for ' + appName; return { text, to, subject }; } } diff --git a/src/LiveQuery/Client.js b/src/LiveQuery/Client.js index d5385bf1bf..1b5b49b709 100644 --- a/src/LiveQuery/Client.js +++ b/src/LiveQuery/Client.js @@ -3,7 +3,7 @@ import logger from '../logger'; import type { FlattenedObjectData } from './Subscription'; export type Message = { [attr: string]: any }; -let dafaultFields = ['className', 'objectId', 'updatedAt', 'createdAt', 'ACL']; +const dafaultFields = ['className', 'objectId', 'updatedAt', 'createdAt', 'ACL']; class Client { id: number; @@ -63,7 +63,7 @@ class Client { _pushEvent(type: string): Function { return function(subscriptionId: number, parseObjectJSON: any): void { - let response: Message = { + const response: Message = { 'op' : type, 'clientId' : this.id }; @@ -85,11 +85,11 @@ class Client { if (!fields) { return parseObjectJSON; } - let limitedParseObject = {}; - for (let field of dafaultFields) { + const limitedParseObject = {}; + for (const field of dafaultFields) { limitedParseObject[field] = parseObjectJSON[field]; } - for (let field of fields) { + for (const field of fields) { if (field in parseObjectJSON) { limitedParseObject[field] = parseObjectJSON[field]; } diff --git a/src/LiveQuery/ParseCloudCodePublisher.js b/src/LiveQuery/ParseCloudCodePublisher.js index 4dc32a0106..5b1645bbe1 100644 --- a/src/LiveQuery/ParseCloudCodePublisher.js +++ b/src/LiveQuery/ParseCloudCodePublisher.js @@ -23,7 +23,7 @@ class ParseCloudCodePublisher { _onCloudCodeMessage(type: string, request: any): void { logger.verbose('Raw request from cloud code current : %j | original : %j', request.object, request.original); // We need the full JSON which includes className - let message = { + const message = { currentParseObject: request.object._toFullJSON() } if (request.original) { diff --git a/src/LiveQuery/ParseLiveQueryServer.js b/src/LiveQuery/ParseLiveQueryServer.js index 354ca6410d..2a68f2324a 100644 --- a/src/LiveQuery/ParseLiveQueryServer.js +++ b/src/LiveQuery/ParseLiveQueryServer.js @@ -28,9 +28,9 @@ class ParseLiveQueryServer { config = config || {}; // Store keys, convert obj to map - let keyPairs = config.keyPairs || {}; + const keyPairs = config.keyPairs || {}; this.keyPairs = new Map(); - for (let key of Object.keys(keyPairs)) { + for (const key of Object.keys(keyPairs)) { this.keyPairs.set(key, keyPairs[key]); } logger.verbose('Support key pairs', this.keyPairs); @@ -39,11 +39,11 @@ class ParseLiveQueryServer { Parse.Object.disableSingleInstance(); Parse.User.enableUnsafeCurrentUser(); - let serverURL = config.serverURL || Parse.serverURL; + const serverURL = config.serverURL || Parse.serverURL; Parse.serverURL = serverURL; - let appId = config.appId || Parse.applicationId; - let javascriptKey = Parse.javaScriptKey; - let masterKey = config.masterKey || Parse.masterKey; + const appId = config.appId || Parse.applicationId; + const javascriptKey = Parse.javaScriptKey; + const masterKey = config.masterKey || Parse.masterKey; Parse.initialize(appId, javascriptKey, masterKey); // Initialize websocket server @@ -86,13 +86,13 @@ class ParseLiveQueryServer { // Message.originalParseObject is the original ParseObject JSON. _inflateParseObject(message: any): void { // Inflate merged object - let currentParseObject = message.currentParseObject; + const currentParseObject = message.currentParseObject; let className = currentParseObject.className; let parseObject = new Parse.Object(className); parseObject._finishFetch(currentParseObject); message.currentParseObject = parseObject; // Inflate original object - let originalParseObject = message.originalParseObject; + const originalParseObject = message.originalParseObject; if (originalParseObject) { className = originalParseObject.className; parseObject = new Parse.Object(className); @@ -106,28 +106,28 @@ class ParseLiveQueryServer { _onAfterDelete(message: any): void { logger.verbose(Parse.applicationId + 'afterDelete is triggered'); - let deletedParseObject = message.currentParseObject.toJSON(); - let className = deletedParseObject.className; + const deletedParseObject = message.currentParseObject.toJSON(); + const className = deletedParseObject.className; logger.verbose('ClassName: %j | ObjectId: %s', className, deletedParseObject.id); logger.verbose('Current client number : %d', this.clients.size); - let classSubscriptions = this.subscriptions.get(className); + const classSubscriptions = this.subscriptions.get(className); if (typeof classSubscriptions === 'undefined') { logger.debug('Can not find subscriptions under this class ' + className); return; } - for (let subscription of classSubscriptions.values()) { - let isSubscriptionMatched = this._matchesSubscription(deletedParseObject, subscription); + for (const subscription of classSubscriptions.values()) { + const isSubscriptionMatched = this._matchesSubscription(deletedParseObject, subscription); if (!isSubscriptionMatched) { continue; } - for (let [clientId, requestIds] of _.entries(subscription.clientRequestIds)) { - let client = this.clients.get(clientId); + for (const [clientId, requestIds] of _.entries(subscription.clientRequestIds)) { + const client = this.clients.get(clientId); if (typeof client === 'undefined') { continue; } - for (let requestId of requestIds) { - let acl = message.currentParseObject.getACL(); + for (const requestId of requestIds) { + const acl = message.currentParseObject.getACL(); // Check ACL this._matchesACL(acl, client, requestId).then((isMatched) => { if (!isMatched) { @@ -151,25 +151,25 @@ class ParseLiveQueryServer { if (message.originalParseObject) { originalParseObject = message.originalParseObject.toJSON(); } - let currentParseObject = message.currentParseObject.toJSON(); - let className = currentParseObject.className; + const currentParseObject = message.currentParseObject.toJSON(); + const className = currentParseObject.className; logger.verbose('ClassName: %s | ObjectId: %s', className, currentParseObject.id); logger.verbose('Current client number : %d', this.clients.size); - let classSubscriptions = this.subscriptions.get(className); + const classSubscriptions = this.subscriptions.get(className); if (typeof classSubscriptions === 'undefined') { logger.debug('Can not find subscriptions under this class ' + className); return; } - for (let subscription of classSubscriptions.values()) { - let isOriginalSubscriptionMatched = this._matchesSubscription(originalParseObject, subscription); - let isCurrentSubscriptionMatched = this._matchesSubscription(currentParseObject, subscription); - for (let [clientId, requestIds] of _.entries(subscription.clientRequestIds)) { - let client = this.clients.get(clientId); + for (const subscription of classSubscriptions.values()) { + const isOriginalSubscriptionMatched = this._matchesSubscription(originalParseObject, subscription); + const isCurrentSubscriptionMatched = this._matchesSubscription(currentParseObject, subscription); + for (const [clientId, requestIds] of _.entries(subscription.clientRequestIds)) { + const client = this.clients.get(clientId); if (typeof client === 'undefined') { continue; } - for (let requestId of requestIds) { + for (const requestId of requestIds) { // Set orignal ParseObject ACL checking promise, if the object does not match // subscription, we do not need to check ACL let originalACLCheckingPromise; @@ -188,7 +188,7 @@ class ParseLiveQueryServer { if (!isCurrentSubscriptionMatched) { currentACLCheckingPromise = Parse.Promise.as(false); } else { - let currentACL = message.currentParseObject.getACL(); + const currentACL = message.currentParseObject.getACL(); currentACLCheckingPromise = this._matchesACL(currentACL, client, requestId); } @@ -221,7 +221,7 @@ class ParseLiveQueryServer { } else { return null; } - let functionName = 'push' + type; + const functionName = 'push' + type; client[functionName](requestId, currentParseObject); }, (error) => { logger.error('Matching ACL error : ', error); @@ -271,23 +271,23 @@ class ParseLiveQueryServer { parseWebsocket.on('disconnect', () => { logger.info('Client disconnect: %d', parseWebsocket.clientId); - let clientId = parseWebsocket.clientId; + const clientId = parseWebsocket.clientId; if (!this.clients.has(clientId)) { logger.error('Can not find client %d on disconnect', clientId); return; } // Delete client - let client = this.clients.get(clientId); + const client = this.clients.get(clientId); this.clients.delete(clientId); // Delete client from subscriptions - for (let [requestId, subscriptionInfo] of _.entries(client.subscriptionInfos)) { - let subscription = subscriptionInfo.subscription; + 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 - let classSubscriptions = this.subscriptions.get(subscription.className); + const classSubscriptions = this.subscriptions.get(subscription.className); if (!subscription.hasSubscribingClient()) { classSubscriptions.delete(subscription.hash); } @@ -316,12 +316,12 @@ class ParseLiveQueryServer { return Parse.Promise.as(true); } // Check subscription sessionToken matches ACL first - let subscriptionInfo = client.getSubscriptionInfo(requestId); + const subscriptionInfo = client.getSubscriptionInfo(requestId); if (typeof subscriptionInfo === 'undefined') { return Parse.Promise.as(false); } - let subscriptionSessionToken = subscriptionInfo.sessionToken; + const subscriptionSessionToken = subscriptionInfo.sessionToken; return this.sessionTokenCache.getUserId(subscriptionSessionToken).then((userId) => { return acl.getReadAccess(userId); }).then((isSubscriptionSessionTokenMatched) => { @@ -368,7 +368,7 @@ class ParseLiveQueryServer { then((roles) => { // Finally, see if any of the user's roles allow them read access - for (let role of roles) { + for (const role of roles) { if (acl.getRoleReadAccess(role)) { return resolve(true); } @@ -387,7 +387,7 @@ class ParseLiveQueryServer { } // Check client sessionToken matches ACL - let clientSessionToken = client.sessionToken; + const clientSessionToken = client.sessionToken; return this.sessionTokenCache.getUserId(clientSessionToken).then((userId) => { return acl.getReadAccess(userId); }); @@ -404,7 +404,7 @@ class ParseLiveQueryServer { logger.error('Key in request is not valid'); return; } - let client = new Client(this.clientId, parseWebsocket); + const client = new Client(this.clientId, parseWebsocket); parseWebsocket.clientId = this.clientId; this.clientId += 1; this.clients.set(parseWebsocket.clientId, client); @@ -417,7 +417,7 @@ class ParseLiveQueryServer { return true; } let isValid = false; - for (let [key, secret] of validKeyPairs) { + for (const [key, secret] of validKeyPairs) { if (!request[key] || request[key] !== secret) { continue; } @@ -434,16 +434,16 @@ class ParseLiveQueryServer { logger.error('Can not find this client, make sure you connect to server before subscribing'); return; } - let client = this.clients.get(parseWebsocket.clientId); + const client = this.clients.get(parseWebsocket.clientId); // Get subscription from subscriptions, create one if necessary - let subscriptionHash = queryHash(request.query); + const subscriptionHash = queryHash(request.query); // Add className to subscriptions if necessary - let className = request.query.className; + const className = request.query.className; if (!this.subscriptions.has(className)) { this.subscriptions.set(className, new Map()); } - let classSubscriptions = this.subscriptions.get(className); + const classSubscriptions = this.subscriptions.get(className); let subscription; if (classSubscriptions.has(subscriptionHash)) { subscription = classSubscriptions.get(subscriptionHash); @@ -453,7 +453,7 @@ class ParseLiveQueryServer { } // Add subscriptionInfo to client - let subscriptionInfo = { + const subscriptionInfo = { subscription: subscription }; // Add selected fields and sessionToken for this subscription if necessary @@ -486,8 +486,8 @@ class ParseLiveQueryServer { logger.error('Can not find this client, make sure you connect to server before unsubscribing'); return; } - let requestId = request.requestId; - let client = this.clients.get(parseWebsocket.clientId); + const requestId = request.requestId; + const client = this.clients.get(parseWebsocket.clientId); if (typeof client === 'undefined') { Client.pushError(parseWebsocket, 2, 'Cannot find client with clientId ' + parseWebsocket.clientId + '. Make sure you connect to live query server before unsubscribing.'); @@ -495,7 +495,7 @@ class ParseLiveQueryServer { return; } - let subscriptionInfo = client.getSubscriptionInfo(requestId); + const subscriptionInfo = client.getSubscriptionInfo(requestId); if (typeof subscriptionInfo === 'undefined') { Client.pushError(parseWebsocket, 2, 'Cannot find subscription with clientId ' + parseWebsocket.clientId + ' subscriptionId ' + requestId + '. Make sure you subscribe to live query server before unsubscribing.'); @@ -506,11 +506,11 @@ class ParseLiveQueryServer { // Remove subscription from client client.deleteSubscriptionInfo(requestId); // Remove client from subscription - let subscription = subscriptionInfo.subscription; - let className = subscription.className; + const subscription = subscriptionInfo.subscription; + const className = subscription.className; subscription.deleteClientSubscription(parseWebsocket.clientId, requestId); // If there is no client which is subscribing this subscription, remove it from subscriptions - let classSubscriptions = this.subscriptions.get(className); + const classSubscriptions = this.subscriptions.get(className); if (!subscription.hasSubscribingClient()) { classSubscriptions.delete(subscription.hash); } diff --git a/src/LiveQuery/ParsePubSub.js b/src/LiveQuery/ParsePubSub.js index 46b510d015..ff321889a1 100644 --- a/src/LiveQuery/ParsePubSub.js +++ b/src/LiveQuery/ParsePubSub.js @@ -7,10 +7,10 @@ import { RedisPubSub } from '../Adapters/PubSub/RedisPubSub'; -let ParsePubSub = {}; +const ParsePubSub = {}; function useRedis(config: any): boolean { - let redisURL = config.redisURL; + const redisURL = config.redisURL; return typeof redisURL !== 'undefined' && redisURL !== ''; } @@ -18,7 +18,7 @@ ParsePubSub.createPublisher = function(config: any): any { if (useRedis(config)) { return RedisPubSub.createPublisher(config); } else { - let adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config) + const adapter = loadAdapter(config.pubSubAdapter, EventEmitterPubSub, config) if (typeof adapter.createPublisher !== 'function') { throw 'pubSubAdapter should have createPublisher()'; } @@ -30,7 +30,7 @@ ParsePubSub.createSubscriber = function(config: any): void { if (useRedis(config)) { return RedisPubSub.createSubscriber(config); } else { - let 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/ParseWebSocketServer.js b/src/LiveQuery/ParseWebSocketServer.js index b7c6094735..575f1c5590 100644 --- a/src/LiveQuery/ParseWebSocketServer.js +++ b/src/LiveQuery/ParseWebSocketServer.js @@ -1,20 +1,20 @@ import logger from '../logger'; -let typeMap = new Map([['disconnect', 'close']]); +const typeMap = new Map([['disconnect', 'close']]); export class ParseWebSocketServer { server: Object; constructor(server: any, onConnect: Function, websocketTimeout: number = 10 * 1000) { - let WebSocketServer = require('ws').Server; - let wss = new WebSocketServer({ server: server }); + const WebSocketServer = require('ws').Server; + const wss = new WebSocketServer({ server: server }); wss.on('listening', () => { logger.info('Parse LiveQuery Server starts running'); }); wss.on('connection', (ws) => { onConnect(new ParseWebSocket(ws)); // Send ping to client periodically - let pingIntervalId = setInterval(() => { + const pingIntervalId = setInterval(() => { if (ws.readyState == ws.OPEN) { ws.ping(); } else { @@ -34,7 +34,7 @@ export class ParseWebSocket { } on(type: string, callback): void { - let wsType = typeMap.has(type) ? typeMap.get(type) : type; + const wsType = typeMap.has(type) ? typeMap.get(type) : type; this.ws.on(wsType, callback); } diff --git a/src/LiveQuery/QueryTools.js b/src/LiveQuery/QueryTools.js index b62e11bce9..6a772ca107 100644 --- a/src/LiveQuery/QueryTools.js +++ b/src/LiveQuery/QueryTools.js @@ -217,8 +217,8 @@ function matchesKeyConstraints(object, key, constraints) { } break; case '$exists': { - let propertyExists = typeof object[key] !== 'undefined'; - let existenceIsRequired = constraints['$exists']; + const propertyExists = typeof object[key] !== 'undefined'; + const existenceIsRequired = constraints['$exists']; if (typeof constraints['$exists'] !== 'boolean') { // The SDK will never submit a non-boolean for $exists, but if someone // tries to submit a non-boolean for $exits outside the SDKs, just ignore it. diff --git a/src/LiveQuery/RequestSchema.js b/src/LiveQuery/RequestSchema.js index b36bcd26c2..05cfed3275 100644 --- a/src/LiveQuery/RequestSchema.js +++ b/src/LiveQuery/RequestSchema.js @@ -1,4 +1,4 @@ -let general = { +const general = { 'title': 'General request schema', 'type': 'object', 'properties': { @@ -9,7 +9,7 @@ let general = { }, }; -let connect = { +const connect = { 'title': 'Connect operation schema', 'type': 'object', 'properties': { @@ -40,7 +40,7 @@ let connect = { "additionalProperties": false }; -let subscribe = { +const subscribe = { 'title': 'Subscribe operation schema', 'type': 'object', 'properties': { @@ -78,7 +78,7 @@ let subscribe = { 'additionalProperties': false }; -let update = { +const update = { 'title': 'Update operation schema', 'type': 'object', 'properties': { @@ -116,7 +116,7 @@ let update = { 'additionalProperties': false }; -let unsubscribe = { +const unsubscribe = { 'title': 'Unsubscribe operation schema', 'type': 'object', 'properties': { @@ -129,7 +129,7 @@ let unsubscribe = { "additionalProperties": false } -let RequestSchema = { +const RequestSchema = { 'general': general, 'connect': connect, 'subscribe': subscribe, diff --git a/src/LiveQuery/SessionTokenCache.js b/src/LiveQuery/SessionTokenCache.js index 57f84720d0..d496e1e0b9 100644 --- a/src/LiveQuery/SessionTokenCache.js +++ b/src/LiveQuery/SessionTokenCache.js @@ -16,14 +16,14 @@ class SessionTokenCache { if (!sessionToken) { return Parse.Promise.error('Empty sessionToken'); } - let userId = this.cache.get(sessionToken); + const userId = this.cache.get(sessionToken); if (userId) { logger.verbose('Fetch userId %s of sessionToken %s from Cache', userId, sessionToken); return Parse.Promise.as(userId); } return Parse.User.become(sessionToken).then((user) => { logger.verbose('Fetch userId %s of sessionToken %s from Parse', user.id, sessionToken); - let userId = user.id; + const userId = user.id; this.cache.set(sessionToken, userId); return Parse.Promise.as(userId); }, (error) => { diff --git a/src/LiveQuery/Subscription.js b/src/LiveQuery/Subscription.js index d5bff3c8b2..53d3938748 100644 --- a/src/LiveQuery/Subscription.js +++ b/src/LiveQuery/Subscription.js @@ -21,18 +21,18 @@ class Subscription { if (!this.clientRequestIds.has(clientId)) { this.clientRequestIds.set(clientId, []); } - let requestIds = this.clientRequestIds.get(clientId); + const requestIds = this.clientRequestIds.get(clientId); requestIds.push(requestId); } deleteClientSubscription(clientId: number, requestId: number): void { - let requestIds = this.clientRequestIds.get(clientId); + const requestIds = this.clientRequestIds.get(clientId); if (typeof requestIds === 'undefined') { logger.error('Can not find client %d to delete', clientId); return; } - let index = requestIds.indexOf(requestId); + const index = requestIds.indexOf(requestId); if (index < 0) { logger.error('Can not find client %d subscription %d to delete', clientId, requestId); return; diff --git a/src/ParseServer.js b/src/ParseServer.js index 0ae7b24621..cb3294ab6b 100644 --- a/src/ParseServer.js +++ b/src/ParseServer.js @@ -307,7 +307,7 @@ class ParseServer { api.use(middlewares.allowMethodOverride); api.use(middlewares.handleParseHeaders); - let appRouter = ParseServer.promiseRouter({ appId }); + const appRouter = ParseServer.promiseRouter({ appId }); api.use(appRouter.expressRouter()); api.use(middlewares.handleParseErrors); @@ -332,7 +332,7 @@ class ParseServer { } static promiseRouter({appId}) { - let routers = [ + const routers = [ new ClassesRouter(), new UsersRouter(), new SessionsRouter(), @@ -351,11 +351,11 @@ class ParseServer { new CloudCodeRouter() ]; - let routes = routers.reduce((memo, router) => { + const routes = routers.reduce((memo, router) => { return memo.concat(router.routes); }, []); - let appRouter = new PromiseRouter(routes, appId); + const appRouter = new PromiseRouter(routes, appId); batch.mountOnto(appRouter); return appRouter; diff --git a/src/ParseServerRESTController.js b/src/ParseServerRESTController.js index 64a0adca35..e027af65a2 100644 --- a/src/ParseServerRESTController.js +++ b/src/ParseServerRESTController.js @@ -33,10 +33,10 @@ function getAuth(options = {}, config) { function ParseServerRESTController(applicationId, router) { function handleRequest(method, path, data = {}, options = {}) { // Store the arguments, for later use if internal fails - let args = arguments; + const args = arguments; - let config = new Config(applicationId); - let serverURL = URL.parse(config.serverURL); + const config = new Config(applicationId); + const serverURL = URL.parse(config.serverURL); if (path.indexOf(serverURL.path) === 0) { path = path.slice(serverURL.path.length, path.length); } @@ -46,7 +46,7 @@ function ParseServerRESTController(applicationId, router) { } if (path === '/batch') { - let promises = data.requests.map((request) => { + const promises = data.requests.map((request) => { return handleRequest(request.method, request.path, request.body, options).then((response) => { return Parse.Promise.as({success: response}); }, (error) => { @@ -63,7 +63,7 @@ function ParseServerRESTController(applicationId, router) { return new Parse.Promise((resolve, reject) => { getAuth(options, config).then((auth) => { - let request = { + const request = { body: data, config, auth, diff --git a/src/PromiseRouter.js b/src/PromiseRouter.js index eb6e592434..0195941e6e 100644 --- a/src/PromiseRouter.js +++ b/src/PromiseRouter.js @@ -93,10 +93,10 @@ export default class PromiseRouter { if (route.method != method) { continue; } - let layer = route.layer || new Layer(route.path, null, route.handler); - let match = layer.match(path); + const layer = route.layer || new Layer(route.path, null, route.handler); + const match = layer.match(path); if (match) { - let params = layer.params; + const params = layer.params; Object.keys(params).forEach((key) => { params[key] = validateParameter(key, params[key]); }); @@ -108,8 +108,8 @@ export default class PromiseRouter { // Mount the routes on this router onto an express app (or express router) mountOnto(expressApp) { this.routes.forEach((route) => { - let method = route.method.toLowerCase(); - let handler = makeExpressHandler(this.appId, route.handler); + const method = route.method.toLowerCase(); + const handler = makeExpressHandler(this.appId, route.handler); expressApp[method].call(expressApp, route.path, handler); }); return expressApp; @@ -140,9 +140,9 @@ export default class PromiseRouter { function makeExpressHandler(appId, promiseHandler) { return function(req, res, next) { try { - let url = maskSensitiveUrl(req); - let body = Object.assign({}, req.body); - let stringifiedBody = JSON.stringify(body, null, 2); + const url = maskSensitiveUrl(req); + const body = Object.assign({}, req.body); + const stringifiedBody = JSON.stringify(body, null, 2); log.verbose(`REQUEST for [${req.method}] ${url}: ${stringifiedBody}`, { method: req.method, url: url, @@ -155,7 +155,7 @@ function makeExpressHandler(appId, promiseHandler) { throw 'control should not get here'; } - let stringifiedResponse = JSON.stringify(result, null, 2); + const stringifiedResponse = JSON.stringify(result, null, 2); log.verbose( `RESPONSE from [${req.method}] ${url}: ${stringifiedResponse}`, {result: result} @@ -198,7 +198,7 @@ function makeExpressHandler(appId, promiseHandler) { function maskSensitiveUrl(req) { let maskUrl = req.originalUrl.toString(); - let shouldMaskUrl = req.method === 'GET' && req.originalUrl.includes('/login') + const shouldMaskUrl = req.method === 'GET' && req.originalUrl.includes('/login') && !req.originalUrl.includes('classes'); if (shouldMaskUrl) { maskUrl = log.maskSensitiveUrl(maskUrl); diff --git a/src/RestQuery.js b/src/RestQuery.js index 07a309fbf5..e6c414ce69 100644 --- a/src/RestQuery.js +++ b/src/RestQuery.js @@ -252,7 +252,7 @@ RestQuery.prototype.replaceInQuery = function() { 'improper usage of $inQuery'); } - let additionalOptions = { + const additionalOptions = { redirectClassNameForKey: inQueryValue.redirectClassNameForKey }; @@ -300,7 +300,7 @@ RestQuery.prototype.replaceNotInQuery = function() { 'improper usage of $notInQuery'); } - let additionalOptions = { + const additionalOptions = { redirectClassNameForKey: notInQueryValue.redirectClassNameForKey }; @@ -350,7 +350,7 @@ RestQuery.prototype.replaceSelect = function() { 'improper usage of $select'); } - let additionalOptions = { + const additionalOptions = { redirectClassNameForKey: selectValue.query.redirectClassNameForKey }; @@ -398,7 +398,7 @@ RestQuery.prototype.replaceDontSelect = function() { throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $dontSelect'); } - let additionalOptions = { + const additionalOptions = { redirectClassNameForKey: dontSelectValue.query.redirectClassNameForKey }; @@ -445,7 +445,7 @@ RestQuery.prototype.runFind = function(options = {}) { this.response = {results: []}; return Promise.resolve(); } - let findOptions = Object.assign({}, this.findOptions); + const findOptions = Object.assign({}, this.findOptions); if (this.keys) { findOptions.keys = this.keys.map((key) => { return key.split('.')[0]; @@ -535,23 +535,23 @@ function includePath(config, auth, response, path, restOptions = {}) { if (pointers.length == 0) { return response; } - let pointersHash = {}; + const pointersHash = {}; for (var pointer of pointers) { if (!pointer) { continue; } - let className = pointer.className; + const className = pointer.className; // only include the good pointers if (className) { pointersHash[className] = pointersHash[className] || new Set(); pointersHash[className].add(pointer.objectId); } } - let includeRestOptions = {}; + const includeRestOptions = {}; if (restOptions.keys) { - let keys = new Set(restOptions.keys.split(',')); - let keySet = Array.from(keys).reduce((set, key) => { - let keyPath = key.split('.'); + const keys = new Set(restOptions.keys.split(',')); + const keySet = Array.from(keys).reduce((set, key) => { + const keyPath = key.split('.'); let i=0; for (i; i { - let where = {'objectId': {'$in': Array.from(pointersHash[className])}}; + const queryPromises = Object.keys(pointersHash).map((className) => { + const where = {'objectId': {'$in': Array.from(pointersHash[className])}}; var query = new RestQuery(config, auth, className, where, includeRestOptions); return query.execute({op: 'get'}).then((results) => { results.className = className; @@ -682,7 +682,7 @@ function findObjectWithKey(root, key) { } if (root instanceof Array) { for (var item of root) { - let answer = findObjectWithKey(item, key); + const answer = findObjectWithKey(item, key); if (answer) { return answer; } @@ -692,7 +692,7 @@ function findObjectWithKey(root, key) { return root; } for (var subkey in root) { - let answer = findObjectWithKey(root[subkey], key); + const answer = findObjectWithKey(root[subkey], key); if (answer) { return answer; } diff --git a/src/RestWrite.js b/src/RestWrite.js index 32531959ba..188660d7af 100644 --- a/src/RestWrite.js +++ b/src/RestWrite.js @@ -153,7 +153,7 @@ RestWrite.prototype.runBeforeTrigger = function() { } let originalObject = null; - let updatedObject = triggers.inflate(extraData, this.originalData); + const updatedObject = triggers.inflate(extraData, this.originalData); if (this.query && this.query.objectId) { // This is an update for existing object. originalObject = triggers.inflate(extraData, this.originalData); @@ -221,7 +221,7 @@ RestWrite.prototype.validateAuthData = function() { var authData = this.data.authData; var providers = Object.keys(authData); if (providers.length > 0) { - let canHandleAuthData = providers.reduce((canHandle, provider) => { + const canHandleAuthData = providers.reduce((canHandle, provider) => { var providerAuthData = authData[provider]; var hasToken = (providerAuthData && providerAuthData.id); return canHandle && (hasToken || providerAuthData == null); @@ -235,11 +235,11 @@ RestWrite.prototype.validateAuthData = function() { }; RestWrite.prototype.handleAuthDataValidation = function(authData) { - let validations = Object.keys(authData).map((provider) => { + const validations = Object.keys(authData).map((provider) => { if (authData[provider] === null) { return Promise.resolve(); } - let validateAuthData = this.config.authDataManager.getValidatorForProvider(provider); + const validateAuthData = this.config.authDataManager.getValidatorForProvider(provider); if (!validateAuthData) { throw new Parse.Error(Parse.Error.UNSUPPORTED_SERVICE, 'This authentication method is unsupported.'); @@ -250,13 +250,13 @@ RestWrite.prototype.handleAuthDataValidation = function(authData) { } RestWrite.prototype.findUsersWithAuthData = function(authData) { - let providers = Object.keys(authData); - let query = providers.reduce((memo, provider) => { + const providers = Object.keys(authData); + const query = providers.reduce((memo, provider) => { if (!authData[provider]) { return memo; } - let queryKey = `authData.${provider}.id`; - let query = {}; + const queryKey = `authData.${provider}.id`; + const query = {}; query[queryKey] = authData[provider].id; memo.push(query); return memo; @@ -293,16 +293,16 @@ RestWrite.prototype.handleAuthData = function(authData) { if (!this.query) { // Login with auth data delete results[0].password; - let userResult = results[0]; + const userResult = results[0]; // need to set the objectId first otherwise location has trailing undefined this.data.objectId = userResult.objectId; // Determine if authData was updated - let mutatedAuthData = {}; + const mutatedAuthData = {}; Object.keys(authData).forEach((provider) => { - let providerData = authData[provider]; - let userAuthData = userResult.authData[provider]; + const providerData = authData[provider]; + const userAuthData = userResult.authData[provider]; if (!_.isEqual(providerData, userAuthData)) { mutatedAuthData[provider] = providerData; } @@ -489,7 +489,7 @@ RestWrite.prototype._validatePasswordHistory = function() { oldPasswords.push(user.password); const newPassword = this.data.password; // compare the new password hash with all old password hashes - let promises = oldPasswords.map(function (hash) { + const promises = oldPasswords.map(function (hash) { return passwordCrypto.compare(newPassword, hash).then((result) => { if (result) // reject if there is a match return Promise.reject("REPEAT_PASSWORD"); @@ -687,7 +687,7 @@ RestWrite.prototype.handleInstallation = function() { var deviceTokenMatches = []; // Instead of issuing 3 reads, let's do it with one OR. - let orQueries = []; + const orQueries = []; if (this.query && this.query.objectId) { orQueries.push({ objectId: this.query.objectId @@ -802,7 +802,7 @@ RestWrite.prototype.handleInstallation = function() { // 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. - let delQuery = {objectId: idMatch.objectId}; + const delQuery = {objectId: idMatch.objectId}; return this.config.database.destroy('_Installation', delQuery) .then(() => { return deviceTokenMatches[0]['objectId']; @@ -813,7 +813,7 @@ RestWrite.prototype.handleInstallation = function() { // We're setting the device token on an existing installation, so // we should try cleaning out old installations that match this // device token. - let delQuery = { + const delQuery = { 'deviceToken': this.data.deviceToken, }; // We have a unique install Id, use that to preserve @@ -1004,8 +1004,8 @@ RestWrite.prototype.runAfterTrigger = function() { } // Avoid doing any setup for triggers if there is no 'afterSave' trigger for this class. - let hasAfterSaveHook = triggers.triggerExists(this.className, triggers.Types.afterSave, this.config.applicationId); - let hasLiveQuery = this.config.liveQueryController.hasLiveQuery(this.className); + const hasAfterSaveHook = triggers.triggerExists(this.className, triggers.Types.afterSave, this.config.applicationId); + const hasLiveQuery = this.config.liveQueryController.hasLiveQuery(this.className); if (!hasAfterSaveHook && !hasLiveQuery) { return Promise.resolve(); } @@ -1023,7 +1023,7 @@ RestWrite.prototype.runAfterTrigger = function() { // Build the inflated object, different from beforeSave, originalData is not empty // since developers can change data in the beforeSave. - let updatedObject = triggers.inflate(extraData, this.originalData); + const updatedObject = triggers.inflate(extraData, this.originalData); updatedObject.set(this.sanitizedData()); updatedObject._handleSaveResponse(this.response.response, this.response.status || 200); @@ -1049,7 +1049,7 @@ RestWrite.prototype.objectId = function() { // Returns a copy of the data and delete bad keys (_auth_data, _hashed_password...) RestWrite.prototype.sanitizedData = function() { - let data = Object.keys(this.data).reduce((data, key) => { + const data = Object.keys(this.data).reduce((data, key) => { // Regexp comes from Parse.Object.prototype.validate if (!(/^[A-Za-z][0-9A-Za-z_]*$/).test(key)) { delete data[key]; @@ -1061,7 +1061,7 @@ RestWrite.prototype.sanitizedData = function() { RestWrite.prototype.cleanUserAuthData = function() { if (this.response && this.response.response && this.className === '_User') { - let user = this.response.response; + const user = this.response.response; if (user.authData) { Object.keys(user.authData).forEach((provider) => { if (user.authData[provider] === null) { @@ -1079,10 +1079,10 @@ RestWrite.prototype._updateResponseWithData = function(response, data) { if (_.isEmpty(this.storage.fieldsChangedByTrigger)) { return response; } - let clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK); + const clientSupportsDelete = ClientSDK.supportsForwardDelete(this.clientSDK); this.storage.fieldsChangedByTrigger.forEach(fieldName => { - let dataValue = data[fieldName]; - let responseValue = response[fieldName]; + const dataValue = data[fieldName]; + const responseValue = response[fieldName]; response[fieldName] = responseValue || dataValue; diff --git a/src/Routers/ClassesRouter.js b/src/Routers/ClassesRouter.js index 110e38546b..2e954619ed 100644 --- a/src/Routers/ClassesRouter.js +++ b/src/Routers/ClassesRouter.js @@ -9,12 +9,12 @@ const ALLOWED_GET_QUERY_KEYS = ['keys', 'include']; export class ClassesRouter extends PromiseRouter { handleFind(req) { - let body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); - let options = {}; - let allowConstraints = ['skip', 'limit', 'order', 'count', 'keys', + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); + const options = {}; + const allowConstraints = ['skip', 'limit', 'order', 'count', 'keys', 'include', 'redirectClassNameForKey', 'where']; - for (let key of Object.keys(body)) { + 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}`); } @@ -49,7 +49,7 @@ export class ClassesRouter extends PromiseRouter { return rest.find(req.config, req.auth, req.params.className, body.where, options, req.info.clientSDK) .then((response) => { if (response && response.results) { - for (let result of response.results) { + for (const result of response.results) { if (result.sessionToken) { result.sessionToken = req.info.sessionToken || result.sessionToken; } @@ -61,10 +61,10 @@ export class ClassesRouter extends PromiseRouter { // Returns a promise for a {response} object. handleGet(req) { - let body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); - let options = {}; + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); + const options = {}; - for (let key of Object.keys(body)) { + 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'); } @@ -114,8 +114,8 @@ export class ClassesRouter extends PromiseRouter { } static JSONFromQuery(query) { - let json = {}; - for (let [key, value] of _.entries(query)) { + const json = {}; + for (const [key, value] of _.entries(query)) { try { json[key] = JSON.parse(value); } catch (e) { diff --git a/src/Routers/CloudCodeRouter.js b/src/Routers/CloudCodeRouter.js index 72501efa4a..0cf45b475d 100644 --- a/src/Routers/CloudCodeRouter.js +++ b/src/Routers/CloudCodeRouter.js @@ -7,8 +7,8 @@ export class CloudCodeRouter extends PromiseRouter { } static getJobs(req) { - let config = req.config; - let jobs = triggers.getJobs(config.applicationId) || {}; + const config = req.config; + const jobs = triggers.getJobs(config.applicationId) || {}; return Promise.resolve({ response: Object.keys(jobs).map((jobName) => { return { diff --git a/src/Routers/GlobalConfigRouter.js b/src/Routers/GlobalConfigRouter.js index b2feb0c229..dce5c280e5 100644 --- a/src/Routers/GlobalConfigRouter.js +++ b/src/Routers/GlobalConfigRouter.js @@ -10,13 +10,13 @@ export class GlobalConfigRouter extends PromiseRouter { // If there is no config in the database - return empty config. return { response: { params: {} } }; } - let globalConfig = results[0]; + const globalConfig = results[0]; return { response: { params: globalConfig.params } }; }); } updateGlobalConfig(req) { - let params = req.body.params; + const params = req.body.params; // Transform in dot notation to make sure it works const update = Object.keys(params).reduce((acc, key) => { acc[`params.${key}`] = params[key]; diff --git a/src/Routers/InstallationsRouter.js b/src/Routers/InstallationsRouter.js index 38f5a34c42..d54b1138e7 100644 --- a/src/Routers/InstallationsRouter.js +++ b/src/Routers/InstallationsRouter.js @@ -5,7 +5,7 @@ import rest from '../rest'; export class InstallationsRouter extends ClassesRouter { handleFind(req) { - let body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); + const body = Object.assign(req.body, ClassesRouter.JSONFromQuery(req.query)); var options = {}; if (body.skip) { diff --git a/src/Routers/PublicAPIRouter.js b/src/Routers/PublicAPIRouter.js index 4e28aac400..e3a569ffb4 100644 --- a/src/Routers/PublicAPIRouter.js +++ b/src/Routers/PublicAPIRouter.js @@ -5,15 +5,15 @@ import path from 'path'; import fs from 'fs'; import qs from 'querystring'; -let public_html = path.resolve(__dirname, "../../public_html"); -let views = path.resolve(__dirname, '../../views'); +const public_html = path.resolve(__dirname, "../../public_html"); +const views = path.resolve(__dirname, '../../views'); export class PublicAPIRouter extends PromiseRouter { verifyEmail(req) { - let { token, username }= req.query; - let appId = req.params.appId; - let config = new Config(appId); + const { token, username } = req.query; + const appId = req.params.appId; + const config = new Config(appId); if (!config.publicServerURL) { return this.missingPublicServerURL(); @@ -23,9 +23,9 @@ export class PublicAPIRouter extends PromiseRouter { return this.invalidLink(req); } - let userController = config.userController; + const userController = config.userController; return userController.verifyEmail(username, token).then(() => { - let params = qs.stringify({username}); + const params = qs.stringify({username}); return Promise.resolve({ status: 302, location: `${config.verifyEmailSuccessURL}?${params}` @@ -37,7 +37,7 @@ export class PublicAPIRouter extends PromiseRouter { changePassword(req) { return new Promise((resolve, reject) => { - let config = new Config(req.query.id); + const config = new Config(req.query.id); if (!config.publicServerURL) { return resolve({ status: 404, @@ -59,20 +59,20 @@ export class PublicAPIRouter extends PromiseRouter { requestResetPassword(req) { - let config = req.config; + const config = req.config; if (!config.publicServerURL) { return this.missingPublicServerURL(); } - let { username, token } = req.query; + const { username, token } = req.query; if (!username || !token) { return this.invalidLink(req); } return config.userController.checkResetTokenValidity(username, token).then(() => { - let params = qs.stringify({token, id: config.applicationId, username, app: config.appName, }); + const params = qs.stringify({token, id: config.applicationId, username, app: config.appName, }); return Promise.resolve({ status: 302, location: `${config.choosePasswordURL}?${params}` @@ -84,13 +84,13 @@ export class PublicAPIRouter extends PromiseRouter { resetPassword(req) { - let config = req.config; + const config = req.config; if (!config.publicServerURL) { return this.missingPublicServerURL(); } - let { + const { username, token, new_password @@ -101,13 +101,13 @@ export class PublicAPIRouter extends PromiseRouter { } return config.userController.updatePassword(username, token, new_password).then(() => { - let params = qs.stringify({username: username}); + const params = qs.stringify({username: username}); return Promise.resolve({ status: 302, location: `${config.passwordResetSuccessURL}?${params}` }); }, (err) => { - let params = qs.stringify({username: username, token: token, id: config.applicationId, error:err, app:config.appName}) + const params = qs.stringify({username: username, token: token, id: config.applicationId, error:err, app:config.appName}) return Promise.resolve({ status: 302, location: `${config.choosePasswordURL}?${params}` @@ -153,7 +153,7 @@ export class PublicAPIRouter extends PromiseRouter { } expressRouter() { - let router = express.Router(); + const router = express.Router(); router.use("/apps", express.static(public_html)); router.use("/", super.expressRouter()); return router; diff --git a/src/Routers/PushRouter.js b/src/Routers/PushRouter.js index 08a633fda2..ace3cf80b0 100644 --- a/src/Routers/PushRouter.js +++ b/src/Routers/PushRouter.js @@ -14,9 +14,9 @@ export class PushRouter extends PromiseRouter { throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Push controller is not set'); } - let where = PushRouter.getQueryCondition(req); + const where = PushRouter.getQueryCondition(req); let resolve; - let promise = new Promise((_resolve) => { + const promise = new Promise((_resolve) => { resolve = _resolve; }); pushController.sendPush(req.body, where, req.config, req.auth, (pushStatusId) => { @@ -38,9 +38,9 @@ export class PushRouter extends PromiseRouter { * @returns {Object} The query condition, the where field in a query api call */ static getQueryCondition(req) { - let body = req.body || {}; - let hasWhere = typeof body.where !== 'undefined'; - let hasChannels = typeof body.channels !== 'undefined'; + const body = req.body || {}; + const hasWhere = typeof body.where !== 'undefined'; + const hasChannels = typeof body.channels !== 'undefined'; let where; if (hasWhere && hasChannels) { diff --git a/src/Routers/SchemasRouter.js b/src/Routers/SchemasRouter.js index f69a18eb7f..7a5b5e3374 100644 --- a/src/Routers/SchemasRouter.js +++ b/src/Routers/SchemasRouter.js @@ -55,8 +55,8 @@ function modifySchema(req) { return classNameMismatchResponse(req.body.className, req.params.className); } - let submittedFields = req.body.fields || {}; - let className = req.params.className; + const submittedFields = req.body.fields || {}; + const className = req.params.className; return req.config.database.loadSchema({ clearCache: true}) .then(schema => schema.updateClass(className, submittedFields, req.body.classLevelPermissions, req.config.database)) diff --git a/src/Routers/UsersRouter.js b/src/Routers/UsersRouter.js index f4c37f716c..a281bb4208 100644 --- a/src/Routers/UsersRouter.js +++ b/src/Routers/UsersRouter.js @@ -9,7 +9,7 @@ import rest from '../rest'; import Auth from '../Auth'; import passwordCrypto from '../password'; import RestWrite from '../RestWrite'; -let cryptoUtils = require('../cryptoUtils'); +const cryptoUtils = require('../cryptoUtils'); export class UsersRouter extends ClassesRouter { handleFind(req) { @@ -23,7 +23,7 @@ export class UsersRouter extends ClassesRouter { } handleCreate(req) { - let data = deepcopy(req.body); + const data = deepcopy(req.body); req.body = data; req.params.className = '_User'; @@ -44,7 +44,7 @@ export class UsersRouter extends ClassesRouter { if (!req.info || !req.info.sessionToken) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token'); } - let sessionToken = req.info.sessionToken; + const sessionToken = req.info.sessionToken; return rest.find(req.config, Auth.master(req.config), '_Session', { sessionToken }, { include: 'user' }, req.info.clientSDK) @@ -54,7 +54,7 @@ export class UsersRouter extends ClassesRouter { !response.results[0].user) { throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'invalid session token'); } else { - let user = response.results[0].user; + const user = response.results[0].user; // Send token back on the login, because SDKs expect that. user.sessionToken = sessionToken; return { response: user }; @@ -96,7 +96,7 @@ export class UsersRouter extends ClassesRouter { }) .then((correct) => { isValidPassword = correct; - let accountLockoutPolicy = new AccountLockout(user, req.config); + const accountLockoutPolicy = new AccountLockout(user, req.config); return accountLockoutPolicy.handleLoginAttempt(isValidPassword); }) .then(() => { @@ -126,7 +126,7 @@ export class UsersRouter extends ClassesRouter { } } - let token = 'r:' + cryptoUtils.newToken(); + const token = 'r:' + cryptoUtils.newToken(); user.sessionToken = token; delete user.password; @@ -145,8 +145,8 @@ export class UsersRouter extends ClassesRouter { req.config.filesController.expandFilesInObject(req.config, user); - let expiresAt = req.config.generateSessionExpiresAt(); - let sessionData = { + const expiresAt = req.config.generateSessionExpiresAt(); + const sessionData = { sessionToken: token, user: { __type: 'Pointer', @@ -165,7 +165,7 @@ export class UsersRouter extends ClassesRouter { sessionData.installationId = req.info.installationId } - let create = new RestWrite(req.config, Auth.master(req.config), '_Session', null, sessionData); + const create = new RestWrite(req.config, Auth.master(req.config), '_Session', null, sessionData); return create.execute(); }).then(() => { return { response: user }; @@ -173,7 +173,7 @@ export class UsersRouter extends ClassesRouter { } handleLogOut(req) { - let success = {response: {}}; + const success = {response: {}}; if (req.info && req.info.sessionToken) { return rest.find(req.config, Auth.master(req.config), '_Session', { sessionToken: req.info.sessionToken }, undefined, req.info.clientSDK @@ -207,14 +207,14 @@ export class UsersRouter extends ClassesRouter { throw e; } } - let { email } = req.body; + const { email } = req.body; if (!email) { throw new Parse.Error(Parse.Error.EMAIL_MISSING, "you must provide an email"); } if (typeof email !== 'string') { throw new Parse.Error(Parse.Error.INVALID_EMAIL_ADDRESS, 'you must provide a valid email string'); } - let userController = req.config.userController; + const userController = req.config.userController; return userController.sendPasswordResetEmail(email).then(() => { return Promise.resolve({ response: {} diff --git a/src/StatusHandler.js b/src/StatusHandler.js index 47d5592b96..116f432310 100644 --- a/src/StatusHandler.js +++ b/src/StatusHandler.js @@ -42,11 +42,11 @@ function statusHandler(className, database) { export function jobStatusHandler(config) { let jobStatus; - let objectId = newObjectId(); - let database = config.database; - let handler = statusHandler(JOB_STATUS_COLLECTION, database); - let setRunning = function(jobName, params) { - let now = new Date(); + const objectId = newObjectId(); + const database = config.database; + const handler = statusHandler(JOB_STATUS_COLLECTION, database); + const setRunning = function(jobName, params) { + const now = new Date(); jobStatus = { objectId, jobName, @@ -61,24 +61,24 @@ export function jobStatusHandler(config) { return handler.create(jobStatus); } - let setMessage = function(message) { + const setMessage = function(message) { if (!message || typeof message !== 'string') { return Promise.resolve(); } return handler.update({ objectId }, { message }); } - let setSucceeded = function(message) { + const setSucceeded = function(message) { return setFinalStatus('succeeded', message); } - let setFailed = function(message) { + const setFailed = function(message) { return setFinalStatus('failed', message); } - let setFinalStatus = function(status, message = undefined) { - let finishedAt = new Date(); - let update = { status, finishedAt }; + const setFinalStatus = function(status, message = undefined) { + const finishedAt = new Date(); + const update = { status, finishedAt }; if (message && typeof message === 'string') { update.message = message; } @@ -96,13 +96,13 @@ export function jobStatusHandler(config) { export function pushStatusHandler(config) { let pushStatus; - let objectId = newObjectId(); - let database = config.database; - let handler = statusHandler(PUSH_STATUS_COLLECTION, database); - let setInitial = function(body = {}, where, options = {source: 'rest'}) { - let now = new Date(); - let data = body.data || {}; - let payloadString = JSON.stringify(data); + const objectId = newObjectId(); + const database = config.database; + const handler = statusHandler(PUSH_STATUS_COLLECTION, database); + const setInitial = function(body = {}, where, options = {source: 'rest'}) { + const now = new Date(); + const data = body.data || {}; + const payloadString = JSON.stringify(data); let pushHash; if (typeof data.alert === 'string') { pushHash = md5Hash(data.alert); @@ -111,7 +111,7 @@ export function pushStatusHandler(config) { } else { pushHash = 'd41d8cd98f00b204e9800998ecf8427e'; } - let object = { + const object = { objectId, createdAt: now, pushTime: now.toISOString(), @@ -135,14 +135,14 @@ export function pushStatusHandler(config) { }); } - let setRunning = function(installations) { + const setRunning = function(installations) { logger.verbose('sending push to %d installations', installations.length); return handler.update({status:"pending", objectId: objectId}, {status: "running", updatedAt: new Date() }); } - let complete = function(results) { - let update = { + const complete = function(results) { + const update = { status: 'succeeded', updatedAt: new Date(), numSent: 0, @@ -155,7 +155,7 @@ export function pushStatusHandler(config) { if (!result || !result.device || !result.device.deviceType) { return memo; } - let deviceType = result.device.deviceType; + const deviceType = result.device.deviceType; if (result.transmitted) { memo.numSent++; @@ -175,8 +175,8 @@ export function pushStatusHandler(config) { return handler.update({status:"running", objectId }, update); } - let fail = function(err) { - let update = { + const fail = function(err) { + const update = { errorMessage: JSON.stringify(err), status: 'failed', updatedAt: new Date() diff --git a/src/batch.js b/src/batch.js index 93b6636209..a8eca6e20e 100644 --- a/src/batch.js +++ b/src/batch.js @@ -22,10 +22,10 @@ function makeBatchRoutingPathFunction(originalUrl, serverURL, publicServerURL) { serverURL = serverURL ? parseURL(serverURL) : undefined; publicServerURL = publicServerURL ? parseURL(publicServerURL): undefined; - let apiPrefixLength = originalUrl.length - batchPath.length; + const apiPrefixLength = originalUrl.length - batchPath.length; let apiPrefix = originalUrl.slice(0, apiPrefixLength); - let makeRoutablePath = function(requestPath) { + const makeRoutablePath = function(requestPath) { // The routablePath is the path minus the api prefix if (requestPath.slice(0, apiPrefix.length) != apiPrefix) { throw new Parse.Error( @@ -37,14 +37,14 @@ function makeBatchRoutingPathFunction(originalUrl, serverURL, publicServerURL) { if (serverURL && publicServerURL && (serverURL.path != publicServerURL.path)) { - let localPath = serverURL.path; - let publicPath = publicServerURL.path; + const localPath = serverURL.path; + const publicPath = publicServerURL.path; // Override the api prefix apiPrefix = localPath; return function(requestPath) { // Build the new path by removing the public path // and joining with the local path - let newPath = path.posix.join('/', localPath, '/' , requestPath.slice(publicPath.length)); + const newPath = path.posix.join('/', localPath, '/' , requestPath.slice(publicPath.length)); // Use the method for local routing return makeRoutablePath(newPath); } diff --git a/src/cli/parse-server.js b/src/cli/parse-server.js index a0ab839144..ef0a7f7495 100755 --- a/src/cli/parse-server.js +++ b/src/cli/parse-server.js @@ -35,7 +35,7 @@ function startServer(options, callback) { app.use(options.mountPath, api); - let server = app.listen(options.port, options.host, callback); + const server = app.listen(options.port, options.host, callback); server.on('connection', initializeConnections); if (options.startLiveQueryServer || options.liveQueryServerOptions) { @@ -69,7 +69,7 @@ function startServer(options, callback) { } } - let handleShutdown = function() { + const handleShutdown = function() { console.log('Termination signal received. Shutting down.'); destroyAliveConnections(); server.close(function () { diff --git a/src/cli/utils/commander.js b/src/cli/utils/commander.js index 23a02f32c9..edf75c28a1 100644 --- a/src/cli/utils/commander.js +++ b/src/cli/utils/commander.js @@ -68,7 +68,7 @@ function parseConfigFile(program) { if (program.args.length > 0) { let jsonPath = program.args[0]; jsonPath = path.resolve(jsonPath); - let jsonConfig = require(jsonPath); + const jsonConfig = require(jsonPath); if (jsonConfig.apps) { if (jsonConfig.apps.length > 1) { throw 'Multiple apps are not supported'; @@ -78,11 +78,11 @@ function parseConfigFile(program) { options = jsonConfig; } Object.keys(options).forEach((key) => { - let value = options[key]; + const value = options[key]; if (!_definitions[key]) { throw `error: unknown option ${key}`; } - let action = _definitions[key].action; + const action = _definitions[key].action; if (action) { options[key] = action(value); } diff --git a/src/cli/utils/runner.js b/src/cli/utils/runner.js index 956144df4f..cf4ed25381 100644 --- a/src/cli/utils/runner.js +++ b/src/cli/utils/runner.js @@ -2,7 +2,7 @@ import program from './commander'; function logStartupOptions(options) { - for (let key in options) { + for (const key in options) { let value = options[key]; if (key == "masterKey") { value = "***REDACTED***"; @@ -31,7 +31,7 @@ export default function({ } program.parse(process.argv, process.env); - let options = program.getOptions(); + const options = program.getOptions(); start(program, options, function() { logStartupOptions(options); }); diff --git a/src/cloud-code/HTTPResponse.js b/src/cloud-code/HTTPResponse.js index 6e6f25d1e7..85613c8747 100644 --- a/src/cloud-code/HTTPResponse.js +++ b/src/cloud-code/HTTPResponse.js @@ -14,7 +14,7 @@ export default class HTTPResponse { _data = body; } - let getText = () => { + const getText = () => { if (!_text && this.buffer) { _text = this.buffer.toString('utf-8'); } else if (!_text && _data) { @@ -23,7 +23,7 @@ export default class HTTPResponse { return _text; } - let getData = () => { + const getData = () => { if (!_data) { try { _data = JSON.parse(getText()); diff --git a/src/cloud-code/httpRequest.js b/src/cloud-code/httpRequest.js index 820500733d..32102341ef 100644 --- a/src/cloud-code/httpRequest.js +++ b/src/cloud-code/httpRequest.js @@ -62,7 +62,7 @@ module.exports = function(options) { } return promise.reject(error); } - let httpResponse = new HTTPResponse(response, body); + const httpResponse = new HTTPResponse(response, body); // Consider <200 && >= 400 as errors if (httpResponse.status < 200 || httpResponse.status >= 400) { diff --git a/src/cryptoUtils.js b/src/cryptoUtils.js index 4b529293b7..f29260bb63 100644 --- a/src/cryptoUtils.js +++ b/src/cryptoUtils.js @@ -23,11 +23,11 @@ export function randomString(size: number): string { if (size === 0) { throw new Error('Zero-length randomString is useless.'); } - let chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' + + const chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789'); let objectId = ''; - let bytes = randomBytes(size); + const bytes = randomBytes(size); for (let i = 0; i < bytes.length; ++i) { objectId += chars[bytes.readUInt8(i) % chars.length]; } diff --git a/src/defaults.js b/src/defaults.js index c2d647c4ca..7be96a45a9 100644 --- a/src/defaults.js +++ b/src/defaults.js @@ -1,6 +1,6 @@ import {nullParser} from './cli/utils/parsers'; -let logsFolder = (() => { +const logsFolder = (() => { let folder = './logs/'; if (typeof process !== 'undefined' && process.env.NODE_ENV === 'test') { folder = './test_logs/' @@ -11,8 +11,8 @@ let logsFolder = (() => { return folder; })(); -let { verbose, level } = (() => { - let verbose = process.env.VERBOSE ? true : false; +const { verbose, level } = (() => { + const verbose = process.env.VERBOSE ? true : false; return { verbose, level: verbose ? 'verbose' : undefined } })(); diff --git a/src/index.js b/src/index.js index 6d85bf990d..5878d28ecc 100644 --- a/src/index.js +++ b/src/index.js @@ -9,14 +9,14 @@ import { useExternal } from './deprecated'; import { getLogger } from './logger'; // Factory function -let _ParseServer = function(options) { - let server = new ParseServer(options); +const _ParseServer = function(options) { + const server = new ParseServer(options); return server.app; } // Mount the create liveQueryServer _ParseServer.createLiveQueryServer = ParseServer.createLiveQueryServer; -let GCSAdapter = useExternal('GCSAdapter', 'parse-server-gcs-adapter'); +const GCSAdapter = useExternal('GCSAdapter', 'parse-server-gcs-adapter'); Object.defineProperty(module.exports, 'logger', { get: getLogger diff --git a/src/logger.js b/src/logger.js index bc4d49bcf2..59baff3954 100644 --- a/src/logger.js +++ b/src/logger.js @@ -4,7 +4,7 @@ import { WinstonLoggerAdapter } from './Adapters/Logger/WinstonLoggerAdapter'; import { LoggerController } from './Controllers/LoggerController'; function defaultLogger() { - let adapter = new WinstonLoggerAdapter({ + const adapter = new WinstonLoggerAdapter({ logsFolder: defaults.logsFolder, jsonLogs: defaults.jsonLogs, verbose: defaults.verbose, diff --git a/src/middlewares.js b/src/middlewares.js index 1e80f796ed..482c773ba6 100644 --- a/src/middlewares.js +++ b/src/middlewares.js @@ -274,7 +274,7 @@ export function enforceMasterKeyAccess(req, res, next) { export function promiseEnforceMasterKeyAccess(request) { if (!request.auth.isMaster) { - let error = new Error(); + const error = new Error(); error.status = 403; error.message = "unauthorized: master key is required"; throw error; diff --git a/src/rest.js b/src/rest.js index 7ecec62e36..07cf2b4dff 100644 --- a/src/rest.js +++ b/src/rest.js @@ -20,7 +20,7 @@ function find(config, auth, className, restWhere, restOptions, clientSDK) { return triggers.maybeRunQueryTrigger(triggers.Types.beforeFind, className, restWhere, restOptions, config, auth).then((result) => { restWhere = result.restWhere || restWhere; restOptions = result.restOptions || restOptions; - let query = new RestQuery(config, auth, className, restWhere, restOptions, clientSDK); + const query = new RestQuery(config, auth, className, restWhere, restOptions, clientSDK); return query.execute(); }); } @@ -28,7 +28,7 @@ function find(config, auth, className, restWhere, restOptions, clientSDK) { // get is just like find but only queries an objectId. const get = (config, auth, className, objectId, restOptions, clientSDK) => { enforceRoleSecurity('get', className, auth); - let query = new RestQuery(config, auth, className, { objectId }, restOptions, clientSDK); + const query = new RestQuery(config, auth, className, { objectId }, restOptions, clientSDK); return query.execute(); } @@ -129,7 +129,7 @@ function update(config, auth, className, objectId, restObject, clientSDK) { function enforceRoleSecurity(method, className, auth) { if (className === '_Installation' && !auth.isMaster) { if (method === 'delete' || method === 'find') { - let error = `Clients aren't allowed to perform the ${method} operation on the installation collection.` + const error = `Clients aren't allowed to perform the ${method} operation on the installation collection.` throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error); } } diff --git a/src/triggers.js b/src/triggers.js index 8b5fe28137..8acd51ac6e 100644 --- a/src/triggers.js +++ b/src/triggers.js @@ -12,10 +12,10 @@ export const Types = { }; const baseStore = function() { - let Validators = {}; - let Functions = {}; - let Jobs = {}; - let Triggers = Object.keys(Types).reduce(function(base, key){ + const Validators = {}; + const Functions = {}; + const Jobs = {}; + const Triggers = Object.keys(Types).reduce(function(base, key){ base[key] = {}; return base; }, {}); @@ -286,7 +286,7 @@ export function maybeRunAfterFindTrigger(triggerType, auth, className, objects, } export function maybeRunQueryTrigger(triggerType, className, restWhere, restOptions, config, auth) { - let trigger = getTrigger(className, triggerType, config.applicationId); + const trigger = getTrigger(className, triggerType, config.applicationId); if (!trigger) { return Promise.resolve({ restWhere, @@ -294,7 +294,7 @@ export function maybeRunQueryTrigger(triggerType, className, restWhere, restOpti }); } - let parseQuery = new Parse.Query(className); + const parseQuery = new Parse.Query(className); if (restWhere) { parseQuery._where = restWhere; } @@ -309,7 +309,7 @@ export function maybeRunQueryTrigger(triggerType, className, restWhere, restOpti parseQuery._limit = restOptions.limit; } } - let requestObject = getRequestQueryObject(triggerType, auth, parseQuery, config); + const requestObject = getRequestQueryObject(triggerType, auth, parseQuery, config); return Promise.resolve().then(() => { return trigger(requestObject); }).then((result) => { @@ -317,7 +317,7 @@ export function maybeRunQueryTrigger(triggerType, className, restWhere, restOpti if (result && result instanceof Parse.Query) { queryResult = result; } - let jsonQuery = queryResult.toJSON(); + const jsonQuery = queryResult.toJSON(); if (jsonQuery.where) { restWhere = jsonQuery.where; }