12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001 |
- "use strict";
- var SchemaController = require('./Controllers/SchemaController');
- var Parse = require('parse/node').Parse;
- const triggers = require('./triggers');
- const {
- continueWhile
- } = require('parse/lib/node/promiseUtils');
- const AlwaysSelectedKeys = ['objectId', 'createdAt', 'updatedAt', 'ACL'];
- const {
- enforceRoleSecurity
- } = require('./SharedRest');
- async function RestQuery({
- method,
- config,
- auth,
- className,
- restWhere = {},
- restOptions = {},
- clientSDK,
- runAfterFind = true,
- runBeforeFind = true,
- context
- }) {
- if (![RestQuery.Method.find, RestQuery.Method.get].includes(method)) {
- throw new Parse.Error(Parse.Error.INVALID_QUERY, 'bad query type');
- }
- enforceRoleSecurity(method, className, auth);
- const result = runBeforeFind ? await triggers.maybeRunQueryTrigger(triggers.Types.beforeFind, className, restWhere, restOptions, config, auth, context, method === RestQuery.Method.get) : Promise.resolve({
- restWhere,
- restOptions
- });
- return new _UnsafeRestQuery(config, auth, className, result.restWhere || restWhere, result.restOptions || restOptions, clientSDK, runAfterFind, context);
- }
- RestQuery.Method = Object.freeze({
- get: 'get',
- find: 'find'
- });
- function _UnsafeRestQuery(config, auth, className, restWhere = {}, restOptions = {}, clientSDK, runAfterFind = true, context) {
- this.config = config;
- this.auth = auth;
- this.className = className;
- this.restWhere = restWhere;
- this.restOptions = restOptions;
- this.clientSDK = clientSDK;
- this.runAfterFind = runAfterFind;
- this.response = null;
- this.findOptions = {};
- this.context = context || {};
- if (!this.auth.isMaster) {
- if (this.className == '_Session') {
- if (!this.auth.user) {
- throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN, 'Invalid session token');
- }
- this.restWhere = {
- $and: [this.restWhere, {
- user: {
- __type: 'Pointer',
- className: '_User',
- objectId: this.auth.user.id
- }
- }]
- };
- }
- }
- this.doCount = false;
- this.includeAll = false;
-
-
-
-
-
-
- this.include = [];
- let keysForInclude = '';
-
-
- if (Object.prototype.hasOwnProperty.call(restOptions, 'keys')) {
- keysForInclude = restOptions.keys;
- }
-
-
- if (Object.prototype.hasOwnProperty.call(restOptions, 'excludeKeys')) {
- keysForInclude += ',' + restOptions.excludeKeys;
- }
- if (keysForInclude.length > 0) {
- keysForInclude = keysForInclude.split(',').filter(key => {
-
- return key.split('.').length > 1;
- }).map(key => {
-
-
- return key.slice(0, key.lastIndexOf('.'));
- }).join(',');
-
-
- if (keysForInclude.length > 0) {
- if (!restOptions.include || restOptions.include.length == 0) {
- restOptions.include = keysForInclude;
- } else {
- restOptions.include += ',' + keysForInclude;
- }
- }
- }
- for (var option in restOptions) {
- switch (option) {
- case 'keys':
- {
- const keys = restOptions.keys.split(',').filter(key => key.length > 0).concat(AlwaysSelectedKeys);
- this.keys = Array.from(new Set(keys));
- break;
- }
- case 'excludeKeys':
- {
- const exclude = restOptions.excludeKeys.split(',').filter(k => AlwaysSelectedKeys.indexOf(k) < 0);
- this.excludeKeys = Array.from(new Set(exclude));
- break;
- }
- case 'count':
- this.doCount = true;
- break;
- case 'includeAll':
- this.includeAll = true;
- break;
- case 'explain':
- case 'hint':
- case 'distinct':
- case 'pipeline':
- case 'skip':
- case 'limit':
- case 'readPreference':
- case 'comment':
- this.findOptions[option] = restOptions[option];
- break;
- case 'order':
- var fields = restOptions.order.split(',');
- this.findOptions.sort = fields.reduce((sortMap, field) => {
- field = field.trim();
- if (field === '$score' || field === '-$score') {
- sortMap.score = {
- $meta: 'textScore'
- };
- } else if (field[0] == '-') {
- sortMap[field.slice(1)] = -1;
- } else {
- sortMap[field] = 1;
- }
- return sortMap;
- }, {});
- break;
- case 'include':
- {
- const paths = restOptions.include.split(',');
- if (paths.includes('*')) {
- this.includeAll = true;
- break;
- }
-
- const pathSet = paths.reduce((memo, path) => {
-
-
-
- return path.split('.').reduce((memo, path, index, parts) => {
- memo[parts.slice(0, index + 1).join('.')] = true;
- return memo;
- }, memo);
- }, {});
- this.include = Object.keys(pathSet).map(s => {
- return s.split('.');
- }).sort((a, b) => {
- return a.length - b.length;
- });
- break;
- }
- case 'redirectClassNameForKey':
- this.redirectKey = restOptions.redirectClassNameForKey;
- this.redirectClassName = null;
- break;
- case 'includeReadPreference':
- case 'subqueryReadPreference':
- break;
- default:
- throw new Parse.Error(Parse.Error.INVALID_JSON, 'bad option: ' + option);
- }
- }
- }
- _UnsafeRestQuery.prototype.execute = function (executeOptions) {
- return Promise.resolve().then(() => {
- return this.buildRestWhere();
- }).then(() => {
- return this.denyProtectedFields();
- }).then(() => {
- return this.handleIncludeAll();
- }).then(() => {
- return this.handleExcludeKeys();
- }).then(() => {
- return this.runFind(executeOptions);
- }).then(() => {
- return this.runCount();
- }).then(() => {
- return this.handleInclude();
- }).then(() => {
- return this.runAfterFindTrigger();
- }).then(() => {
- return this.handleAuthAdapters();
- }).then(() => {
- return this.response;
- });
- };
- _UnsafeRestQuery.prototype.each = function (callback) {
- const {
- config,
- auth,
- className,
- restWhere,
- restOptions,
- clientSDK
- } = this;
-
- restOptions.limit = restOptions.limit || 100;
- restOptions.order = 'objectId';
- let finished = false;
- return continueWhile(() => {
- return !finished;
- }, async () => {
-
-
- const query = new _UnsafeRestQuery(config, auth, className, restWhere, restOptions, clientSDK, this.runAfterFind, this.context);
- const {
- results
- } = await query.execute();
- results.forEach(callback);
- finished = results.length < restOptions.limit;
- if (!finished) {
- restWhere.objectId = Object.assign({}, restWhere.objectId, {
- $gt: results[results.length - 1].objectId
- });
- }
- });
- };
- _UnsafeRestQuery.prototype.buildRestWhere = function () {
- return Promise.resolve().then(() => {
- return this.getUserAndRoleACL();
- }).then(() => {
- return this.redirectClassNameForKey();
- }).then(() => {
- return this.validateClientClassCreation();
- }).then(() => {
- return this.replaceSelect();
- }).then(() => {
- return this.replaceDontSelect();
- }).then(() => {
- return this.replaceInQuery();
- }).then(() => {
- return this.replaceNotInQuery();
- }).then(() => {
- return this.replaceEquality();
- });
- };
- _UnsafeRestQuery.prototype.getUserAndRoleACL = function () {
- if (this.auth.isMaster) {
- return Promise.resolve();
- }
- this.findOptions.acl = ['*'];
- if (this.auth.user) {
- return this.auth.getUserRoles().then(roles => {
- this.findOptions.acl = this.findOptions.acl.concat(roles, [this.auth.user.id]);
- return;
- });
- } else {
- return Promise.resolve();
- }
- };
- _UnsafeRestQuery.prototype.redirectClassNameForKey = function () {
- if (!this.redirectKey) {
- return Promise.resolve();
- }
-
- return this.config.database.redirectClassNameForKey(this.className, this.redirectKey).then(newClassName => {
- this.className = newClassName;
- this.redirectClassName = newClassName;
- });
- };
- _UnsafeRestQuery.prototype.validateClientClassCreation = function () {
- if (this.config.allowClientClassCreation === false && !this.auth.isMaster && SchemaController.systemClasses.indexOf(this.className) === -1) {
- return this.config.database.loadSchema().then(schemaController => schemaController.hasClass(this.className)).then(hasClass => {
- if (hasClass !== true) {
- throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'This user is not allowed to access ' + 'non-existent class: ' + this.className);
- }
- });
- } else {
- return Promise.resolve();
- }
- };
- function transformInQuery(inQueryObject, className, results) {
- var values = [];
- for (var result of results) {
- values.push({
- __type: 'Pointer',
- className: className,
- objectId: result.objectId
- });
- }
- delete inQueryObject['$inQuery'];
- if (Array.isArray(inQueryObject['$in'])) {
- inQueryObject['$in'] = inQueryObject['$in'].concat(values);
- } else {
- inQueryObject['$in'] = values;
- }
- }
- _UnsafeRestQuery.prototype.replaceInQuery = async function () {
- var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery');
- if (!inQueryObject) {
- return;
- }
-
- var inQueryValue = inQueryObject['$inQuery'];
- if (!inQueryValue.where || !inQueryValue.className) {
- throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $inQuery');
- }
- const additionalOptions = {
- redirectClassNameForKey: inQueryValue.redirectClassNameForKey
- };
- if (this.restOptions.subqueryReadPreference) {
- additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
- additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
- } else if (this.restOptions.readPreference) {
- additionalOptions.readPreference = this.restOptions.readPreference;
- }
- const subquery = await RestQuery({
- method: RestQuery.Method.find,
- config: this.config,
- auth: this.auth,
- className: inQueryValue.className,
- restWhere: inQueryValue.where,
- restOptions: additionalOptions,
- context: this.context
- });
- return subquery.execute().then(response => {
- transformInQuery(inQueryObject, subquery.className, response.results);
-
- return this.replaceInQuery();
- });
- };
- function transformNotInQuery(notInQueryObject, className, results) {
- var values = [];
- for (var result of results) {
- values.push({
- __type: 'Pointer',
- className: className,
- objectId: result.objectId
- });
- }
- delete notInQueryObject['$notInQuery'];
- if (Array.isArray(notInQueryObject['$nin'])) {
- notInQueryObject['$nin'] = notInQueryObject['$nin'].concat(values);
- } else {
- notInQueryObject['$nin'] = values;
- }
- }
- _UnsafeRestQuery.prototype.replaceNotInQuery = async function () {
- var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery');
- if (!notInQueryObject) {
- return;
- }
-
- var notInQueryValue = notInQueryObject['$notInQuery'];
- if (!notInQueryValue.where || !notInQueryValue.className) {
- throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $notInQuery');
- }
- const additionalOptions = {
- redirectClassNameForKey: notInQueryValue.redirectClassNameForKey
- };
- if (this.restOptions.subqueryReadPreference) {
- additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
- additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
- } else if (this.restOptions.readPreference) {
- additionalOptions.readPreference = this.restOptions.readPreference;
- }
- const subquery = await RestQuery({
- method: RestQuery.Method.find,
- config: this.config,
- auth: this.auth,
- className: notInQueryValue.className,
- restWhere: notInQueryValue.where,
- restOptions: additionalOptions,
- context: this.context
- });
- return subquery.execute().then(response => {
- transformNotInQuery(notInQueryObject, subquery.className, response.results);
-
- return this.replaceNotInQuery();
- });
- };
- const getDeepestObjectFromKey = (json, key, idx, src) => {
- if (key in json) {
- return json[key];
- }
- src.splice(1);
- };
- const transformSelect = (selectObject, key, objects) => {
- var values = [];
- for (var result of objects) {
- values.push(key.split('.').reduce(getDeepestObjectFromKey, result));
- }
- delete selectObject['$select'];
- if (Array.isArray(selectObject['$in'])) {
- selectObject['$in'] = selectObject['$in'].concat(values);
- } else {
- selectObject['$in'] = values;
- }
- };
- _UnsafeRestQuery.prototype.replaceSelect = async function () {
- var selectObject = findObjectWithKey(this.restWhere, '$select');
- if (!selectObject) {
- return;
- }
-
- var selectValue = selectObject['$select'];
-
- if (!selectValue.query || !selectValue.key || typeof selectValue.query !== 'object' || !selectValue.query.className || Object.keys(selectValue).length !== 2) {
- throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $select');
- }
- const additionalOptions = {
- redirectClassNameForKey: selectValue.query.redirectClassNameForKey
- };
- if (this.restOptions.subqueryReadPreference) {
- additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
- additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
- } else if (this.restOptions.readPreference) {
- additionalOptions.readPreference = this.restOptions.readPreference;
- }
- const subquery = await RestQuery({
- method: RestQuery.Method.find,
- config: this.config,
- auth: this.auth,
- className: selectValue.query.className,
- restWhere: selectValue.query.where,
- restOptions: additionalOptions,
- context: this.context
- });
- return subquery.execute().then(response => {
- transformSelect(selectObject, selectValue.key, response.results);
-
- return this.replaceSelect();
- });
- };
- const transformDontSelect = (dontSelectObject, key, objects) => {
- var values = [];
- for (var result of objects) {
- values.push(key.split('.').reduce(getDeepestObjectFromKey, result));
- }
- delete dontSelectObject['$dontSelect'];
- if (Array.isArray(dontSelectObject['$nin'])) {
- dontSelectObject['$nin'] = dontSelectObject['$nin'].concat(values);
- } else {
- dontSelectObject['$nin'] = values;
- }
- };
- _UnsafeRestQuery.prototype.replaceDontSelect = async function () {
- var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect');
- if (!dontSelectObject) {
- return;
- }
-
- var dontSelectValue = dontSelectObject['$dontSelect'];
- if (!dontSelectValue.query || !dontSelectValue.key || typeof dontSelectValue.query !== 'object' || !dontSelectValue.query.className || Object.keys(dontSelectValue).length !== 2) {
- throw new Parse.Error(Parse.Error.INVALID_QUERY, 'improper usage of $dontSelect');
- }
- const additionalOptions = {
- redirectClassNameForKey: dontSelectValue.query.redirectClassNameForKey
- };
- if (this.restOptions.subqueryReadPreference) {
- additionalOptions.readPreference = this.restOptions.subqueryReadPreference;
- additionalOptions.subqueryReadPreference = this.restOptions.subqueryReadPreference;
- } else if (this.restOptions.readPreference) {
- additionalOptions.readPreference = this.restOptions.readPreference;
- }
- const subquery = await RestQuery({
- method: RestQuery.Method.find,
- config: this.config,
- auth: this.auth,
- className: dontSelectValue.query.className,
- restWhere: dontSelectValue.query.where,
- restOptions: additionalOptions,
- context: this.context
- });
- return subquery.execute().then(response => {
- transformDontSelect(dontSelectObject, dontSelectValue.key, response.results);
-
- return this.replaceDontSelect();
- });
- };
- _UnsafeRestQuery.prototype.cleanResultAuthData = function (result) {
- delete result.password;
- if (result.authData) {
- Object.keys(result.authData).forEach(provider => {
- if (result.authData[provider] === null) {
- delete result.authData[provider];
- }
- });
- if (Object.keys(result.authData).length == 0) {
- delete result.authData;
- }
- }
- };
- const replaceEqualityConstraint = constraint => {
- if (typeof constraint !== 'object') {
- return constraint;
- }
- const equalToObject = {};
- let hasDirectConstraint = false;
- let hasOperatorConstraint = false;
- for (const key in constraint) {
- if (key.indexOf('$') !== 0) {
- hasDirectConstraint = true;
- equalToObject[key] = constraint[key];
- } else {
- hasOperatorConstraint = true;
- }
- }
- if (hasDirectConstraint && hasOperatorConstraint) {
- constraint['$eq'] = equalToObject;
- Object.keys(equalToObject).forEach(key => {
- delete constraint[key];
- });
- }
- return constraint;
- };
- _UnsafeRestQuery.prototype.replaceEquality = function () {
- if (typeof this.restWhere !== 'object') {
- return;
- }
- for (const key in this.restWhere) {
- this.restWhere[key] = replaceEqualityConstraint(this.restWhere[key]);
- }
- };
- _UnsafeRestQuery.prototype.runFind = async function (options = {}) {
- if (this.findOptions.limit === 0) {
- this.response = {
- results: []
- };
- return Promise.resolve();
- }
- const findOptions = Object.assign({}, this.findOptions);
- if (this.keys) {
- findOptions.keys = this.keys.map(key => {
- return key.split('.')[0];
- });
- }
- if (options.op) {
- findOptions.op = options.op;
- }
- const results = await this.config.database.find(this.className, this.restWhere, findOptions, this.auth);
- if (this.className === '_User' && !findOptions.explain) {
- for (var result of results) {
- this.cleanResultAuthData(result);
- }
- }
- await this.config.filesController.expandFilesInObject(this.config, results);
- if (this.redirectClassName) {
- for (var r of results) {
- r.className = this.redirectClassName;
- }
- }
- this.response = {
- results: results
- };
- };
- _UnsafeRestQuery.prototype.runCount = function () {
- if (!this.doCount) {
- return;
- }
- this.findOptions.count = true;
- delete this.findOptions.skip;
- delete this.findOptions.limit;
- return this.config.database.find(this.className, this.restWhere, this.findOptions).then(c => {
- this.response.count = c;
- });
- };
- _UnsafeRestQuery.prototype.denyProtectedFields = async function () {
- if (this.auth.isMaster) {
- return;
- }
- const schemaController = await this.config.database.loadSchema();
- const protectedFields = this.config.database.addProtectedFields(schemaController, this.className, this.restWhere, this.findOptions.acl, this.auth, this.findOptions) || [];
- for (const key of protectedFields) {
- if (this.restWhere[key]) {
- throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, `This user is not allowed to query ${key} on class ${this.className}`);
- }
- }
- };
- _UnsafeRestQuery.prototype.handleIncludeAll = function () {
- if (!this.includeAll) {
- return;
- }
- return this.config.database.loadSchema().then(schemaController => schemaController.getOneSchema(this.className)).then(schema => {
- const includeFields = [];
- const keyFields = [];
- for (const field in schema.fields) {
- if (schema.fields[field].type && schema.fields[field].type === 'Pointer' || schema.fields[field].type && schema.fields[field].type === 'Array') {
- includeFields.push([field]);
- keyFields.push(field);
- }
- }
-
- this.include = [...new Set([...this.include, ...includeFields])];
-
- if (this.keys) {
- this.keys = [...new Set([...this.keys, ...keyFields])];
- }
- });
- };
- _UnsafeRestQuery.prototype.handleExcludeKeys = function () {
- if (!this.excludeKeys) {
- return;
- }
- if (this.keys) {
- this.keys = this.keys.filter(k => !this.excludeKeys.includes(k));
- return;
- }
- return this.config.database.loadSchema().then(schemaController => schemaController.getOneSchema(this.className)).then(schema => {
- const fields = Object.keys(schema.fields);
- this.keys = fields.filter(k => !this.excludeKeys.includes(k));
- });
- };
- _UnsafeRestQuery.prototype.handleInclude = function () {
- if (this.include.length == 0) {
- return;
- }
- var pathResponse = includePath(this.config, this.auth, this.response, this.include[0], this.context, this.restOptions);
- if (pathResponse.then) {
- return pathResponse.then(newResponse => {
- this.response = newResponse;
- this.include = this.include.slice(1);
- return this.handleInclude();
- });
- } else if (this.include.length > 0) {
- this.include = this.include.slice(1);
- return this.handleInclude();
- }
- return pathResponse;
- };
- _UnsafeRestQuery.prototype.runAfterFindTrigger = function () {
- if (!this.response) {
- return;
- }
- if (!this.runAfterFind) {
- return;
- }
-
- const hasAfterFindHook = triggers.triggerExists(this.className, triggers.Types.afterFind, this.config.applicationId);
- if (!hasAfterFindHook) {
- return Promise.resolve();
- }
-
- if (this.findOptions.pipeline || this.findOptions.distinct) {
- return Promise.resolve();
- }
- const json = Object.assign({}, this.restOptions);
- json.where = this.restWhere;
- const parseQuery = new Parse.Query(this.className);
- parseQuery.withJSON(json);
-
- return triggers.maybeRunAfterFindTrigger(triggers.Types.afterFind, this.auth, this.className, this.response.results, this.config, parseQuery, this.context).then(results => {
-
- if (this.redirectClassName) {
- this.response.results = results.map(object => {
- if (object instanceof Parse.Object) {
- object = object.toJSON();
- }
- object.className = this.redirectClassName;
- return object;
- });
- } else {
- this.response.results = results;
- }
- });
- };
- _UnsafeRestQuery.prototype.handleAuthAdapters = async function () {
- if (this.className !== '_User' || this.findOptions.explain) {
- return;
- }
- await Promise.all(this.response.results.map(result => this.config.authDataManager.runAfterFind({
- config: this.config,
- auth: this.auth
- }, result.authData)));
- };
- function includePath(config, auth, response, path, context, restOptions = {}) {
- var pointers = findPointers(response.results, path);
- if (pointers.length == 0) {
- return response;
- }
- const pointersHash = {};
- for (var pointer of pointers) {
- if (!pointer) {
- continue;
- }
- const className = pointer.className;
-
- if (className) {
- pointersHash[className] = pointersHash[className] || new Set();
- pointersHash[className].add(pointer.objectId);
- }
- }
- const includeRestOptions = {};
- if (restOptions.keys) {
- 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 < path.length; i++) {
- if (path[i] != keyPath[i]) {
- return set;
- }
- }
- if (i < keyPath.length) {
- set.add(keyPath[i]);
- }
- return set;
- }, new Set());
- if (keySet.size > 0) {
- includeRestOptions.keys = Array.from(keySet).join(',');
- }
- }
- if (restOptions.excludeKeys) {
- const excludeKeys = new Set(restOptions.excludeKeys.split(','));
- const excludeKeySet = Array.from(excludeKeys).reduce((set, key) => {
- const keyPath = key.split('.');
- let i = 0;
- for (i; i < path.length; i++) {
- if (path[i] != keyPath[i]) {
- return set;
- }
- }
- if (i == keyPath.length - 1) {
- set.add(keyPath[i]);
- }
- return set;
- }, new Set());
- if (excludeKeySet.size > 0) {
- includeRestOptions.excludeKeys = Array.from(excludeKeySet).join(',');
- }
- }
- if (restOptions.includeReadPreference) {
- includeRestOptions.readPreference = restOptions.includeReadPreference;
- includeRestOptions.includeReadPreference = restOptions.includeReadPreference;
- } else if (restOptions.readPreference) {
- includeRestOptions.readPreference = restOptions.readPreference;
- }
- const queryPromises = Object.keys(pointersHash).map(async className => {
- const objectIds = Array.from(pointersHash[className]);
- let where;
- if (objectIds.length === 1) {
- where = {
- objectId: objectIds[0]
- };
- } else {
- where = {
- objectId: {
- $in: objectIds
- }
- };
- }
- const query = await RestQuery({
- method: objectIds.length === 1 ? RestQuery.Method.get : RestQuery.Method.find,
- config,
- auth,
- className,
- restWhere: where,
- restOptions: includeRestOptions,
- context: context
- });
- return query.execute({
- op: 'get'
- }).then(results => {
- results.className = className;
- return Promise.resolve(results);
- });
- });
-
- return Promise.all(queryPromises).then(responses => {
- var replace = responses.reduce((replace, includeResponse) => {
- for (var obj of includeResponse.results) {
- obj.__type = 'Object';
- obj.className = includeResponse.className;
- if (obj.className == '_User' && !auth.isMaster) {
- delete obj.sessionToken;
- delete obj.authData;
- }
- replace[obj.objectId] = obj;
- }
- return replace;
- }, {});
- var resp = {
- results: replacePointers(response.results, path, replace)
- };
- if (response.count) {
- resp.count = response.count;
- }
- return resp;
- });
- }
- function findPointers(object, path) {
- if (object instanceof Array) {
- return object.map(x => findPointers(x, path)).flat();
- }
- if (typeof object !== 'object' || !object) {
- return [];
- }
- if (path.length == 0) {
- if (object === null || object.__type == 'Pointer') {
- return [object];
- }
- return [];
- }
- var subobject = object[path[0]];
- if (!subobject) {
- return [];
- }
- return findPointers(subobject, path.slice(1));
- }
- function replacePointers(object, path, replace) {
- if (object instanceof Array) {
- return object.map(obj => replacePointers(obj, path, replace)).filter(obj => typeof obj !== 'undefined');
- }
- if (typeof object !== 'object' || !object) {
- return object;
- }
- if (path.length === 0) {
- if (object && object.__type === 'Pointer') {
- return replace[object.objectId];
- }
- return object;
- }
- var subobject = object[path[0]];
- if (!subobject) {
- return object;
- }
- var newsub = replacePointers(subobject, path.slice(1), replace);
- var answer = {};
- for (var key in object) {
- if (key == path[0]) {
- answer[key] = newsub;
- } else {
- answer[key] = object[key];
- }
- }
- return answer;
- }
- function findObjectWithKey(root, key) {
- if (typeof root !== 'object') {
- return;
- }
- if (root instanceof Array) {
- for (var item of root) {
- const answer = findObjectWithKey(item, key);
- if (answer) {
- return answer;
- }
- }
- }
- if (root && root[key]) {
- return root;
- }
- for (var subkey in root) {
- const answer = findObjectWithKey(root[subkey], key);
- if (answer) {
- return answer;
- }
- }
- }
- module.exports = RestQuery;
- module.exports._UnsafeRestQuery = _UnsafeRestQuery;
|