function getHelper($el) { return _.find(elementHelpers, (elementHelper) => elementHelper.match($el)); }
var getClient = function(clientId) { return __.find(clients, function(client) { return client.client_id == clientId; }); };
findById: function(id) { return _.clone(_.find(users, function(user) { return user.id === id })); },
} }); var ClusterInfo = React.createClass({ mixins: [renamingMixin('clustername')], getClusterValue(fieldName) { var cluster = this.props.cluster; var settings = cluster.get('settings'); switch (fieldName) { case 'status': return i18n('cluster.status.' + cluster.get('status')); case 'openstack_release': return cluster.get('release').get('name'); case 'compute': var libvirtSettings = settings.get('common').libvirt_type; var computeLabel = _.find(libvirtSettings.values, {data: libvirtSettings.value}).label; if (settings.get('common').use_vcenter.value) { return computeLabel + ' ' + i18n(ns + 'and_vcenter'); } return computeLabel; case 'network': var networkingParameters = cluster.get('networkConfiguration').get('networking_parameters'); if (cluster.get('net_provider') === 'nova_network') { return i18n(ns + 'nova_with') + ' ' + networkingParameters.get('net_manager'); } return (i18n('common.network.neutron_' + networkingParameters.get('segmentation_type'))); case 'storage_backends': return _.map(_.filter(settings.get('storage'), {value: true}), 'label') || i18n(ns + 'no_storage_enabled'); default: return cluster.get(fieldName);
_getPropertyFromArray: function(array, propName) { return _und.find(array,function(elem) { return (propName===("{{"+elem.key+"}}")); }); },
render: function () { var d = this.props.data var days = this.props.days var maxAttending = _.reduce(this.props.data.people, function (t, i) { if (i.attending) { return t + 1 } else { return t } }, 0) var otherEvents = [] if (d.invitedBridalBrunch) { var bridalBrunch = _.find(days.friday, function (x) { return x.name === 'bridal brunch'}) otherEvents.push(<OtherEvent key='bridalBrunchCount' day='Friday' eventDetails={bridalBrunch} countName='bridalBrunchCount' maxAttending={maxAttending} attending={d.bridalBrunchCount || 0}/>) } if (d.invitedFlowerFarm) { var flower = _.find(days.friday, function (x) { return x.name === 'flower harvest'}) otherEvents.push(<OtherEvent key='flowerFarmCount' day='Friday' eventDetails={flower} countName='flowerFarmCount' maxAttending={maxAttending} attending={d.flowerFarmCount || 0}/>) } if (d.invitedRehearsalDinner) { var rehearsal = _.find(days.friday, function (x) { return x.name === 'rehearsal dinner'}) otherEvents.push(<OtherEvent key='rehearsalDinnerCount' day='Friday' asterisk={true} countName='rehearsalDinnerCount' eventDetails={rehearsal} maxAttending={maxAttending} attending={d.rehearsalDinnerCount || 0}/>) } if (d.invitedWelcomeParty) { var welcomeParty = _.find(days.friday, function (x) { return x.name === 'welcome party'}) otherEvents.push(<OtherEvent key='welcomePartyCount' day='Friday' countName='welcomePartyCount' eventDetails={welcomeParty} maxAttending={maxAttending} attending={d.welcomePartyCount || 0}/>) } otherEvents.push(<div className='rsvp-events-wedding'> <div className='left-side'> <h4>Wedding & Reception*</h4> <p>Saturday 4:30 to 11:00 PM</p> <p>Yesterday Spaces</p> </div> <div className='right-side'></div> </div>) if (d.invitedSundayBrunch) { var brunch = _.find(days.sunday, function (x) { return x.name === 'farewell picnic'}) otherEvents.push(<OtherEvent key='sundayBrunchCount' day='Sunday' countName='sundayBrunchCount' eventDetails={brunch} maxAttending={maxAttending} attending={d.sundayBrunchCount || 0}/>) } return (<div className='rsvp-overlay-inner'> <div className='rsvp-overlay-title'> <h3>MORE EVENTS</h3> <span className="underline"></span> </div> <div className='rsvp-overlay-content'> <p className='rsvp-description'>Yay! We've got other events planned for the weekend. Please give us a head count for each event.</p> <div className='rsvp-schedule-items'> {otherEvents} </div> <a href='#' className='link-button golden' onClick={this._submit}>NEXT</a> <p className='rsvp-description'>* We are choosing a menu to accomodate vegetarians, vegans and celiacs. If you have other dietary concerns or allergies please let us know at <a href="mailto:us@ameliaandsteve.com?subject=Food">us@ameliaandsteve.com</a></p> </div> </div>) }
selectOptions = _.filter(selectOptions, function(option) { return undefined === _.find(selectedTokens, function(token) { return _.isEqual(token, option); }); }.bind(this));
app.boot = function(options) { options = options || {}; if(typeof options === 'string') { options = {appRootDir: options}; } var app = this; var appRootDir = options.appRootDir = options.appRootDir || process.cwd(); var ctx = {}; var appConfig = options.app; var modelConfig = options.models; var dataSourceConfig = options.dataSources; if(!appConfig) { appConfig = tryReadConfig(appRootDir, 'app') || {}; } if(!modelConfig) { modelConfig = tryReadConfig(appRootDir, 'models') || {}; } if(!dataSourceConfig) { dataSourceConfig = tryReadConfig(appRootDir, 'datasources') || {}; } assertIsValidConfig('app', appConfig); assertIsValidConfig('model', modelConfig); assertIsValidConfig('data source', dataSourceConfig); appConfig.host = process.env.npm_config_host || process.env.OPENSHIFT_SLS_IP || process.env.OPENSHIFT_NODEJS_IP || process.env.HOST || appConfig.host || process.env.npm_package_config_host || app.get('host'); appConfig.port = _.find([ process.env.npm_config_port, process.env.OPENSHIFT_SLS_PORT, process.env.OPENSHIFT_NODEJS_PORT, process.env.PORT, appConfig.port, process.env.npm_package_config_port, app.get('port'), 3000 ], _.isFinite); appConfig.restApiRoot = appConfig.restApiRoot || app.get('restApiRoot') || '/api'; if(appConfig.host !== undefined) { assert(typeof appConfig.host === 'string', 'app.host must be a string'); app.set('host', appConfig.host); } if(appConfig.port !== undefined) { var portType = typeof appConfig.port; assert(portType === 'string' || portType === 'number', 'app.port must be a string or number'); app.set('port', appConfig.port); } assert(appConfig.restApiRoot !== undefined, 'app.restApiRoot is required'); assert(typeof appConfig.restApiRoot === 'string', 'app.restApiRoot must be a string'); assert(/^\//.test(appConfig.restApiRoot), 'app.restApiRoot must start with "/"'); app.set('restApiRoot', appConfig.restApiRoot); for(var configKey in appConfig) { var cur = app.get(configKey); if(cur === undefined || cur === null) { app.set(configKey, appConfig[configKey]); } } // instantiate data sources forEachKeyedObject(dataSourceConfig, function(key, obj) { app.dataSource(key, obj); }); // instantiate models forEachKeyedObject(modelConfig, function(key, obj) { app.model(key, obj); }); // try to attach models to dataSources by type try { require('./loopback').autoAttach(); } catch(e) { if(e.name === 'AssertionError') { console.warn(e); } else { throw e; } } // disable token requirement for swagger, if available var swagger = app.remotes().exports.swagger; var requireTokenForSwagger = appConfig.swagger && appConfig.swagger.requireToken; if(swagger) { swagger.requireToken = requireTokenForSwagger || false; } // require directories var requiredModels = requireDir(path.join(appRootDir, 'models')); var requiredBootScripts = requireDir(path.join(appRootDir, 'boot')); }
handleChange () { this.setState(this.props.store.getState()); }, handleCheckbox (student, event) { if (event.target.checked) { this.props.store.dispatch(Actions.selectStudent(student.id)); } else { this.props.store.dispatch(Actions.unselectStudent(student.id)); } }, isModerationSet (students) { return !!(_.find(students, (student) => { return student.in_moderation_set; })); }, handleSelectAll (event) { if (event.target.checked) { var allStudents = this.props.store.getState().students; this.props.store.dispatch(Actions.selectAllStudents(allStudents)); } else { this.props.store.dispatch(Actions.unselectAllStudents()); } }, render () { return ( <div className='ModerationApp' role="grid"> <FlashMessageHolder {...this.state.flashMessage} /> <h1 className='screenreader-only'>{I18n.t('Moderate %{assignment_name}', {assignment_name: this.state.assignment.title})}</h1>
function getGame(gameId) { return _.find(gameList, function(x) { return x.id === gameId; }) || undefined; }
collection.findOne({locationId:obj.locationId}, function (err, location) { if (err) { console.error('Error finding collection.', err); options && options.error && options.error(err); return; } if (!location) { location = { locationId:obj.locationId }; } if (!location.played) { location.played = []; } if (!location.votes) { location.votes = []; } var trackIndex = -1; var track = _.find(location.votes, function (track, i) { if (track.trackId == obj.trackId && !track.played) { trackIndex = i; return true; } else { return false; } }); if (track) { console.log('Found track: ' + JSON.stringify(track)); track.played = true; location.votes.splice(trackIndex, 1); } else { track = { trackId:obj.trackId, played:true }; } console.log('pushing track onto played list: ' + JSON.stringify(track)); location.played.push(track); while (location.played > MAX_PLAYED_LENGTH) { location.played.unshift(); } var topTrack = _.sortBy(location.votes, function (track) { return track.votes * -1; })[0]; location.upNext = topTrack; collection.update({locationId:location.locationId}, location, {upsert:true}, function (err, obj) { if (err) { console.error('Error marking track as played.', err); (options && options.error && options.error(err)); } else { self.getVotes({ locationId:location.locationId, limit:5, excludePlayed:true }, options); // (options && options.success && options.success(location)); } }) });
function getPlayer(gameId, playerId) { var game = getGame(gameId); return _.find(game.players, function(x) { return x.id === playerId; }); }
return names.map(function(name) { return _.find(this.games.models, function(item) { return item.get('gameCode') === name; }); }, this);
test('sets cannot_edit if moderation_in_progress is true on the column object', function() { const moderatedColumn = _.find(this.allAssignmentColumns, (column) => column.object.moderation_in_progress) this.getVisibleGradeGridColumns() strictEqual(moderatedColumn.cssClass, 'cannot_edit') })
array.forEach(function(each) { var found = _.find(arrayExpected, function(eachExpected) {return each.id == eachExpected.id}) assert.equal(each.value, found.value) })
function getTruck(name) { return _.find(foodTrucks, function(truck){ return truck.name === name; }); }
return P.map(userSongs,function(song){ return _.find(collectedSongs,function(collectedSong){ return (collectedSong.song_id == song.song_id); }); }).then(function(uncollected_songs){
], function(error, result) { if (error) { res.tryCacheError(error); if (error == 404 || error.code == 'ENOTFOUND') { return next(new utils.NotFound('Page not found')); } return next(new Error("Requested page error: " + error)); } if (result.safe_html) { cache.set('html:' + version + ':' + uri, result.safe_html); result.links.unshift({ href: CONFIG.baseAppUrl + "/reader.js?uri=" + encodeURIComponent(uri), type: CONFIG.T.javascript, rel: [CONFIG.R.reader, CONFIG.R.inline] }); delete result.safe_html; } var render_link = _.find(result.links, function(link) { return link.html && link.rel.indexOf(CONFIG.R.inline) === -1 && link.type === CONFIG.T.text_html; }); if (render_link) { cache.set('render_link:' + version + ':' + uri, _.extend({ title: result.meta.title }, render_link)); // Copy to keep removed fields. render_link.href = CONFIG.baseAppUrl + "/render?uri=" + encodeURIComponent(uri); delete render_link.html; } else { // Cache non inline link to later render for older consumers. render_link = _.find(result.links, function(link) { return link.html && link.rel.indexOf(CONFIG.R.inline) > -1 && link.type === CONFIG.T.text_html; }); if (render_link) { cache.set('render_link:' + version + ':' + uri, _.extend({ title: result.meta.title }, render_link)); // Copy to keep removed fields. } } iframelyCore.sortLinks(result.links); if (req.query.group) { var links = result.links; var groups = {}; CONFIG.REL_GROUPS.forEach(function(rel) { var l = links.filter(function(link) { return link.rel.indexOf(rel) > -1; }); if (l.length > 0) { groups[rel] = l; } }); var other = links.filter(function(link) { return _.intersection(link.rel, CONFIG.REL_GROUPS).length == 0 }); if (other.length) { groups.other = other; } result.links = groups; } /* if (req.query.whitelist) { // if whitelist record's domain is "*" - ignore this wildcard var whitelistRecord = iframely.whitelist.findWhitelistRecordFor(uri) || {} ; result.whitelist = whitelistRecord.isDefault ? {} : whitelistRecord; } */ res.sendJsonCached(result); //iframely.disposeObject(debug); //iframely.disposeObject(result); if (global.gc) { //console.log('GC called'); global.gc(); } });
getTodo: function (text) { return _.find(this.todo_items, function (todo) { return todo.text === text; }); },
MarkGroup.prototype.attrIsMapped = function(attr) { return _.find(this.mappings, function(mapping) { return mapping.attr == attr; }) !== undefined; };
function findBase(paths){ var existingPath = _.find(paths, function(p){ return fs.existsSync(p); }) return path.normalize(existingPath+"/../"); };
var PostGradesStore = state => { var store = $.extend(createStore(state), { reset() { var assignments = this.getAssignments() _.each(assignments, a => (a.please_ignore = false)) this.setState({ assignments: assignments, pleaseShowNeedsGradingPage: false }) }, hasAssignments() { var assignments = this.getAssignments() if (assignments != undefined && assignments.length > 0) { return true } else { return false } }, getSISSectionId(section_id) { var sections = this.getState().sections return sections && sections[section_id] ? sections[section_id].sis_section_id : null }, allOverrideIds(a) { var overrides = [] _.each(a.overrides, o => { overrides.push(o.course_section_id) }) return overrides }, overrideForEveryone(a) { var overrides = this.allOverrideIds(a) var sections = _.keys(this.getState().sections) var section_ids_with_no_overrides = $(sections) .not(overrides) .get() var section_for_everyone = _.find(section_ids_with_no_overrides, o => { return state.selected.id == o }) return section_for_everyone }, selectedSISId() { return this.getState().selected.sis_id }, setGradeBookAssignments(gradebookAssignments) { var assignments = [] for (var id in gradebookAssignments) { var gba = gradebookAssignments[id] // Only accept assignments suitable to post, e.g. published, post_to_sis if (assignmentUtils.suitableToPost(gba)) { // Push a copy, and only of relevant attributes assignments.push(assignmentUtils.copyFromGradebook(gba)) } } // A second loop is needed to ensure non-unique name errors are included // in hasError _.each(assignments, a => { a.original_error = assignmentUtils.hasError(assignments, a) }) this.setState({assignments: assignments}) }, setSections(sections) { this.setState({sections: sections}) this.setSelectedSection(this.getState().sectionToShow) }, validCheck(a) { if ( a.overrideForThisSection != undefined && a.currentlySelected.type == 'course' && a.currentlySelected.id.toString() == a.overrideForThisSection.course_section_id ) { return a.due_at != null ? true : false } else if ( a.overrideForThisSection != undefined && a.currentlySelected.type == 'section' && a.currentlySelected.id.toString() == a.overrideForThisSection.course_section_id ) { return a.overrideForThisSection.due_at != null ? true : false } else { return true } }, getAssignments() { var assignments = this.getState().assignments var state = this.getState() if (state.selected.type == 'section') { _.each(assignments, a => { a.recentlyUpdated = false a.currentlySelected = state.selected a.sectionCount = _.keys(state.sections).length a.overrideForThisSection = _.find(a.overrides, override => { return override.course_section_id == state.selected.id }) //Handle assignment with overrides and the 'Everyone Else' scenario with a section that does not have any overrides //cleanup overrideForThisSection logic if (a.overrideForThisSection == undefined) { a.selectedSectionForEveryone = this.overrideForEveryone(a) } }) } else { _.each(assignments, a => { a.recentlyUpdated = false a.currentlySelected = state.selected a.sectionCount = _.keys(state.sections).length //Course is currentlySlected with sections that have overrides AND are invalid a.overrideForThisSection = _.find(a.overrides, override => { return override.due_at == null || typeof override.due_at == 'object' }) //Handle assignment with overrides and the 'Everyone Else' scenario with the course currentlySelected if (a.overrideForThisSection == undefined) { a.selectedSectionForEveryone = this.overrideForEveryone(a) } }) } return assignments }, getAssignment(assignment_id) { var assignments = this.getAssignments() return _.find(assignments, a => a.id == assignment_id) }, setSelectedSection(section) { var state = this.getState() var section_id = parseInt(section) var selected if (section) { selected = { type: 'section', id: section_id, sis_id: this.getSISSectionId(section_id) } } else { selected = { type: 'course', id: state.course.id, sis_id: state.course.sis_id } } this.setState({selected: selected, sectionToShow: section}) }, updateAssignment(assignment_id, newAttrs) { var assignments = this.getAssignments() var assignment = _.find(assignments, a => a.id == assignment_id) $.extend(assignment, newAttrs) this.setState({assignments: assignments}) }, updateAssignmentDate(assignment_id, date) { var assignments = this.getState().assignments var assignment = _.find(assignments, a => a.id == assignment_id) //the assignment has an override and the override being updated is for the section that is currentlySelected update it if ( assignment.overrideForThisSection != undefined && assignment.currentlySelected.id.toString() == assignment.overrideForThisSection.course_section_id ) { assignment.overrideForThisSection.due_at = date assignment.please_ignore = false assignment.hadOriginalErrors = true this.setState({assignments: assignments}) } //the section override being set from the course level of the sction dropdown else if ( assignment.overrideForThisSection != undefined && assignment.currentlySelected.id.toString() != assignment.overrideForThisSection.course_section_id ) { assignment.overrideForThisSection.due_at = date assignment.please_ignore = false assignment.hadOriginalErrors = true this.setState({assignments: assignments}) } //update normal assignment and the 'Everyone Else' scenario if the course is currentlySelected else { this.updateAssignment(assignment_id, { due_at: date, please_ignore: false, hadOriginalErrors: true }) } }, assignmentOverrideOrigianlErrorCheck(a) { a.hadOriginalErrors = a.hadOriginalErrors == true }, saveAssignments() { var assignments = assignmentUtils.withOriginalErrorsNotIgnored(this.getAssignments()) var course_id = this.getState().course.id _.each(assignments, a => { this.assignmentOverrideOrigianlErrorCheck(a) assignmentUtils.saveAssignmentToCanvas(course_id, a) }) }, postGrades() { var assignments = assignmentUtils.notIgnored(this.getAssignments()) var selected = this.getState().selected assignmentUtils.postGradesThroughCanvas(selected, assignments) }, getPage() { var state = this.getState() if (state.pleaseShowNeedsGradingPage) { return 'needsGrading' } else { var originals = assignmentUtils.withOriginalErrors(this.getAssignments()) var withErrorsCount = _.keys(assignmentUtils.withErrors(this.getAssignments())).length if (withErrorsCount == 0 && (state.pleaseShowSummaryPage || originals.length == 0)) { return 'summary' } else { return 'corrections' } } } }) return store }
serviceOfType: function( serviceType ) { return _.find( this.services(), function( s ) { return s["srv.type"] === serviceType; } ); },
findPlaybackPlugin(source) { return _.find(this.loader.playbackPlugins, (p) => { return p.canPlay(source.toString()) }, this); }
exports.getOembed = function(uri, data, options) { if (!data) { return; } var oembed = { type: 'rich', version: '1.0', title: data.meta.title, url: data.meta.canonical || uri }; if (data.meta.author) { oembed.author = data.meta.author; } if (data.meta.author_url) { oembed.author_url = data.meta.author_url; } if (data.meta.site) { oembed.provider_name = data.meta.site; } if (data.meta.description) { oembed.description = data.meta.description; } if (data.meta.videoId) { oembed.videoId = data.meta.videoId; } // Search only promo for thumbnails. var thumbnailLinks = htmlUtils.filterLinksByRel(CONFIG.R.promo, data.links); if (thumbnailLinks.length === 0) { // Fallback: no promos. thumbnailLinks = data.links; } var thumbnails = htmlUtils.filterLinksByRel(CONFIG.R.thumbnail, thumbnailLinks); // Find largest. var maxW = 0, thumbnail; thumbnails && thumbnails.forEach(function(t) { var m = t.media; if (m && m.width && m.width > maxW) { maxW = m.width; thumbnail = t; } }); // Or first if no sizes. if (!thumbnail && thumbnails && thumbnails.length) { thumbnail = thumbnails[0]; } if (thumbnail) { oembed.thumbnail_url = thumbnail.href; var m = thumbnail.media; if (m && m.width && m.height) { oembed.thumbnail_width = m.width; oembed.thumbnail_height = m.height; } } var link; htmlUtils.sortLinks(data.links); var foundRel = _.find(options && options.mediaPriority ? CONFIG.OEMBED_RELS_MEDIA_PRIORITY : CONFIG.OEMBED_RELS_PRIORITY, function(rel) { link = htmlUtils.filterLinksByRel(rel, data.links, { returnOne: true, excludeRel: CONFIG.R.autoplay }); return link; }); if (!link) { link = _.find(data.links, function(link) { return link.type.indexOf('image') === 0 && link.rel.indexOf(CONFIG.R.file) > -1; }); if (link) { foundRel = CONFIG.R.image; } } var inlineReader = link && _.intersection(link.rel, [CONFIG.R.inline, CONFIG.R.reader]).length == 2; var m = link && link.media; if (m) { if (m.width) { oembed.width = m.width; } if (m.height) { oembed.height = m.height; } if (m["aspect-ratio"] && options && options.targetWidthForResponsive) { oembed.width = options.targetWidthForResponsive; oembed.height = Math.round(options.targetWidthForResponsive / m["aspect-ratio"]); } } if (link && link.content_length) { oembed.content_length = link.content_length; } if (foundRel === CONFIG.R.player) { // Link found. Check incompatible rels. if (link.rel.indexOf(CONFIG.R.audio) === -1 && link.rel.indexOf(CONFIG.R.slideshow) === -1 && link.rel.indexOf(CONFIG.R.playlist) === -1) { oembed.type = 'video'; } } if (link && !inlineReader) { if (foundRel === CONFIG.R.image && link.type.indexOf('image') === 0) { oembed.type = "photo"; // Override url with image href. oembed.url = link.href; } else if (link.html) { oembed.html = link.html; } else { // "player", "survey", "reader" var omit_css = options && options.omit_css; var generateLinkOptions = { iframelyData: data, aspectWrapperClass: omit_css ? CONFIG.DEFAULT_OMIT_CSS_WRAPPER_CLASS : false, maxWidthWrapperClass: omit_css ? CONFIG.DEFAULT_MAXWIDTH_WRAPPER_CLASS : false, omitInlineStyles: omit_css, forceWidthLimitContainer: true }; if (CONFIG.GENERATE_LINK_PARAMS) { _.extend(generateLinkOptions, CONFIG.GENERATE_LINK_PARAMS); } oembed.html = htmlUtils.generateLinkElementHtml(link, generateLinkOptions); } } else { if (link && link.html) { oembed.html = link.html; } else { oembed.type = "link"; } } if (data.messages && data.messages.length) { oembed.messages = data.messages; } return oembed; };
payload.getHAR(function(err, har) { // did we get a error ? if(err) { // debug payload.error('Got a error trying to get the HAR', err); // done return fn(null); } // sanity checck if(!har) return fn(null); if(!har.log) return fn(null); // get the entries var entries = har.log.entries || []; // parse the url var uri = url.parse(data.url); // loop all the har entries and check for query strings in the proxy for(var i = 0; i < entries.length; i++) { // local reference var entry = entries[i]; // get the content type var contentTypeHeader = _.find(entry.response.headers || [], function(item) { // returns the item return (item.name || '').toLowerCase() == 'content-type'; }); // check the status if(((entry || {}).response || {}).status != 200) continue; // check content type if(!contentTypeHeader) continue; // pull out values var value = (contentTypeHeader.value || '').toLowerCase().split(','); // right check if this one of our allowed types if(allowedContentTypes.indexOf(value[0] || '') === -1) continue; // ok so now we check if the url that was contained a query string var entryUri = url.parse( entry.response.url || entry.request.url ); // must be from the same domain if((uri.hostname || '').toLowerCase().indexOf((entryUri.hostname || '').toLowerCase()) === -1) continue; // right see how big this is if(value.join(',').indexOf('charset=utf-8') != -1) continue; // if this is smaller than 3kb we show a rule payload.addRule({ message: 'Specify a character set early', key: 'charset', type: 'notice' }, { message: '$ did not specify the charset', identifiers: [ entry.request.url ], url: entry.request.url, type: 'url', filename: entry.request.url }); } // send back all the rules fn(null) });
_getColumn: function () { return _.find(this._columns, function (column) { return column.label === this.model.get('attribute'); }, this); },
function getSet(id) { return _.find(_exercise.sets, function (set) { return set.id === id; }); }
findByUsername: function(username) { return _.clone(_.find(users, function(user) { return user.username === username; })); },
module.exports = async (ctx, next) => { // no used variable 'hostname' & 'config' // let hostname = ctx.hostname; // let config = yapi.WEBCONFIG; let path = ctx.path; if (path.indexOf('/mock/') !== 0) { if (next) await next(); return true; } let paths = path.split("/"); let projectId = paths[2]; paths.splice(0, 3); path = "/" + paths.join("/"); if (!projectId) { return ctx.body = yapi.commons.resReturn(null, 400, 'projectId不能为空'); } let projectInst = yapi.getInst(projectModel), project; try { project = await projectInst.get(projectId); } catch (e) { return ctx.body = yapi.commons.resReturn(null, 403, e.message); } if (!project) { return ctx.body = yapi.commons.resReturn(null, 400, '不存在的项目'); } let interfaceData, newpath; let interfaceInst = yapi.getInst(interfaceModel); try { newpath = path.substr(project.basepath.length); interfaceData = await interfaceInst.getByPath(project._id, newpath, ctx.method); //处理query_path情况 if (!interfaceData || interfaceData.length === 0) { interfaceData = await interfaceInst.getByQueryPath(project._id, newpath, ctx.method); let i, l, j, len, curQuery, match = false; for (i = 0, l = interfaceData.length; i < l; i++) { match = false; let currentInterfaceData = interfaceData[i]; curQuery = currentInterfaceData.query_path; if (!curQuery || typeof curQuery !== 'object' || !curQuery.path) { continue; } for (j = 0, len = curQuery.params.length; j < len; j++) { if (ctx.query[curQuery.params[j].name] !== curQuery.params[j].value) { continue; } if (j === len - 1) { match = true; } } if (match) { interfaceData = [currentInterfaceData]; break; } if (i === l - 1) { interfaceData = []; } } } //处理动态路由 if (!interfaceData || interfaceData.length === 0) { let newData = await interfaceInst.getVar(project._id, ctx.method); let findInterface = _.find(newData, (item) => { let m = matchApi(newpath, item.path) if (m !== false) { ctx.request.query = Object.assign(m, ctx.request.query); return true; } return false; }); if (!findInterface) { //非正常跨域预检请求回应 if (ctx.method === 'OPTIONS' && ctx.request.header['access-control-request-method']) { return handleCorsRequest(ctx); } return ctx.body = yapi.commons.resReturn(null, 404, `不存在的api, 当前请求path为 ${newpath}, 请求方法为 ${ctx.method} ,请确认是否定义此请求。`); } interfaceData = [ await interfaceInst.get(findInterface._id) ] } if (interfaceData.length > 1) { return ctx.body = yapi.commons.resReturn(null, 405, '存在多个api,请检查数据库'); } else { interfaceData = interfaceData[0]; } ctx.set("Access-Control-Allow-Origin", "*") let res; res = interfaceData.res_body; try { if (interfaceData.res_body_type === 'json') { res = mockExtra( yapi.commons.json_parse(interfaceData.res_body), { query: ctx.request.query, body: ctx.request.body, params: Object.assign({}, ctx.request.query, ctx.request.body) } ); try { res = Mock.mock(res); } catch (e) { yapi.commons.log(e, 'error') } } let context = { projectData: project, interfaceData: interfaceData, ctx: ctx, mockJson: res, resHeader: {}, httpCode: 200, delay: 0 } await yapi.emitHook('mock_after', context); let handleMock = new Promise(resolve => { setTimeout(() => { resolve(true) }, context.delay) }) await handleMock; if (context.resHeader && typeof context.resHeader === 'object') { for (let i in context.resHeader) { let cookie; if (i === 'Set-Cookie') { if (context.resHeader[i] && typeof context.resHeader[i] === 'string') { cookie = parseCookie(context.resHeader[i]); if (cookie && typeof cookie === 'object') { ctx.cookies.set(cookie.name, cookie.value, { maxAge: 864000000 }); } } else if (context.resHeader[i] && Array.isArray(context.resHeader[i])) { context.resHeader[i].forEach(item => { cookie = parseCookie(item); if (cookie && typeof cookie === 'object') { ctx.cookies.set(cookie.name, cookie.value, { maxAge: 864000000 }); } }) } } else ctx.set(i, context.resHeader[i]); } } ctx.status = context.httpCode; return ctx.body = context.mockJson; } catch (e) { yapi.commons.log(e, 'error') return ctx.body = { errcode: 400, errmsg: '解析出错,请检查。Error: ' + e.message, data: null } } } catch (e) { console.error(e) return ctx.body = yapi.commons.resReturn(null, 409, e.message); } };