code
stringlengths
28
313k
docstring
stringlengths
25
85.3k
func_name
stringlengths
1
74
language
stringclasses
1 value
repo
stringlengths
5
60
path
stringlengths
4
172
url
stringlengths
44
218
license
stringclasses
7 values
ScoreForIntentRefresh = function (card, targetPosition, cardIntents) { let score = 0; const cardId = card.getBaseCardId(); const validIntents = cardIntents != null ? CardIntent.filterIntentsByIntentType(cardIntents, CardIntentType.Refresh) : CardIntent.getIntentsByIntentType(cardId, CardIntentType.Refresh); _....
Returns the Refresh score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @param {Array} [cardIntents=null] forced card intents (won't use card's own card intents) @returns {Number} @static @public
ScoreForIntentRefresh
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_refresh.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_refresh.js
CC0-1.0
ScoreForIntentRemove = function (card, targetPosition, cardIntents) { let score = 0; const cardId = card.getBaseCardId(); const validIntents = cardIntents != null ? CardIntent.filterIntentsByIntentType(cardIntents, CardIntentType.Remove) : CardIntent.getIntentsByIntentType(cardId, CardIntentType.Remove); _.eac...
Returns the remove score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @param {Array} [cardIntents=null] forced card intents (won't use card's own card intents) @returns {Number} @static @public
ScoreForIntentRemove
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_remove.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_remove.js
CC0-1.0
getScoreForSummonFromCardWithIntent = function (card, intent, targetPosition) { let score = 0; if (targetPosition != null) { const amount = intent.amount || 1; let summonedCards; if (intent.cardId != null) { summonedCards = [card.getGameSession().getExistingCardFromIndexOrCreateCardFromData({ id: ...
Returns the score for a unit at target position @param {Card} card @param {Object} intent @param {Vec2} targetPosition @returns {Number} @static @public
getScoreForSummonFromCardWithIntent
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_summon.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_summon.js
CC0-1.0
ScoreForIntentSummon = function (card, targetPosition, cardIntents) { let score = 0; const cardId = card.getBaseCardId(); if (card instanceof SDK.Unit) { score += ScoreForUnitSummon(card, targetPosition); if (score < THRESHOLD.PLAY_CARD) { score += THRESHOLD.PLAY_CARD; } } const validInten...
Returns the Summon score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @param {Array} [cardIntents=null] forced card intents (won't use card's own card intents) @returns {Number} @static @public
ScoreForIntentSummon
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_summon.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_summon.js
CC0-1.0
ScoreForIntentTeleportDestination = function (card, targetPosition, cardIntents) { let score = 0; const cardId = card.getBaseCardId(); const validIntents = cardIntents != null ? CardIntent.filterIntentsByIntentType(cardIntents, CardIntentType.TeleportDestination) : CardIntent.getIntentsByIntentType(cardId, CardIn...
Returns the TeleportDestination score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @param {Array} [cardIntents=null] forced card intents (won't use card's own card intents) @returns {Number} @static @public
ScoreForIntentTeleportDestination
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_teleport_destination.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_teleport_destination.js
CC0-1.0
getScoreForTeleportTargetFromCardWithIntentToCard = function (card, intent, targetPosition) { let score = 0; if (targetPosition != null) { const targetedUnit = card.getGameSession().getBoard().getUnitAtPosition(targetPosition); score += ScoreForUnitTeleportTarget(targetedUnit, targetPosition); } return ...
Returns the score for selecting a card to be teleported @param {Card} card @param {Object} intent @param {Card} targetCard @returns {Number} @static @public
getScoreForTeleportTargetFromCardWithIntentToCard
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_teleport_target.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_teleport_target.js
CC0-1.0
ScoreForIntentTeleportTarget = function (card, targetPosition, cardIntents) { let score = 0; const cardId = card.getBaseCardId(); const validIntents = cardIntents != null ? CardIntent.filterIntentsByIntentType(cardIntents, CardIntentType.TeleportTarget) : CardIntent.getIntentsByIntentType(cardId, CardIntentType.T...
Returns the TeleportTarget score for a card at a target position. Should select the best-positioned enemy unit or the worst-positioned friendly unit. Unit score is softened heavily to serve only as a tie-breaker for two similarly-positioned units Assumes that the current player is the casting player for purposes ...
ScoreForIntentTeleportTarget
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_teleport_target.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_teleport_target.js
CC0-1.0
ScoreForIntentTransform = function (card, targetPosition, cardIntents) { let score = 0; const cardId = card.getBaseCardId(); const validIntents = cardIntents != null ? CardIntent.filterIntentsByIntentType(cardIntents, CardIntentType.Transform) : CardIntent.getIntentsByIntentType(cardId, CardIntentType.Transform);...
Returns the Transform score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @param {Array} [cardIntents=null] forced card intents (won't use card's own card intents) @returns {Number} @static @public
ScoreForIntentTransform
javascript
open-duelyst/duelyst
server/ai/scoring/intent/intent_transform.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/intent/intent_transform.js
CC0-1.0
ScoreForPhaseDeath = function (card, targetPosition, cardIntents) { let score = 0; const cardId = card.getBaseCardId(); const gameSession = GameSession.getInstance(); const board = gameSession.getBoard(); const validIntents = cardIntents != null ? cardIntents : CardIntent.getIntentsByPartialPhaseType(cardId, ...
Returns the Phase Death score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @param {Array} [cardIntents=null] forced card intents (won't use card's own card intents) @returns {Number} @static @public
ScoreForPhaseDeath
javascript
open-duelyst/duelyst
server/ai/scoring/phase/phase_death.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/phase/phase_death.js
CC0-1.0
ScoreForPhaseSpell = function (card, targetPosition) { let score = 0; const cardId = card.getBaseCardId(); const player = card.getOwner(); const cardsInHand = [].concat(player.getDeck().getCardsInHand(), player.getCurrentSignatureCard()); if (cardsInHand.length > 0) { const intents = CardIntent.getIntent...
Returns the spell phase score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @returns {Number} @static @public
ScoreForPhaseSpell
javascript
open-duelyst/duelyst
server/ai/scoring/phase/phase_spell.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/phase/phase_spell.js
CC0-1.0
ScoreForPhaseSummon = function (card, targetPosition) { let score = 0; const cardId = card.getBaseCardId(); const player = card.getOwner(); const cardsInHand = [].concat(player.getDeck().getCardsInHand(), player.getCurrentSignatureCard()); if (cardsInHand.length > 0) { const intents = CardIntent.getInten...
Returns the summon phase score for a card at a target position. @param {Card} card @param {Vec2} targetPosition @returns {Number} @static @public
ScoreForPhaseSummon
javascript
open-duelyst/duelyst
server/ai/scoring/phase/phase_summon.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/phase/phase_summon.js
CC0-1.0
position_objective_distanceFromBestObjective = function (gameSession, unit, position, bestObjective, scoringMode) { // Logger.module("AI").debug("[G:" + gameSession.gameId + "] position_objective_distanceFromBestObjective() => score for " + unit.getLogName() + " at " + position.x + "," + position.y + " for best objec...
Returns a score for a unit's distance from their best objective. @param {GameSession} gameSession @param {Unit} unit @param {Vec2} position @param {Card} bestObjective @param {Boolean} [scoringMode=false] whether in board scoring mode, which softens some penalties such as evasive units running away. @returns {Number}
position_objective_distanceFromBestObjective
javascript
open-duelyst/duelyst
server/ai/scoring/position/position_objective_distanceFromBestObjective.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/position/position_objective_distanceFromBestObjective.js
CC0-1.0
position_zeal = function (gameSession, unit, position) { let score = 0; if (unit.hasModifierClass(ModifierBanding)) { // bonus if adjacent to general /// /Logger.module("AI").debug("[G:" + gameSession.gameId + "] scoreForUnit_module_zeal() => unit " + unit.getLogName() + ". score = " + score); const general...
Should be used for scoring positions for purposes of summoning/moving/teleporting. should not really be part of board scoring since zeal will proc whatever modifier and be scored as part of the unit's scoring. @param {GameSession} gameSession @param {Unit} unit @param {Vec2} position @returns
position_zeal
javascript
open-duelyst/duelyst
server/ai/scoring/position/position_zeal.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/position/position_zeal.js
CC0-1.0
arePositionsEqualOrAdjacent = function (positionA, positionB) { return Math.abs(positionA.x - positionB.x) <= 1 && Math.abs(positionA.y - positionB.y) <= 1; }
Returns whether two positions are equal or adjacent. @param {Vec2} positionA @param {Vec2} positionB @returns {Boolean}
arePositionsEqualOrAdjacent
javascript
open-duelyst/duelyst
server/ai/scoring/utils/utils_arePositionsEqualOrAdjacent.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/utils/utils_arePositionsEqualOrAdjacent.js
CC0-1.0
canCardAndEffectsBeAppliedAnywhere = function (card, cardIntents) { if (card instanceof Artifact) return true; if (card instanceof Spell && card.getCanBeAppliedAnywhere()) { const cardId = card.getBaseCardId(); if (cardIntents == null) { cardIntents = CardIntent.getIntentsByCardId(cardId, true); }...
Returns whether a card plus optional card intents can be applied anywhere and still have the same effect. @param {Card} card @param {Array} [cardIntents=null] @returns {Boolean}
canCardAndEffectsBeAppliedAnywhere
javascript
open-duelyst/duelyst
server/ai/scoring/utils/utils_canCardAndEffectsBeAppliedAnywhere.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/utils/utils_canCardAndEffectsBeAppliedAnywhere.js
CC0-1.0
isUnitBuffer = function (unit) { const modifiers = unit.getModifiers(); if (modifiers.length > 0) { for (let i = 0, il = modifiers.length; i < il; i++) { const modifier = modifiers[i]; // in 99% of cases, a unit buffs self or others when: // 1. it is not an aura, opening gambit, or dying wish ...
Returns whether a unit is a buffer. @param {Unit} unit @returns {Boolean}
isUnitBuffer
javascript
open-duelyst/duelyst
server/ai/scoring/utils/utils_isUnitBuffer.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/utils/utils_isUnitBuffer.js
CC0-1.0
isUnitEvasive = function (unit) { return (unit.hasModifierClass(ModifierRanged) || unit.hasModifierClass(ModifierBlastAttack) // Look into improving isUnitBuffer function. || (isUnitBuffer(unit) && unit.getHP() < BOUNTY.BUFFER_HP_EVASIVE_THRESHOLD && !unit.hasModifierClass(ModifierForcefieldAbsorb)) |...
Returns whether a unit is evasive. @param {Unit} unit @returns {Boolean}
isUnitEvasive
javascript
open-duelyst/duelyst
server/ai/scoring/utils/utils_isUnitEvasive.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/utils/utils_isUnitEvasive.js
CC0-1.0
willUnitSurviveCard = function (unit, card) { let unitSurvives = true; const gameSession = card.getGameSession(); const myGeneral = gameSession.getGeneralForPlayerId(unit.getOwnerId()); const cardId = card.getBaseCardId(); const minionOrGeneralTargetType = unit.getIsGeneral() ? CardTargetType.General : CardTa...
Returns whether or not a unit will survive any burn intents on a card. @param {Unit} unit @param {Card} card @returns {Boolean}
willUnitSurviveCard
javascript
open-duelyst/duelyst
server/ai/scoring/utils/utils_willUnitSurviveCard.js
https://github.com/open-duelyst/duelyst/blob/master/server/ai/scoring/utils/utils_willUnitSurviveCard.js
CC0-1.0
maybeReady = function () { if (isReady || !isLoadingCompleted || readyHoldsCount > 0) return; isReady = true; // Run startup callbacks while (callbackQueue.length) (callbackQueue.shift())(); }
Allow to run callbacks on Storybook startup, after stories are imported Based on Meteor.startup client side implementation @see https://github.com/meteor/meteor/blob/24865b28a0689de8b4949fb69ea1f95da647cd7a/packages/meteor/startup_client.js
maybeReady
javascript
VulcanJS/Vulcan
.storybook/startup.js
https://github.com/VulcanJS/Vulcan/blob/master/.storybook/startup.js
MIT
onStartup = function (callback) { // Fix for < IE9, see http://javascript.nwbox.com/IEContentLoaded/ var doScroll = !document.addEventListener && document.documentElement.doScroll; if (!doScroll || window !== top) { if (isReady) callback(); else callbackQueue.push(callback); } else { ...
@summary Run code when a client or a server starts. @locus Anywhere @param {Function} func A function to run on startup.
onStartup
javascript
VulcanJS/Vulcan
.storybook/startup.js
https://github.com/VulcanJS/Vulcan/blob/master/.storybook/startup.js
MIT
findPathToVulcanPackages = () => { // look for VULCAN_DIR env variable if (process.env.VULCAN_DIR) return `${process.env.VULCAN_DIR}/packages`; // look for METEOR_PACKAGE_DIRS variable const rawPackageDirs = process.env.METEOR_PACKAGE_DIRS; if (rawPackageDirs) { const dirs = rawPackageDirs.split(':'); ...
Smart function to find Vulcan packages You can either provide a path to Vulcan as VULCAN_DIR env or set the METEOR_PACKAGE_DIR variable
findPathToVulcanPackages
javascript
VulcanJS/Vulcan
.storybook/webpack.config.js
https://github.com/VulcanJS/Vulcan/blob/master/.storybook/webpack.config.js
MIT
function isFileReady(readyState) { // Check to see if any of the ways a file can be ready are available as properties on the file's element return (!readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized'); }
Sourced from: https://github.com/nathanboktae/mocha-phantomjs-core
isFileReady
javascript
VulcanJS/Vulcan
packages/meteor-mocha/browser-shim.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/meteor-mocha/browser-shim.js
MIT
useMeteorLogout = (callback = () => {}) => { const client = useApolloClient(); return () => Meteor.logout(() => { const resetStoreCallback = () => { callback(); removeResetStoreCallback(resetStoreCallback); }; const removeResetStoreCallback = client.onResetStore(resetStoreCallb...
Hook used to sign the user out. @param {function} callback called after the logout and the Apollo store reset @returns {function} a function to execute when you log the user out
useMeteorLogout
javascript
VulcanJS/Vulcan
packages/vulcan-accounts/imports/useMeteorLogout.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-accounts/imports/useMeteorLogout.js
MIT
withDocumentId = (fieldName = 'documentId') => Component => { const withDocumentId = props => ( <Component documentId={props[fieldName] || (props.params && props.params[fieldName]) || undefined} {...props} /> ); withDocumentId.displayName = `withDocumentId(${Component.displayName})`; return ...
Get the documentId from parent props or from the route
withDocumentId
javascript
VulcanJS/Vulcan
packages/vulcan-backoffice/lib/hocs/withDocumentId.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-backoffice/lib/hocs/withDocumentId.js
MIT
withRouteParam = fieldName => Component => { const Wrapper = props => ( <Component {...props} {...{ [fieldName]: props[fieldName] || (props.params && props.params[fieldName]) || undefined, }} /> ); Wrapper.propTypes = { // @see React router 4 withRouter API match: PropTy...
Pass a route param to its child
withRouteParam
javascript
VulcanJS/Vulcan
packages/vulcan-backoffice/lib/hocs/withRouteParam.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-backoffice/lib/hocs/withRouteParam.js
MIT
mergeDefaultCollectionOptions = (collectionOptions, options = {}) => _merge({}, defaultBackofficeOptions, options, collectionOptions)
Setup default options and provides helper to generate valid options based on these defaults
mergeDefaultCollectionOptions
javascript
VulcanJS/Vulcan
packages/vulcan-backoffice/lib/modules/options.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-backoffice/lib/modules/options.js
MIT
setupBackoffice = (collections, providedOptions = {}, collectionsOptions = {}) => { const options = mergeDefaultBackofficeOptions(providedOptions); // pages for each collection collections.forEach(collection => { const collectionName = getCollectionName(collection); const collectionOptions = mergeDefaultC...
Setup a full fledged backoffice - create components - create routes - register menu items
setupBackoffice
javascript
VulcanJS/Vulcan
packages/vulcan-backoffice/lib/modules/setupBackoffice.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-backoffice/lib/modules/setupBackoffice.js
MIT
setupCollectionMenuItems = (collection, collectionOptions) => { const options = mergeDefaultCollectionOptions(collectionOptions); const labelToken = options.menuItem.labelToken; const label = !labelToken ? options.menuItem.label || getCollectionDisplayName(collection) : undefined; const collectionName =...
Add an item to the menu to access the collection
setupCollectionMenuItems
javascript
VulcanJS/Vulcan
packages/vulcan-backoffice/lib/modules/setupCollectionMenuItems.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-backoffice/lib/modules/setupCollectionMenuItems.js
MIT
createCollectionComponents = (collection, options) => { const mergedOptions = mergeDefaultCollectionOptions(options); const ListComponent = createListComponent(collection, mergedOptions); const ItemComponent = createItemComponent(collection, mergedOptions); return { ListComponent, ItemComponent }; }
Create List and Item components for the provided collection, based on the generic Vulcan backoffice components
createCollectionComponents
javascript
VulcanJS/Vulcan
packages/vulcan-backoffice/lib/modules/createCollectionComponents/createCollectionComponents.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-backoffice/lib/modules/createCollectionComponents/createCollectionComponents.js
MIT
resetMenus = () => { Object.keys(Menus).forEach(key => { delete Menus[key]; }); Menus[defaultMenuGroup] = {}; }
Menu configuration is a map { defaultMenu: { item1: { ... } adminMenu: { some-item: { ... } } shortMenu: { ... } ... }
resetMenus
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/menu.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/menu.js
MIT
getDocumentFromMutation = (mutation, mutationName) => { const mutationData = (mutation.result.data[mutationName] || {}); const document = mutationData.data; return document; }
Safe getter Must returns null if the document is absent (eg in case of validation failure) TODO: use this getter @param {*} mutation @param {*} mutationName
getDocumentFromMutation
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/containers/cacheUpdate.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/containers/cacheUpdate.js
MIT
addToData = ({ queryResult, multiResolverName, document, sort, selector }) => { const queryData = queryResult[multiResolverName]; let { results, totalCount } = queryData; const idx = positionInSet(results, document); let newResults = [...results]; if (idx !== -1) { // doc has already been ad...
Add to data @param {*} queryData @param {*} document
addToData
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/containers/cacheUpdate.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/containers/cacheUpdate.js
MIT
multiQueryUpdater = ({ typeName, fragment, fragmentName, collection, resolverName }) => (cache, { data }) => { const multiResolverName = collection.options.multiResolverName; // update multi queries const multiQuery = buildMultiQuery({ typeName, fragmentName, fragment }); const newDoc = data?.[resolve...
Update cached list of data after a document creation
multiQueryUpdater
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/containers/create.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/containers/create.js
MIT
buildQueryOptions = (options, { paginationTerms }, { terms }) => { let { pollInterval = getSetting('pollInterval', 20000), enableTotal = true, enableCache = false, // generic graphQL options queryOptions = {} } = options; // if this is the SSR process, set pollInterval to null // see https:/...
Build the graphQL query options @param {*} options @param {*} state @param {*} props
buildQueryOptions
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/containers/multi.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/containers/multi.js
MIT
buildQueryOptions = (options, { documentId, slug, selector = { documentId, slug } }) => { let { pollInterval = getSetting('pollInterval', 20000), enableCache = false, fetchPolicy, queryOptions = {} } = options; // if this is the SSR process, set pollInterval to null // see https://github.com/apollographql/apollo-...
Create GraphQL useQuery options and variables based on props and provided options @param {*} options @param {*} props
buildQueryOptions
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/containers/single.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/containers/single.js
MIT
computeQueryVariables = (options, argsOrProps) => { const { _id: optionsId, input: optionsInput = {} } = options; const { _id: argsId, input: argsInput = {} } = argsOrProps; const _id = argsId || optionsId || undefined; // use dynamic _id in priority, default _id otherwise const input = !_id ? _merge({}...
Compute the _id or input based on default options of the hooks + dynamic props (for single) or dynamic arguments (for update) @param {*} options @param {*} argsOrProps
computeQueryVariables
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/containers/variables.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/containers/variables.js
MIT
function withAccess(options) { const { groups = [], redirect = null, failureComponent = null, failureComponentName = null, message } = options; // we return a function that takes a component and itself returns a component return WrappedComponent => { class AccessComponent extends PureComponent { // if ...
withAccess - description @param {Object} options the options that define the hoc @param {string[]} options.groups the groups that have access to this component @param {string} options.redirect the link to redirect to in case the access is not granted (optional) ...
withAccess
javascript
VulcanJS/Vulcan
packages/vulcan-core/lib/modules/containers/withAccess.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-core/lib/modules/containers/withAccess.js
MIT
constructor(message, error, options = {}) { super(message); if (!error) throw new Error(`new ${this.name} requires a message and error`); let message_lines = (this.message.match(/\n/g) || []).length + 1; let stack_array = this.stack.split('\n'); if (options.remove) { stack_array.splice(messa...
@param {string} message - An error message @param {Error} error - An Error caught in a catch block @param {Object} [options] - The employee who is responsible for the project. @param {boolean|number} [options.stack] - Enable, disable or set the number of lines of stack output @param {number} [options.remove] - The numb...
constructor
javascript
VulcanJS/Vulcan
packages/vulcan-errors/lib/modules/rethrown-NOTUSED.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-errors/lib/modules/rethrown-NOTUSED.js
MIT
withCollectionProps = C => { const CollectionPropsWrapper = ({ collection: _collection, collectionName: _collectionName, ...otherProps }) => { const { collection, collectionName } = extractCollectionInfo({ collection: _collection, collectionName: _collectionName }); const typeName = collection...
Handle the collection or collectionName and pass down other related props (typeName, collectionName, etc.)
withCollectionProps
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/components/withCollectionProps.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/components/withCollectionProps.js
MIT
getFragmentName = (formType, collectionName, fragmentType) => [collectionName, formType, 'form', fragmentType, 'fragment'].map(Utils.capitalize).join('')
Generate mutation and query fragments for a form based on the schema TODO: refactor to mutualize more code with vulcan-core defaultFragment functions TODO: move to lib when refactored
getFragmentName
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/formFragments.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/formFragments.js
MIT
getFormFragments = ({ formType = 'new', // new || edit collectionName, typeName, schema, fields, // restrict on certain fields addFields, // add additional fields (eg to display static fields) }) => { // get the root schema fieldNames let queryFieldNames = getQueryFieldNames({ schema, o...
Generate query and mutation fragments for forms
getFormFragments
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/formFragments.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/formFragments.js
MIT
joinPath = array => array.reduce( (string, item) => string + ( Number.isNaN(Number(item)) ? `${string === '' ? '' : '.'}${item}` : `[${item}]` ), '', )
Joins a path in array format into a string. @param {[string|number]} array Path in array format @return {String}
joinPath
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/path_utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/path_utils.js
MIT
removePrefix = (prefix, paths) => { const explodedPrefix = splitPath(prefix); return paths.map(path => { if (path === prefix) { return path; } const explodedPath = splitPath(path); const explodedSuffix = takeRight( explodedPath, explodedPath.length - explodedPrefix.length, ); ...
Removes prefix from the given paths. @param {String} prefix @param {String[]} paths @return {String[]}
removePrefix
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/path_utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/path_utils.js
MIT
filterPathsByPrefix = (prefix, paths) => paths.filter(path => ( path === prefix || path.startsWith(`${prefix}.`) || path.startsWith(`${prefix}[`) ))
Filters paths that have the given prefix. @param {String} prefix @param {String[]} paths @return {String[]}
filterPathsByPrefix
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/path_utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/path_utils.js
MIT
mergeValue = ({ currentValue, documentValue, deletedValues: deletedFields, path, locale, datatype }) => { if (locale) { // note: intl fields are of type Object but should be treated as Strings return currentValue || documentValue || ''; } // note: retrieve nested deleted values is performed here to avoid...
Merges values. It takes into account the current, original and deleted values, and the merge produces the proper type for simple objects or arrays. @param {Object} props Form component props. Only specific properties for this function are documented. @param {*} props.currentValue Current value of the field @param {*...
mergeValue
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/utils.js
MIT
getDeletedValues = (deletedFields, accumulator = {}) => deletedFields.reduce((deletedValues, path) => set(deletedValues, path, null), accumulator)
Converts a list of field names to an object of deleted values. @param {string[]|Object.<string|string>} deletedFields List of deleted field names or paths @param {Object|Array=} accumulator={} Value to reduce the values to @return {Object|Array} Deleted values, with the structure defined by taking the received dele...
getDeletedValues
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/utils.js
MIT
getNestedDeletedValues = (prefix, deletedFields, accumulator = {}) => getDeletedValues(removePrefix(prefix, filterPathsByPrefix(prefix, deletedFields)), accumulator)
Filters the given field names by prefix, removes it from each one of them and convert the list to an object of deleted values. @param {string=} prefix Prefix to filter and remove from deleted fields @param {string[]|Object.<string|string>} deletedFields List of deleted field names or paths @param {Object|Array=} acc...
getNestedDeletedValues
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/utils.js
MIT
getNullValue = datatype => { const fieldType = getFieldType(datatype); if (fieldType === Array) { return []; } else if (fieldType === Boolean) { return false; } else if (fieldType === String) { return ''; } else if (fieldType === Number) { return ''; } else { // normalize to null ret...
Get appropriate null value for various field types @param {Array} datatype Field's datatype property
getNullValue
javascript
VulcanJS/Vulcan
packages/vulcan-forms/lib/modules/utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-forms/lib/modules/utils.js
MIT
function setToken(loginToken, expires) { if (loginToken && expires !== -1) { cookie.set('meteor_login_token', loginToken, { path: '/', expires, sameSite: 'lax', secure: document.domain !== 'localhost', }); } else { cookie.remove('meteor_login_token', { path: '/', }); ...
Manage meteor_login_token cookie Necessary for authentication when the Authorization header is not set E.g on first page loading
setToken
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/client/auth.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/client/auth.js
MIT
addCallback = function (hook, callback) { const formattedHook = formatHookName(hook); if (!callback.name) { // eslint-disable-next-line no-console console.log(`// Warning! You are adding an unnamed callback to ${formattedHook}. Please use the function foo () {} syntax.`); } // if callback array doesn...
@summary Add a callback function to a hook @param {String} hook - The name of the hook @param {Function} callback - The callback function
addCallback
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/callbacks.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/callbacks.js
MIT
removeCallback = function (hookName, callbackName) { const formattedHook = formatHookName(hookName); Callbacks[formattedHook] = _.reject(Callbacks[formattedHook], function (callback) { return callback.name === callbackName; }); }
@summary Remove a callback from a hook @param {string} hookName - The name of the hook @param {string} callbackName - The name of the function to remove
removeCallback
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/callbacks.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/callbacks.js
MIT
removeAllCallbacks = function(hookName) { const formattedHook = formatHookName(hookName); Callbacks[formattedHook] = []; }
@summary Remove all callbacks from a hook (mostly for testing purposes) @param {string} hookName - The name of the hook
removeAllCallbacks
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/callbacks.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/callbacks.js
MIT
runCallbacks = function () { let hook, item, args, callbacks, formattedHook; if (typeof arguments[0] === 'object' && arguments.length === 1) { const singleArgument = arguments[0]; hook = singleArgument.name; formattedHook = formatHookName(hook); item = singleArgument.iterator; args = singleArgu...
@summary Successively run all of a hook's callbacks on an item @param {String} hook - First argument: the name of the hook, or an array @param {Object} item - Second argument: the post, comment, modifier, etc. on which to run the callbacks @param {Any} args - Other arguments will be passed to each successive iteration ...
runCallbacks
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/callbacks.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/callbacks.js
MIT
runCallbacksAsync = function() { let hook, args, callbacks, formattedHook; if (typeof arguments[0] === 'object' && arguments.length === 1) { const singleArgument = arguments[0]; hook = singleArgument.name; formattedHook = formatHookName(hook); args = [singleArgument.properties]; // wrap in array for...
@summary Successively run all of a hook's callbacks on an item, in async mode (only works on server) @param {String} hook - First argument: the name of the hook @param {Any} args - Other arguments will be passed to each successive iteration
runCallbacksAsync
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/callbacks.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/callbacks.js
MIT
extendCollection = (collection, options) => { const newOptions = mergeWith({}, collection.options, options, (a, b) => { if (Array.isArray(a) && Array.isArray(b)) { return a.concat(b); } if (Array.isArray(a) && b) { return a.concat([b]); } if (Array.isArray(b) && a) { return b.con...
@summary Allow mongodb aggregation @param {Array} pipelines mongodb pipeline @param {Object} options mongodb option object
extendCollection
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/collections.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/collections.js
MIT
function registerComponent(name, rawComponent, ...hocs) { // support single-argument syntax if (typeof arguments[0] === 'object') { // note: cannot use `const` because name, components, hocs are already defined // as arguments so destructuring cannot work // eslint-disable-next-line no-redeclare var...
Register a Vulcan component with a name, a raw component than can be extended and one or more optional higher order components. @param {String} name The name of the component to register. @param {Component} rawComponent Interchangeable/extendable react component. @param {...(Function|Array)} hocs The HOCs to compose w...
registerComponent
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/components.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/components.js
MIT
componentExists = (name) => { const component = ComponentsTable[name]; return !!component; }
Returns true if a component with the given name has been registered with registerComponent(name, component, ...hocs). @param {String} name The name of the component to get. @returns {Boolean}
componentExists
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/components.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/components.js
MIT
getComponent = name => { const component = ComponentsTable[name]; if (!component) { throw new Error(`Component ${name} not registered.`); } if (component.hocs && component.hocs.length) { const hocs = component.hocs.map(hoc => { if (!Array.isArray(hoc)) { if (typeof hoc !== 'function') { ...
Get a component registered with registerComponent(name, component, ...hocs). @param {String} name The name of the component to get. @returns {Function|React Component} A (wrapped) React component
getComponent
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/components.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/components.js
MIT
getRawComponent = name => { return ComponentsTable[name].rawComponent; }
Get the **raw** (original) component registered with registerComponent without the possible HOCs wrapping it. @param {String} name The name of the component to get. @returns {Function|React Component} An interchangeable/extendable React component
getRawComponent
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/components.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/components.js
MIT
function replaceComponent(name, newComponent, ...newHocs) { // support single argument syntax if (typeof arguments[0] === 'object') { // eslint-disable-next-line no-redeclare var { name, component, hocs = [] } = arguments[0]; newComponent = component; newHocs = hocs; } const previousComponent =...
Replace a Vulcan component with the same name with a new component or an extension of the raw component and one or more optional higher order components. This function keeps track of the previous HOCs and wrap the new HOCs around previous ones @param {String} name The name of the component to register. @param {React C...
replaceComponent
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/components.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/components.js
MIT
instantiateComponent = (component, props) => { if (!component) { return null; } else if (typeof component === 'string') { const Component = Components[component]; return <Component {...props} />; } else if (React.isValidElement(component)) { return React.cloneElement(component, props); } else if...
Returns an instance of the given component name of function @param {string|function} component A component, the name of a component, or a react element @param {Object} [props] Optional properties to pass to the component
instantiateComponent
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/components.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/components.js
MIT
delayedComponent = name => { return props => { const Component = Components[name] || null; return Component && <Component {...props} />; }; }
Creates a component that will render the registered component with the given name. This function may be useful when in need for some registered component, but in contexts where they have not yet been initialized, for example at compile time execution. In other words, when using `Components.ComponentName` is not allow...
delayedComponent
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/components.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/components.js
MIT
dynamicLoader = importComponent => loadable({ loader: isFunction(importComponent) ? importComponent : () => importComponent, // backwards compatibility, // use delayedComponent, as this function can be used when Components is not populated yet loading: delayedComponent('DynamicLoading'), })
Returns a component that will perform the given dynamic import and render `Components.DynamicLoading` in the meantime. @example Register a component with a dynamic import registerComponent('MyComponent', dynamicLoader(() => import('./path/to/MyComponent'))); @example Pass a dynamic component to a route import { add...
dynamicLoader
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/dynamic_loader.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/dynamic_loader.js
MIT
getDynamicComponent = componentImport => { // eslint-disable-next-line no-console console.warn( 'getDynamicComponent is deprecated, use renderDynamicComponent instead.', 'If you want to retrieve the component instead that of just rendering it,', 'use dynamicLoader. See this issue to know how to do it: h...
Renders a dynamic component with the given props. @param {dynamicLoader~importComponent|Promise<React.Component>} importComponent @param {Object} props
getDynamicComponent
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/dynamic_loader.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/dynamic_loader.js
MIT
findByIds = async function(collection, ids, context) { // get documents const documents = await Connectors.find(collection, { _id: { $in: ids } }); // order documents in the same order as the ids passed as argument const orderedDocuments = ids.map(id => _.findWhere(documents, {_id: id})); return orderedD...
@summary Find by ids, for DataLoader, inspired by https://github.com/tmeasday/mongo-find-by-ids/blob/master/index.js
findByIds
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/findbyids.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/findbyids.js
MIT
getDefaultFragmentName = (collectionOrName) => { const collectionName = typeof collectionOrName === 'string' ? collectionOrName : collectionOrName.options.collectionName; return `${collectionName}DefaultFragment`; }
@param {*} collectionOrName A collection name, or a whole collection
getDefaultFragmentName
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/fragments.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/fragments.js
MIT
extractCollectionInfo = ({ collectionName, collection }) => { if (!(collectionName || collection)) throw new Error('Please specify either collection or collectionName'); const _collectionName = collectionName || collection.options.collectionName; const _collection = collection || getCollection(collectionName); ...
Extract collectionName from collection or collection from collectionName @param {*} param0
extractCollectionInfo
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/handleOptions.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/handleOptions.js
MIT
extractFragmentInfo = ({ fragment, fragmentName }, collectionName) => { if (!(fragment || fragmentName || collectionName)) throw new Error('Please specify either fragment or fragmentName, or pass a collectionName'); if (fragment) { return { fragment, fragmentName: fragmentName || getFragmentName...
Extract fragmentName from fragment or fragment from fragmentName
extractFragmentInfo
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/handleOptions.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/handleOptions.js
MIT
pluralizeString = (message, values) => { const results = message.match(/{[^,]+, plural, .+?}}/g); if (!results || !values) { return message; } let pluralizedMessage = message; for (let result of results) { const parts = result.replace(/^{|}$/g, '').split(', '); const key = parts[0]; const va...
Pluralize a string using [ICU Message syntax used by react-intl](https://formatjs.io/docs/core-concepts/icu-syntax/#plural-format). Note: `few` and `many` categories are not supported. @param {string} message @param {object} values @return {string}
pluralizeString
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/intl.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/intl.js
MIT
substituteStringValues = (message, values) => { let messageArray = [message]; Object.keys(values).forEach(key => { const value = values[key]; messageArray = messageArray.reduce((accumulator, message) => { if (typeof message !== 'string') { // if this message array element is not a string, pas...
Substitute values in a message using [react-intl Simple Argument syntax](https://formatjs.io/docs/core-concepts/icu-syntax/#simple-argument) @param {string} message @param {object} values Object with keys that may contain string, number, and React Node values @return {string|React.ReactNodeArray} If `values` only cont...
substituteStringValues
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/intl.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/intl.js
MIT
getIntlLabel = ({ intl, fieldName, collectionName, schema, isDescription }, values) => { if (!fieldName) { throw new Error('fieldName option passed to formatLabel cannot be empty or undefined'); } // if this is a description, just add .description at the end of the intl key const suffix = isDescription ? '...
getIntlLabel - Get a label for a field, for a given collection, in the current language. The evaluation is as follows : i18n(intlId) > i18n(collectionName.fieldName) > i18n(global.fieldName) > i18n(fieldName) @param {object} params @param {object} params.intl An intlShape object obtained from the react...
getIntlLabel
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/intl.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/intl.js
MIT
convertSelector = selector => { return selector; }
Converts selector and options to Mongo parameters (selector, fields)
convertSelector
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/mongoParams.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/mongoParams.js
MIT
createReactiveState = ({stateKey, schema, defaultValue, skipDuplicate}) => { if (reactiveStates[stateKey]) { if (skipDuplicate) return reactiveStates[stateKey]; throw new Error(`There is already a reactive state named ${stateKey}`); } if (schema) { schema = createSchema(schema); defaultValue = cl...
Create a new reactive state @param {string} stateKey The name/id/key for the new reactive state @param {Object|SimpleSchema} [schema] Optional schema definition object that will be converted to `SimpleSchema` using `createSchema()` @param {*} [defaultValue] Optional default value; alternatively you can define `defaul...
createReactiveState
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/reactive-state.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/reactive-state.js
MIT
getReactiveState = (stateKey) => { const stateObject = reactiveStates[stateKey]; if (!stateObject) { throw new Error(`There is no reactive state with stateKey ${stateKey}`); } return stateObject; }
Return a reactive state previously created @param {string} stateKey The key of the desired reactive state @returns {ReactiveState} @throws Will throw an error if there is no reactive state with the given key
getReactiveState
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/reactive-state.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/reactive-state.js
MIT
cleanReactiveStateValue = (value, schema) => { if (typeof value === 'object') { value = {...value}; if (schema) { value = schema.clean(value); schema.validate(value); } } return value; }
Given a value to be stored in state, this functions clones, cleans and validates it @param {Object} value The value object @param {SimpleSchema} [schema] Optional schema for validation @returns {Object} The cleaned value
cleanReactiveStateValue
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/reactive-state.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/reactive-state.js
MIT
resetReactiveState = () => { _forOwn(reactiveStates, function (stateObject, stateKey) { stateObject(null); }); }
Resets the value of all reactive states to their defaults
resetReactiveState
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/reactive-state.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/reactive-state.js
MIT
addAsChildRoute = (parentRouteName, addedRoutes) => { // if the parentRouteName does not exist, error if (!RoutesTable[parentRouteName]) { throw new Error(`Route ${parentRouteName} doesn't exist`); } // modify the routes table with the new routes addedRoutes.map(({ name, path, ...properties }) => { ...
A route is defined in the list like: (same as above) RoutesTable.foobar = { name: 'foobar', path: '/xyz', component: getComponent('FooBar') componentName: 'FooBar' // optional } NOTE: This is implemented on single level deep ONLY for now
addAsChildRoute
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/routes.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/routes.js
MIT
forEachDocumentField = (document, schema, callback, currentPath = '') => { if (!document) return; Object.keys(document).forEach(fieldName => { const fieldSchema = schema[fieldName]; callback({ fieldName, fieldSchema, currentPath, document, schema, isNested: !!currentPath }); // Check if we need a recur...
Iterate over a document fields and run a callback with side effect Works recursively for nested fields and arrays of objects (but excluding blackboxed objects, native JSON, and arrays of native values) @param {*} document Current document @param {*} schema Document schema @param {*} callback Called on each field with t...
forEachDocumentField
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/schema_utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/schema_utils.js
MIT
unarrayfyFieldName = (fieldName) => { return fieldName ? fieldName.split('.')[0] : fieldName; }
Helpers specific to Simple Schema See "schema_utils" for more generic methods
unarrayfyFieldName
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/simpleSchema_utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/simpleSchema_utils.js
MIT
getHtmlInputProps = props => { const { name, path, options, label, onChange, onBlur, value, disabled } = props; // these properties are whitelisted so that they can be safely passed to the actual form input // and avoid https://facebook.github.io/react/warnings/unknown-prop.html warnings const inputProperties ...
Extract input props for the FormComponentInner @param {*} props All component props @returns Initial props + props specific to the HTML input in an inputProperties object
getHtmlInputProps
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/ui_utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/ui_utils.js
MIT
capitalize = function (str) { return str && str.charAt(0).toUpperCase() + str.slice(1); }
@summary Capitalize a string. @param {String} str
capitalize
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/utils.js
MIT
registerStateLinkDefault = ({ name, defaultValue, options = {} }) => { registeredDefaults[name] = defaultValue; return registeredDefaults; }
Defaults are default response to queries
registerStateLinkDefault
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/apollo-common/links/state.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/apollo-common/links/state.js
MIT
getObjectFragment = ({ schema, fragmentName, options }) => { const fieldNames = getFragmentFieldNames({ schema, options }); const childFragments = fieldNames.length && fieldNames.map(fieldName => getFieldFragment({ schema, fieldName, options, getObjectFragment: getObj...
Generates the default fragment for a collection = a fragment containing all fields
getObjectFragment
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/graphql/defaultFragment.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/graphql/defaultFragment.js
MIT
getNestedGraphQLType = (typeName, fieldName, isInput) => `${typeName}${Utils.capitalize(unarrayfyFieldName(fieldName))}${isInput ? 'Input' : ''}`
Expected GraphQL Schema: # The room name name(locale: String): String @intl # The room name name_intl(locale: String): [IntlValue] @intl JS schema: name: { type: String, optional: false, canRead: ['guests'], canCreate: ['admins'], intl: true, },
getNestedGraphQLType
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/modules/graphql/utils.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/modules/graphql/utils.js
MIT
setupGraphQLMiddlewares = async (apolloServer, config, apolloApplyMiddlewareOptions) => { // IMPORTANT: order matters ! // 1 - Add request parsing middleware // 2 - Add apollo specific middlewares // 3 - CLOSE CONNEXION (otherwise the endpoint hungs) // 4 - ONLY THEN you can start adding other middlewares (gr...
@see https://www.apollographql.com/docs/apollo-server/whats-new.html @see https://www.apollographql.com/docs/apollo-server/migration-two-dot.html
setupGraphQLMiddlewares
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/apollo-server/apollo_server.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/apollo-server/apollo_server.js
MIT
getCorsOptions = () => { // enable all cors const enableAllcors = _get(Meteor.settings, 'apolloServer.corsEnableAll', false); if (enableAllcors) return true; // will allow all distant queries DANGEROUS // enable only a whitelist or nothing const corsWhitelist = _get(Meteor.settings, 'apolloServer.corsWhitelis...
setup CORS @see https://expressjs.com/en/resources/middleware/cors.html @see https://www.apollographql.com/docs/apollo-server/api/apollo-server/#apolloserver In Apollo, default cors is defined in packages/apollo-server/src/index.ts, it's too permissive so we use "false" in production
getCorsOptions
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/apollo-server/apollo_server.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/apollo-server/apollo_server.js
MIT
createApolloServer = ({ apolloServerOptions = {}, // apollo options config, // Vulcan options }) => { // given options contains the schema const apolloServer = new ApolloServer({ // graphql playground (replacement to graphiql), available on the app path playground: getPlaygroundConfig(config), // co...
Options: Apollo server usual options Config: a config specific to Vulcan
createApolloServer
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/apollo-server/apollo_server.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/apollo-server/apollo_server.js
MIT
initContext = currentContext => { let context; if (currentContext) { context = { ...currentContext }; } else { context = {}; } // add all collections to context Collections.forEach(c => (context[c.collectionName] = c)); // merge with custom context // TODO: deepmerge created an infinite loop ...
Called once on server creation @param {*} currentContext
initContext
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/apollo-server/context.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/apollo-server/context.js
MIT
getPlaygroundConfig = currentConfig => { // NOTE: this is redundant, Apollo won't show the GUI if NODE_ENV="production" if (!Meteor.isDevelopment) return undefined; return { endpoint: currentConfig.path, // allow override //FIXME: this global option does not exist yet... // @see https://github.com...
GraphQL Playground setup, through Apollo "gui" option
getPlaygroundConfig
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/apollo-server/playground.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/apollo-server/playground.js
MIT
makePageRenderer = ({ computeContext }) => { // onPageLoad callback const renderPage = async sink => { const req = sink.request; // according to the Apollo doc, client needs to be recreated on every request // this avoids caching server side const client = await createClient({ req, computeContext })...
Render the page server side @see https://github.com/szomolanyi/MeteorApolloStarter/blob/master/imports/startup/server/ssr.js @see https://github.com/apollographql/GitHunt-React/blob/master/src/server.js @see https://www.apollographql.com/docs/react/features/server-side-rendering.html#renderToStringWithData
makePageRenderer
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/apollo-ssr/renderPage.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/apollo-ssr/renderPage.js
MIT
getCollectionInfos = collection => { const collectionName = collection.options.collectionName; const typeName = collection.typeName ? collection.typeName : Utils.camelToSpaces(_initial(collectionName).join('')); // default to posts -> Post const schema = collection.simpleSchema()._schema; const description = co...
Extract relevant collection information and set default values @param {*} collection
getCollectionInfos
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/graphql/collection.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/graphql/collection.js
MIT
getType(typeName) { return { type: Object, blackbox: true, typeName: typeName, }; }
getType - pass this into the schema to make a nested object type, referencing another type. This type sould be declared through createCollection or addTypeAndResolvers @param {*} typeName @returns
getType
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/graphql/graphql.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/graphql/graphql.js
MIT
generateResolversFromSchema = schema => { if (!(schema instanceof SimpleSchema)) { throw Error('must pass a SimpleSchema to generate Resolvers'); } const { _schema, _firstLevelSchemaKeys } = schema; const resolvers = {}; _firstLevelSchemaKeys.forEach(key => { const field = _schema[key];...
Generate field resolvers for the type defined in the SimpleSchema. @param {SimpleSchema} schema @returns an object mapping the field names to a GraphQL resolver function
generateResolversFromSchema
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/graphql/resolvers.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/graphql/resolvers.js
MIT
capitalize = word => { if (!word) return word; const [first, ...rest] = word; return [first.toUpperCase(), ...rest].join(''); }
Generate graphQL types for the fields of a Vulcan schema
capitalize
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/graphql/schemaFields.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/graphql/schemaFields.js
MIT
getArrayChildSchema = (fieldName, schema) => { return getNestedSchema(getArrayChild(fieldName, schema)); }
// * Expected GraphQL Schema: // * // * # The room name // * name(locale: String): String @intl // * # The room name // * name_intl(locale: String): [IntlValue] @intl // * // * JS schema: // * // * name: { // * type: String, // * optional: false, // * canRead: ['guests'], // * ...
getArrayChildSchema
javascript
VulcanJS/Vulcan
packages/vulcan-lib/lib/server/graphql/schemaFields.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-lib/lib/server/graphql/schemaFields.js
MIT
getSubject = posts => { const subject = posts.map((post, index) => (index > 0 ? `, ${post.title}` : post.title)).join(''); return Utils.trimWords(subject, 15); }
@summary Build a newsletter subject from an array of posts (Called from Newsletter.send) @param {Array} posts
getSubject
javascript
VulcanJS/Vulcan
packages/vulcan-newsletter/lib/server/newsletters.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-newsletter/lib/server/newsletters.js
MIT
getNext = () => { var nextJob = SyncedCron.nextScheduledAtDate('scheduleNewsletter'); return nextJob; }
@summary Get info about the next scheduled newsletter
getNext
javascript
VulcanJS/Vulcan
packages/vulcan-newsletter/lib/server/newsletters.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-newsletter/lib/server/newsletters.js
MIT
getLast = () => { return Newsletters.findOne({}, { sort: { createdAt: -1 } }); }
@summary Get the last sent newsletter
getLast
javascript
VulcanJS/Vulcan
packages/vulcan-newsletter/lib/server/newsletters.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-newsletter/lib/server/newsletters.js
MIT
function _getConfig(configFileName) { const appdir = process.env.PWD || process.cwd(); const custom_config_filename = path.join(appdir, configFileName); let userConfig = {}; if (fileExists(custom_config_filename)) { userConfig = fs.readFileSync(custom_config_filename, { encoding: "utf8", }); ...
Build a path from current process working directory (i.e. meteor project root) and specified file name, try to get the file and parse its content. @param configFileName @returns {{}} @private
_getConfig
javascript
VulcanJS/Vulcan
packages/vulcan-scss/plugin/compile-scss.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-scss/plugin/compile-scss.js
MIT
function SubscribedCategoriesNotifications (post) { if (Meteor.isServer && !!post.categories && !!post.categories.length) { // get the subscribers of the different categories from the post's categories const subscribers = post.categories // find the category from its id ...
@summary Notify users subscribed to 'another user' whenever another user posts
SubscribedCategoriesNotifications
javascript
VulcanJS/Vulcan
packages/vulcan-subscribe/lib/callbacks.js
https://github.com/VulcanJS/Vulcan/blob/master/packages/vulcan-subscribe/lib/callbacks.js
MIT