@function applyModelViewCollection

apply views to results object

@param {object} context
@param {integer} num
@param {array} raw

@returns {Promise}
179744
function applyModelViewCollection (context, num, raw) {
    // if there are record views then execute them before collection
    if (this.hasRecord) {
        var recordPromise = this.applyModelViewRecord(raw)
    }
    // wait for record view to resolve
    return Promise.resolve(recordPromise)
    // apply collection view
    .then(recordRaw => {
        // if there is a record result use it
        if (recordRaw) {
            raw = recordRaw
        }
        // if there are synchronous collection views apply
        if (this.hasCollectionSynchronous) {
            this.applyModelViewCollectionSynchronous(context, num, raw)
        }
        // if there are asychronous views then do async apply
        if (this.hasCollectionAsynchronous) {
            return this.applyModelViewCollectionAsynchronous(context, num, raw)
        }
        // otherwise resolve with context
        else {
            return context
        }
    })
}
1306735
function resolveModelViewName (modelViews, modelViewName, resolved) {
    // map of names resolved - this is needed to detect infinite loops
    if (!resolved) {
        resolved = {}
    }
    // throw error if name has already been resolved - infinite loop
    assert.ok(!resolved[modelViewName], 'views error: '+modelViewName+' cannot be resolved to model view object')
    // set flag that current name has been seen
    resolved[modelViewName] = true
    // get specified model view - this has already been tested to exist
    var modelView = modelViews[modelViewName]
    // return resolved value(s)
    return Array.isArray(modelView)
        ? _.map(modelView, modelView => requireValidModelView(modelView, modelViews, true, resolved))
        : requireValidModelView(modelView, modelViews, true, resolved)
}
1224906
function(res, method, model, options) {
		// parse non-document responses
		if (res._id == null && res._rev == null) {
			// write result
			if (method !== "read") return { _id: res.id, _rev: res.rev };

			// view result
			if (res.rows != null) {
				if (isCollection(model)) return res.rows.map(function(row) {
					return row[options.rowKey];
				});

				// grab just the first row for models
				return res.rows.length ? res.rows[0][options.rowKey] : null;
			}

			// changes feed result
			if (res[options.rowKey] != null) return res[options.rowKey];
		}

		return res;
	}
656389
function HttpViewResult(name, data)
{
    this.name = name;
    this.data = data===undefined? []: data;
    this.contentType = 'text/html;charset=utf-8';
    this.contentEncoding = 'utf8';
}
1230922
function executeNext() {
	// Get the next data update.
	const dataNew = executeQueue[0];

	// Merge new data into current data.
	for (let key in dataNew) {
		data[key] = dataNew[key];
	}

	// Begin executing the view.
	const viewNew = viewCurrent(data);

	setViewNew(viewNew);
	executeView([viewNew], [null], [0]);
}
1288534
function recordResult (results) {
    // if only ids were selected the return result object to fetch records
    if (this.query.select.isSelectOnlyIds) {
        // build result object
        var result = new ImmutableCoreModelResult({
            query: this.query,
            results: results,
            applyView: true,
        })
        // return result or all records if specified
        return this.query.args.all ? result.all() : result
    }
    // otherwise return ImmutableCoreModelInstance record(s)
    else {
        // if query is for a single record then return record or undefined
        if (this.query.args.limit === 1) {
            // if there are not results return undefined
            if (!results.length) {
                return undefined
            }
            // apply model view to record
            return Promise.resolve(this.applyModelViewRecord(results[0]))
            // resolve with instance
            .then(result => this.newRecordInstance(result))
        }
        // if query is for all records then return all
        else {
            // apply model views to each record
            return Promise.map(results, result => {
                // apply model view to record
                return this.applyModelViewRecord(result)
                // resolve with instance
                .then(result => this.newRecordInstance(result))
            })
        }
    }
}
1369383
function getView(app, view) {
    if (typeof view !== 'string') {
      return view;
    }
    if (app.isCollection) {
      view = app.getView(view);

    } else if (app.isList) {
      view = app.getItem(view);

    } else {
      view = findView(app, view);
    }
    return view;
  }
485409
function _applyFilters(rawdata, filterOptions) {
			var dataToWorkOn = (JSON.parse(JSON.stringify(rawdata)));
			var containerWidth = document.querySelector('#sapUiSupportPerfHeaderTimeline').offsetWidth - document.querySelector('#sapUiSupportPerfHeaderTimelineBarInfoWrapper').offsetWidth;
			var scrollWidth = 20;
			var filteredTime = 1;

			dataToWorkOn = _filterByTime(filterOptions.filterByTime, dataToWorkOn);
			dataToWorkOn = _sortBy(filterOptions.orderByValue, dataToWorkOn);
			dataToWorkOn = _filterMinValue(filterOptions.minValue, dataToWorkOn);

			if (dataToWorkOn.length) {
				filteredTime = filterOptions.filterByTime.end - filterOptions.filterByTime.start;
			}

			_widthSingleUnit = ((containerWidth - scrollWidth) / filteredTime); //ms in px

			return dataToWorkOn;
		}
965240
function getViewsOf(model) {
        return getRefsTo(model, function (ref) {
            return (ref instanceof Core.View) && (ref.model === model);
        });
    }
505434
function initViews () {
    // list of views - may be empty
    this.modelViews = []
    // if view is false no model views will be applied overriding any defaults
    if (this.args.view === false) {
        return
    }
    // get view from args or default
    var viewArg = defined(this.args.view) ? this.args.view : this.model.views.default
    // skip unless view arg is set from args or default
    if (!defined(viewArg)) {
        return
    }
    // list of views to apply to model
    var views
    // if view is string then convert to array
    if (typeof viewArg === 'string') {
        views = [viewArg]
    }
    // if view is array use it
    else if (Array.isArray(viewArg)) {
        views = viewArg
    }
    // invalid argument
    else {
        throw this.error('invalid view argument')
    }
    // iterate over views getting model view objects
    _.each(views, view => {
        var modelView = requireValidModelView(view, this.model.views, true)
        // if result is array then add all
        if (Array.isArray(modelView)) {
            _.each(modelView, modelView => this.modelViews.push(modelView))
        }
        // otherwise add object
        else {
            this.modelViews.push(modelView)
        }
    })
    // instantiate model view engine if there are views
    if (this.modelViews.length > 0) {
        this.modelViewEngine = new ImmutableCoreModelViewEngine({query: this})
    }
}
528630
function( model ) {
			var modelColl = model.collection;
			var coll = this.getCollection( model );
			coll && coll._add( model );
			model.collection = modelColl;
		}
462348
function applyModelViewRecordAsynchronous (raw) {
    // get data column
    var dataColumn = this.query.model.columnName('data')
    // apply model views to data
    return Promise.all(_.map(this.modelViews.record.asynchronous, modelView => {
        // if this model view applies to meta data then pass entire db record
        var data = modelView.meta ? raw : raw[dataColumn]
        // call each function with modelView and data
        return modelView.each({
            modelView: modelView,
            record: data,
            session: this.query.session,
        })
        // merge result to data
        .then((eachData => {
            _.merge(data, eachData)
        }))
    }))
    // resolve with merged data
    .then(() => raw)
}
279464
function() {
      var newItemViews = [];
      _.each(this.modelsToRender(), function(model, indexOfModel) {
        var itemView = this.getItemViewFromModel(model);
        if (!itemView) {
          newItemViews.push({
            view: this.__createItemView(model, true),
            indexOfModel: indexOfModel
          });
        }
      }, this);
      this.__updateOrderedModelIdList();
      return newItemViews;
    }
504981
function getResult(attrNode, dataSourceName, context) {
    const resultId = attrNode.dataSources[dataSourceName].resultId;
    if (typeof resultId === 'undefined') {
        const attrPath = context.attrPath.length > 0 ? context.attrPath.join('.') : '{root}';
        throw new ImplementationError(`Result for "${attrPath}" (DataSource "${dataSourceName}") missing`);
    }
    return context.rawResults[resultId];
}
561284
function (context, callback) {

            var self = this,
                options = {},
                model,
                processor,
                isPatch = context.request.method === "PATCH",
                upsert = this.$resourceConfiguration.$.upsert,
                defaults;


            flow()
                .seq("collection", function (cb) {
                    self._findCollection(context, cb);
                })
                .seq(function (cb) {
                    model = this.vars.collection.createItem(self.$resourceId);
                    defaults = _.clone(model.$);
                    // check if model exists
                    if (upsert && !isPatch) {
                        cb();
                    } else {
                        model.fetch(null, cb);
                    }
                })
                .seq(function () {
                    if (!isPatch) {
                        model.clear();
                        model.set(defaults);
                    }

                    var payload = context.request.params;

                    processor = self.$restHandler.$restDataSource.getProcessorForModel(model);

                    model.set(processor.parse(model, payload || {}));

                    options.action = DataSource.ACTION.UPDATE;

                    // TODO: add hook to add session data like user id
                    if (upsert === true) {
                        options.upsert = true;
                        model.set(model.idField, model.factory.prototype.convertIdentifier(self.$resourceId));
                    }
                })
                .seq(function () {
                    self._generateAutoValues(model);
                })
                .seq(function (cb) {
                    self._validate(model, context, cb);
                })
                .seq(function (cb) {
                    self._beforeModelSave(model, context, cb);
                })
                .seq(function (cb) {
                    self._beforeModelUpdate(model, context, cb);
                })
                .seq(function (cb) {
                    model.validateAndSave(options, cb);
                })
                .seq(function (cb) {
                    self._afterModelUpdate(model, context, cb);
                })
                .exec(function (err, results) {
                    if (!err) {
                        // TODO: do correct invalidation
                        results.collection.invalidatePageCache();

                        self._fetchAllHrefsForModel(model, context);

                        // TODO: generate the location header
                        var body = JSON.stringify(processor.compose(model, null));

                        var response = context.response;
                        response.writeHead(200, "", {
                            'Content-Type': 'application/json'
                            // TODO : add updated date in head ???
//                            'Location': context.request.urlInfo.uri
                        });

                        response.write(body);
                        response.end();

                        callback(null);
                    } else {
                        if (!(err instanceof HttpError)) {
                            var statusCode = 400;
                            if (err === DataSource.ERROR.NOT_FOUND) {
                                statusCode = 404;
                            }
                            err = new HttpError(err, statusCode);
                        }
                        callback(err);
                    }
                });

        }
485368
function collectionResultIterator (context, results) {
    // create new result object
    var result = new ImmutableCoreModelResult({
        query: this.query,
        results: results,
    })
    // execute iterator
    return result.each((record, num) => {
        // get result
        return this.applyModelViewCollection(context, num, record.raw)
        // merge result to context
        .then(ctx => {
            _.merge(context, ctx)
        })
    })
    // resolve with context
    .then(() => context)
}
305792
function(req, res, next) {
    return function(modelOrCollection) {
      this.prepareResponse(modelOrCollection, req, res, next);
    }.bind(this);
  }