id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
7,100
TerriaJS/terriajs
lib/Models/GeoJsonCatalogItem.js
filterValue
function filterValue(obj, prop, func) { for (var p in obj) { if (obj.hasOwnProperty(p) === false) { continue; } else if (p === prop) { if (func && typeof func === "function") { func(obj, prop); } } else if (typeof obj[p] === "object") { filterValue(obj[p], prop, func); ...
javascript
function filterValue(obj, prop, func) { for (var p in obj) { if (obj.hasOwnProperty(p) === false) { continue; } else if (p === prop) { if (func && typeof func === "function") { func(obj, prop); } } else if (typeof obj[p] === "object") { filterValue(obj[p], prop, func); ...
[ "function", "filterValue", "(", "obj", ",", "prop", ",", "func", ")", "{", "for", "(", "var", "p", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "p", ")", "===", "false", ")", "{", "continue", ";", "}", "else", "if", "(", ...
Find a member by name in the gml.
[ "Find", "a", "member", "by", "name", "in", "the", "gml", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/GeoJsonCatalogItem.js#L731-L743
7,101
TerriaJS/terriajs
lib/Models/GeoJsonCatalogItem.js
filterArray
function filterArray(pts, func) { if (!(pts[0] instanceof Array) || !(pts[0][0] instanceof Array)) { pts = func(pts); return pts; } var result = new Array(pts.length); for (var i = 0; i < pts.length; i++) { result[i] = filterArray(pts[i], func); //at array of arrays of points } return result; }
javascript
function filterArray(pts, func) { if (!(pts[0] instanceof Array) || !(pts[0][0] instanceof Array)) { pts = func(pts); return pts; } var result = new Array(pts.length); for (var i = 0; i < pts.length; i++) { result[i] = filterArray(pts[i], func); //at array of arrays of points } return result; }
[ "function", "filterArray", "(", "pts", ",", "func", ")", "{", "if", "(", "!", "(", "pts", "[", "0", "]", "instanceof", "Array", ")", "||", "!", "(", "pts", "[", "0", "]", "[", "0", "]", "instanceof", "Array", ")", ")", "{", "pts", "=", "func", ...
Filter a geojson coordinates array structure.
[ "Filter", "a", "geojson", "coordinates", "array", "structure", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/GeoJsonCatalogItem.js#L746-L757
7,102
TerriaJS/terriajs
lib/Models/SpatialDetailingCatalogFunction.js
function(terria) { CatalogFunction.call(this, terria); this.url = undefined; this.name = "Spatial Detailing"; this.description = "Predicts the characteristics of fine-grained regions by learning and exploiting correlations of coarse-grained data with Census characteristics."; this._regionTypeToPredictPa...
javascript
function(terria) { CatalogFunction.call(this, terria); this.url = undefined; this.name = "Spatial Detailing"; this.description = "Predicts the characteristics of fine-grained regions by learning and exploiting correlations of coarse-grained data with Census characteristics."; this._regionTypeToPredictPa...
[ "function", "(", "terria", ")", "{", "CatalogFunction", ".", "call", "(", "this", ",", "terria", ")", ";", "this", ".", "url", "=", "undefined", ";", "this", ".", "name", "=", "\"Spatial Detailing\"", ";", "this", ".", "description", "=", "\"Predicts the c...
A Terria Spatial Inference function to predicts the characteristics of fine-grained regions by learning and exploiting correlations of coarse-grained data with Census characteristics. @alias SpatialDetailingCatalogFunction @constructor @extends CatalogFunction @param {Terria} terria The Terria instance.
[ "A", "Terria", "Spatial", "Inference", "function", "to", "predicts", "the", "characteristics", "of", "fine", "-", "grained", "regions", "by", "learning", "and", "exploiting", "correlations", "of", "coarse", "-", "grained", "data", "with", "Census", "characteristic...
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/SpatialDetailingCatalogFunction.js#L24-L81
7,103
TerriaJS/terriajs
lib/Charts/ChartRenderer.js
findSelectedData
function findSelectedData(data, x) { // For each chart line (pointArray), find the point with the closest x to the mouse. const closestXPoints = data.map(line => line.points.reduce((previous, current) => Math.abs(current.x - x) < Math.abs(previous.x - x) ? current : previous ) ); // Of those, find...
javascript
function findSelectedData(data, x) { // For each chart line (pointArray), find the point with the closest x to the mouse. const closestXPoints = data.map(line => line.points.reduce((previous, current) => Math.abs(current.x - x) < Math.abs(previous.x - x) ? current : previous ) ); // Of those, find...
[ "function", "findSelectedData", "(", "data", ",", "x", ")", "{", "// For each chart line (pointArray), find the point with the closest x to the mouse.", "const", "closestXPoints", "=", "data", ".", "map", "(", "line", "=>", "line", ".", "points", ".", "reduce", "(", "...
Returns only the data lines which have a selected point on them, with an added "point" property for the selected point.
[ "Returns", "only", "the", "data", "lines", "which", "have", "a", "selected", "point", "on", "them", "with", "an", "added", "point", "property", "for", "the", "selected", "point", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Charts/ChartRenderer.js#L512-L534
7,104
TerriaJS/terriajs
lib/Models/GnafApi.js
function(corsProxy, overrideUrl) { this.url = corsProxy.getURLProxyIfNecessary( defaultValue(overrideUrl, DATA61_GNAF_SEARCH_URL) ); this.bulk_url = corsProxy.getURLProxyIfNecessary( defaultValue(overrideUrl, DATA61_GNAF_BULK_SEARCH_URL) ); }
javascript
function(corsProxy, overrideUrl) { this.url = corsProxy.getURLProxyIfNecessary( defaultValue(overrideUrl, DATA61_GNAF_SEARCH_URL) ); this.bulk_url = corsProxy.getURLProxyIfNecessary( defaultValue(overrideUrl, DATA61_GNAF_BULK_SEARCH_URL) ); }
[ "function", "(", "corsProxy", ",", "overrideUrl", ")", "{", "this", ".", "url", "=", "corsProxy", ".", "getURLProxyIfNecessary", "(", "defaultValue", "(", "overrideUrl", ",", "DATA61_GNAF_SEARCH_URL", ")", ")", ";", "this", ".", "bulk_url", "=", "corsProxy", "...
Simple JS Api for the Data61 Lucene GNAF service. @param {CorsProxy} corsProxy CorsProxy to use to determine whether calls need to go through the terria proxy. @param {String} [overrideUrl] The URL to use to query the service - will default if not provided. @constructor
[ "Simple", "JS", "Api", "for", "the", "Data61", "Lucene", "GNAF", "service", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/GnafApi.js#L23-L30
7,105
TerriaJS/terriajs
lib/Models/GnafApi.js
convertLuceneHit
function convertLuceneHit(locational, item) { var jsonInfo = JSON.parse(item.json); return { score: item.score, locational: locational, name: item.d61Address .slice(0, 3) .filter(function(string) { return string.length > 0; }) .join(", "), flatNumber: sanitiseAddress...
javascript
function convertLuceneHit(locational, item) { var jsonInfo = JSON.parse(item.json); return { score: item.score, locational: locational, name: item.d61Address .slice(0, 3) .filter(function(string) { return string.length > 0; }) .join(", "), flatNumber: sanitiseAddress...
[ "function", "convertLuceneHit", "(", "locational", ",", "item", ")", "{", "var", "jsonInfo", "=", "JSON", ".", "parse", "(", "item", ".", "json", ")", ";", "return", "{", "score", ":", "item", ".", "score", ",", "locational", ":", "locational", ",", "n...
Converts from the Lucene schema to a neater one better suited to addresses. @param {boolean} locational Whether to set locational to true - this is set for results that came up within the bounding box passed to {@link #geoCode}. @param {object} item The lucene schema object to convert.
[ "Converts", "from", "the", "Lucene", "schema", "to", "a", "neater", "one", "better", "suited", "to", "addresses", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/GnafApi.js#L201-L232
7,106
TerriaJS/terriajs
lib/Models/GnafApi.js
buildRequestData
function buildRequestData(searchTerm, maxResults) { var requestData = { numHits: maxResults, fuzzy: { maxEdits: 2, minLength: 5, prefixLength: 2 } }; if (searchTerm instanceof Array) { requestData["addresses"] = searchTerm.map(processAddress); } else { requestData["addr"] ...
javascript
function buildRequestData(searchTerm, maxResults) { var requestData = { numHits: maxResults, fuzzy: { maxEdits: 2, minLength: 5, prefixLength: 2 } }; if (searchTerm instanceof Array) { requestData["addresses"] = searchTerm.map(processAddress); } else { requestData["addr"] ...
[ "function", "buildRequestData", "(", "searchTerm", ",", "maxResults", ")", "{", "var", "requestData", "=", "{", "numHits", ":", "maxResults", ",", "fuzzy", ":", "{", "maxEdits", ":", "2", ",", "minLength", ":", "5", ",", "prefixLength", ":", "2", "}", "}...
Builds the data to be POSTed to elastic search. @param {string} searchTerm The plain-text query to search for. @param {number} maxResults The max number of results to search for.
[ "Builds", "the", "data", "to", "be", "POSTed", "to", "elastic", "search", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/GnafApi.js#L248-L264
7,107
TerriaJS/terriajs
lib/Models/GnafApi.js
addBoundingBox
function addBoundingBox(requestData, rectangle) { requestData["box"] = { minLat: CesiumMath.toDegrees(rectangle.south), maxLon: CesiumMath.toDegrees(rectangle.east), maxLat: CesiumMath.toDegrees(rectangle.north), minLon: CesiumMath.toDegrees(rectangle.west) }; }
javascript
function addBoundingBox(requestData, rectangle) { requestData["box"] = { minLat: CesiumMath.toDegrees(rectangle.south), maxLon: CesiumMath.toDegrees(rectangle.east), maxLat: CesiumMath.toDegrees(rectangle.north), minLon: CesiumMath.toDegrees(rectangle.west) }; }
[ "function", "addBoundingBox", "(", "requestData", ",", "rectangle", ")", "{", "requestData", "[", "\"box\"", "]", "=", "{", "minLat", ":", "CesiumMath", ".", "toDegrees", "(", "rectangle", ".", "south", ")", ",", "maxLon", ":", "CesiumMath", ".", "toDegrees"...
Adds a bounding box filter to the search query for elastic search. This simply modifies requestData and returns nothing. @param {object} requestData Request data to modify @param {Rectangle} rectangle rectangle to source the bounding box from.
[ "Adds", "a", "bounding", "box", "filter", "to", "the", "search", "query", "for", "elastic", "search", ".", "This", "simply", "modifies", "requestData", "and", "returns", "nothing", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/GnafApi.js#L283-L290
7,108
TerriaJS/terriajs
lib/Models/GnafApi.js
splitIntoBatches
function splitIntoBatches(arrayToSplit, batchSize) { var arrayBatches = []; var minSlice = 0; var finish = false; for (var maxSlice = batchSize; maxSlice < Infinity; maxSlice += batchSize) { if (maxSlice >= arrayToSplit.length) { maxSlice = arrayToSplit.length; finish = true; } arrayBatc...
javascript
function splitIntoBatches(arrayToSplit, batchSize) { var arrayBatches = []; var minSlice = 0; var finish = false; for (var maxSlice = batchSize; maxSlice < Infinity; maxSlice += batchSize) { if (maxSlice >= arrayToSplit.length) { maxSlice = arrayToSplit.length; finish = true; } arrayBatc...
[ "function", "splitIntoBatches", "(", "arrayToSplit", ",", "batchSize", ")", "{", "var", "arrayBatches", "=", "[", "]", ";", "var", "minSlice", "=", "0", ";", "var", "finish", "=", "false", ";", "for", "(", "var", "maxSlice", "=", "batchSize", ";", "maxSl...
Breaks an array into pieces, putting them in another array. @param {Array} arrayToSplit array to split @param {number} batchSize maximum number of items in each array at end @return array containing other arrays, which contain a maxiumum number of items in each.
[ "Breaks", "an", "array", "into", "pieces", "putting", "them", "in", "another", "array", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/GnafApi.js#L299-L315
7,109
TerriaJS/terriajs
lib/Core/supportsWebGL.js
supportsWebGL
function supportsWebGL() { if (defined(result)) { return result; } //Check for webgl support and if not, then fall back to leaflet if (!window.WebGLRenderingContext) { // Browser has no idea what WebGL is. Suggest they // get a new browser by presenting the user with link to // http://get.webgl...
javascript
function supportsWebGL() { if (defined(result)) { return result; } //Check for webgl support and if not, then fall back to leaflet if (!window.WebGLRenderingContext) { // Browser has no idea what WebGL is. Suggest they // get a new browser by presenting the user with link to // http://get.webgl...
[ "function", "supportsWebGL", "(", ")", "{", "if", "(", "defined", "(", "result", ")", ")", "{", "return", "result", ";", "}", "//Check for webgl support and if not, then fall back to leaflet", "if", "(", "!", "window", ".", "WebGLRenderingContext", ")", "{", "// B...
Determines if the current browser supports WebGL. @return {Boolean|String} False if WebGL is not supported at all, 'slow' if WebGL is supported but it has a major performance caveat (e.g. software rendering), and True if WebGL is available without a major performance caveat.
[ "Determines", "if", "the", "current", "browser", "supports", "WebGL", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Core/supportsWebGL.js#L14-L57
7,110
TerriaJS/terriajs
lib/Models/CatalogMember.js
getParentIds
function getParentIds(catalogMember, parentIds) { parentIds = defaultValue(parentIds, []); if (defined(catalogMember.parent)) { return getParentIds( catalogMember.parent, parentIds.concat([catalogMember.uniqueId]) ); } return parentIds; }
javascript
function getParentIds(catalogMember, parentIds) { parentIds = defaultValue(parentIds, []); if (defined(catalogMember.parent)) { return getParentIds( catalogMember.parent, parentIds.concat([catalogMember.uniqueId]) ); } return parentIds; }
[ "function", "getParentIds", "(", "catalogMember", ",", "parentIds", ")", "{", "parentIds", "=", "defaultValue", "(", "parentIds", ",", "[", "]", ")", ";", "if", "(", "defined", "(", "catalogMember", ".", "parent", ")", ")", "{", "return", "getParentIds", "...
Gets the ids of all parents of a catalog member, ordered from the closest descendant to the most distant. Ignores the root. @private @param catalogMember The catalog member to get parent ids for. @param parentIds A starting list of parent ids to add to (allows the function to work recursively). @returns {String[]}
[ "Gets", "the", "ids", "of", "all", "parents", "of", "a", "catalog", "member", "ordered", "from", "the", "closest", "descendant", "to", "the", "most", "distant", ".", "Ignores", "the", "root", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/CatalogMember.js#L543-L554
7,111
TerriaJS/terriajs
lib/Models/TableCatalogItem.js
createDataSourceForLatLong
function createDataSourceForLatLong(item, tableStructure) { // Create the TableDataSource and save it to item._dataSource. item._dataSource = new TableDataSource( item.terria, tableStructure, item._tableStyle, item.name, item.polling.seconds > 0 ); item._dataSource.changedEvent.addEventListe...
javascript
function createDataSourceForLatLong(item, tableStructure) { // Create the TableDataSource and save it to item._dataSource. item._dataSource = new TableDataSource( item.terria, tableStructure, item._tableStyle, item.name, item.polling.seconds > 0 ); item._dataSource.changedEvent.addEventListe...
[ "function", "createDataSourceForLatLong", "(", "item", ",", "tableStructure", ")", "{", "// Create the TableDataSource and save it to item._dataSource.", "item", ".", "_dataSource", "=", "new", "TableDataSource", "(", "item", ".", "terria", ",", "tableStructure", ",", "it...
Creates a datasource based on tableStructure provided and adds it to item. Suitable for TableStructures that contain lat-lon columns. @param {TableCatalogItem} item Item that tableDataSource is created for. @param {TableStructure} tableStructure TableStructure to use in creating datasource. @return {Promise} @private
[ "Creates", "a", "datasource", "based", "on", "tableStructure", "provided", "and", "adds", "it", "to", "item", ".", "Suitable", "for", "TableStructures", "that", "contain", "lat", "-", "lon", "columns", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/TableCatalogItem.js#L817-L835
7,112
TerriaJS/terriajs
lib/Models/Leaflet.js
function(terria, map) { GlobeOrMap.call(this, terria); /** * Gets or sets the Leaflet {@link Map} instance. * @type {Map} */ this.map = map; this.scene = new LeafletScene(map); /** * Gets or sets whether this viewer _can_ show a splitter. * @type {Boolean} */ this.canShowSplitter = true...
javascript
function(terria, map) { GlobeOrMap.call(this, terria); /** * Gets or sets the Leaflet {@link Map} instance. * @type {Map} */ this.map = map; this.scene = new LeafletScene(map); /** * Gets or sets whether this viewer _can_ show a splitter. * @type {Boolean} */ this.canShowSplitter = true...
[ "function", "(", "terria", ",", "map", ")", "{", "GlobeOrMap", ".", "call", "(", "this", ",", "terria", ")", ";", "/**\n * Gets or sets the Leaflet {@link Map} instance.\n * @type {Map}\n */", "this", ".", "map", "=", "map", ";", "this", ".", "scene", "=", ...
The Leaflet viewer component @alias Leaflet @constructor @extends GlobeOrMap @param {Terria} terria The Terria instance. @param {Map} map The leaflet map instance.
[ "The", "Leaflet", "viewer", "component" ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/Leaflet.js#L85-L202
7,113
TerriaJS/terriajs
lib/Models/Leaflet.js
updateOneLayer
function updateOneLayer(item, currZIndex) { if (defined(item.imageryLayer) && defined(item.imageryLayer.setZIndex)) { if (item.supportsReordering) { item.imageryLayer.setZIndex(currZIndex.reorderable++); } else { item.imageryLayer.setZIndex(currZIndex.fixed++); } } }
javascript
function updateOneLayer(item, currZIndex) { if (defined(item.imageryLayer) && defined(item.imageryLayer.setZIndex)) { if (item.supportsReordering) { item.imageryLayer.setZIndex(currZIndex.reorderable++); } else { item.imageryLayer.setZIndex(currZIndex.fixed++); } } }
[ "function", "updateOneLayer", "(", "item", ",", "currZIndex", ")", "{", "if", "(", "defined", "(", "item", ".", "imageryLayer", ")", "&&", "defined", "(", "item", ".", "imageryLayer", ".", "setZIndex", ")", ")", "{", "if", "(", "item", ".", "supportsReor...
this private function is called by updateLayerOrder
[ "this", "private", "function", "is", "called", "by", "updateLayerOrder" ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/Leaflet.js#L507-L515
7,114
TerriaJS/terriajs
lib/Models/ImageryLayerCatalogItem.js
nextLayerFromIndex
function nextLayerFromIndex(index) { const imageryProvider = catalogItem.createImageryProvider( catalogItem.intervals.get(index).data ); imageryProvider.enablePickFeatures = false; catalogItem._nextLayer = ImageryLayerCatalogItem.enableLayer( catalogItem, imageryProvider, 0.0 ...
javascript
function nextLayerFromIndex(index) { const imageryProvider = catalogItem.createImageryProvider( catalogItem.intervals.get(index).data ); imageryProvider.enablePickFeatures = false; catalogItem._nextLayer = ImageryLayerCatalogItem.enableLayer( catalogItem, imageryProvider, 0.0 ...
[ "function", "nextLayerFromIndex", "(", "index", ")", "{", "const", "imageryProvider", "=", "catalogItem", ".", "createImageryProvider", "(", "catalogItem", ".", "intervals", ".", "get", "(", "index", ")", ".", "data", ")", ";", "imageryProvider", ".", "enablePic...
Given an interval index, set up an imagery provider and layer.
[ "Given", "an", "interval", "index", "set", "up", "an", "imagery", "provider", "and", "layer", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/ImageryLayerCatalogItem.js#L1243-L1255
7,115
TerriaJS/terriajs
lib/Models/CkanCatalogGroup.js
addItem
function addItem(resource, rootCkanGroup, itemData, extras, parent) { var item = rootCkanGroup.terria.catalog.shareKeyIndex[ parent.uniqueId + "/" + resource.id ]; var alreadyExists = defined(item); if (!alreadyExists) { item = createItemFromResource( resource, rootCkanGroup, ...
javascript
function addItem(resource, rootCkanGroup, itemData, extras, parent) { var item = rootCkanGroup.terria.catalog.shareKeyIndex[ parent.uniqueId + "/" + resource.id ]; var alreadyExists = defined(item); if (!alreadyExists) { item = createItemFromResource( resource, rootCkanGroup, ...
[ "function", "addItem", "(", "resource", ",", "rootCkanGroup", ",", "itemData", ",", "extras", ",", "parent", ")", "{", "var", "item", "=", "rootCkanGroup", ".", "terria", ".", "catalog", ".", "shareKeyIndex", "[", "parent", ".", "uniqueId", "+", "\"/\"", "...
Creates a catalog item from the supplied resource and adds it to the supplied parent if necessary.. @private @param resource The Ckan resource @param rootCkanGroup The root group of all items in this Ckan hierarchy @param itemData The data of the item to build the catalog item from @param extras @param parent The paren...
[ "Creates", "a", "catalog", "item", "from", "the", "supplied", "resource", "and", "adds", "it", "to", "the", "supplied", "parent", "if", "necessary", ".." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Models/CkanCatalogGroup.js#L845-L867
7,116
TerriaJS/terriajs
lib/Map/featureDataToGeoJson.js
getEsriGeometry
function getEsriGeometry(featureData, geometryType, spatialReference) { if (defined(featureData.features)) { // This is a FeatureCollection. return { type: "FeatureCollection", crs: esriSpatialReferenceToCrs(featureData.spatialReference), features: featureData.features.map(function(subFeatur...
javascript
function getEsriGeometry(featureData, geometryType, spatialReference) { if (defined(featureData.features)) { // This is a FeatureCollection. return { type: "FeatureCollection", crs: esriSpatialReferenceToCrs(featureData.spatialReference), features: featureData.features.map(function(subFeatur...
[ "function", "getEsriGeometry", "(", "featureData", ",", "geometryType", ",", "spatialReference", ")", "{", "if", "(", "defined", "(", "featureData", ".", "features", ")", ")", "{", "// This is a FeatureCollection.", "return", "{", "type", ":", "\"FeatureCollection\"...
spatialReference is optional.
[ "spatialReference", "is", "optional", "." ]
abcce28ff189f6fdbc0ee541a235ec6cabd90bd5
https://github.com/TerriaJS/terriajs/blob/abcce28ff189f6fdbc0ee541a235ec6cabd90bd5/lib/Map/featureDataToGeoJson.js#L63-L155
7,117
cornerstonejs/cornerstoneTools
src/store/setToolMode.js
function( element, toolName, options, interactionTypes ) { // If interactionTypes was passed in via options if (interactionTypes === undefined && Array.isArray(options)) { interactionTypes = options; options = null; } const tool = getToolForElement(element, toolName); if (tool) { _resolv...
javascript
function( element, toolName, options, interactionTypes ) { // If interactionTypes was passed in via options if (interactionTypes === undefined && Array.isArray(options)) { interactionTypes = options; options = null; } const tool = getToolForElement(element, toolName); if (tool) { _resolv...
[ "function", "(", "element", ",", "toolName", ",", "options", ",", "interactionTypes", ")", "{", "// If interactionTypes was passed in via options", "if", "(", "interactionTypes", "===", "undefined", "&&", "Array", ".", "isArray", "(", "options", ")", ")", "{", "in...
Sets a tool's state, with the provided toolName and element, to 'active'. Active tools are rendered, respond to user input, and can create new data. @public @function setToolActiveForElement @memberof CornerstoneTools @example <caption>Setting a tool 'active' for a specific interaction type.</caption> // Sets length ...
[ "Sets", "a", "tool", "s", "state", "with", "the", "provided", "toolName", "and", "element", "to", "active", ".", "Active", "tools", "are", "rendered", "respond", "to", "user", "input", "and", "can", "create", "new", "data", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/setToolMode.js#L39-L79
7,118
cornerstonejs/cornerstoneTools
src/store/setToolMode.js
_resolveGenericInputConflicts
function _resolveGenericInputConflicts( interactionType, tool, element, options ) { const interactionTypeFlag = `is${interactionType}Active`; const activeToolWithActiveInteractionType = store.state.tools.find( t => t.element === element && t.mode === 'active' && t.options[interactionTy...
javascript
function _resolveGenericInputConflicts( interactionType, tool, element, options ) { const interactionTypeFlag = `is${interactionType}Active`; const activeToolWithActiveInteractionType = store.state.tools.find( t => t.element === element && t.mode === 'active' && t.options[interactionTy...
[ "function", "_resolveGenericInputConflicts", "(", "interactionType", ",", "tool", ",", "element", ",", "options", ")", "{", "const", "interactionTypeFlag", "=", "`", "${", "interactionType", "}", "`", ";", "const", "activeToolWithActiveInteractionType", "=", "store", ...
If the incoming tool isTouchActive, find any conflicting tools and set their isTouchActive to false to avoid conflicts. @private @function _resolveGenericInputConflicts @param {string} interactionType @param {Object} tool @param {HTMLElement} element @param {(Object|number)} options @returns {undefined}
[ "If", "the", "incoming", "tool", "isTouchActive", "find", "any", "conflicting", "tools", "and", "set", "their", "isTouchActive", "to", "false", "to", "avoid", "conflicts", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/setToolMode.js#L507-L529
7,119
cornerstonejs/cornerstoneTools
src/eventListeners/mouseEventListeners.js
onMouseUp
function onMouseUp(e) { // Cancel the timeout preventing the click event from triggering clearTimeout(preventClickTimeout); let eventType = EVENTS.MOUSE_UP; if (isClickEvent) { eventType = EVENTS.MOUSE_CLICK; } // Calculate our current points in page and image coordinates const curr...
javascript
function onMouseUp(e) { // Cancel the timeout preventing the click event from triggering clearTimeout(preventClickTimeout); let eventType = EVENTS.MOUSE_UP; if (isClickEvent) { eventType = EVENTS.MOUSE_CLICK; } // Calculate our current points in page and image coordinates const curr...
[ "function", "onMouseUp", "(", "e", ")", "{", "// Cancel the timeout preventing the click event from triggering", "clearTimeout", "(", "preventClickTimeout", ")", ";", "let", "eventType", "=", "EVENTS", ".", "MOUSE_UP", ";", "if", "(", "isClickEvent", ")", "{", "eventT...
Hook mouseup so we can unbind our event listeners When they stop dragging
[ "Hook", "mouseup", "so", "we", "can", "unbind", "our", "event", "listeners", "When", "they", "stop", "dragging" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/eventListeners/mouseEventListeners.js#L204-L271
7,120
cornerstonejs/cornerstoneTools
src/stackTools/stackPrefetch.js
removeFromList
function removeFromList(imageIdIndex) { const index = stackPrefetch.indicesToRequest.indexOf(imageIdIndex); if (index > -1) { // Don't remove last element if imageIdIndex not found stackPrefetch.indicesToRequest.splice(index, 1); } }
javascript
function removeFromList(imageIdIndex) { const index = stackPrefetch.indicesToRequest.indexOf(imageIdIndex); if (index > -1) { // Don't remove last element if imageIdIndex not found stackPrefetch.indicesToRequest.splice(index, 1); } }
[ "function", "removeFromList", "(", "imageIdIndex", ")", "{", "const", "index", "=", "stackPrefetch", ".", "indicesToRequest", ".", "indexOf", "(", "imageIdIndex", ")", ";", "if", "(", "index", ">", "-", "1", ")", "{", "// Don't remove last element if imageIdIndex ...
Remove an imageIdIndex from the list of indices to request This fires when the individual image loading deferred is resolved
[ "Remove", "an", "imageIdIndex", "from", "the", "list", "of", "indices", "to", "request", "This", "fires", "when", "the", "individual", "image", "loading", "deferred", "is", "resolved" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/stackTools/stackPrefetch.js#L102-L109
7,121
cornerstonejs/cornerstoneTools
src/stateManagement/imageIdSpecificStateManager.js
clearImageIdSpecificToolStateManager
function clearImageIdSpecificToolStateManager(element) { const enabledElement = external.cornerstone.getEnabledElement(element); if ( !enabledElement.image || toolState.hasOwnProperty(enabledElement.image.imageId) === false ) { return; } delete toolState[enabledElement.image.imag...
javascript
function clearImageIdSpecificToolStateManager(element) { const enabledElement = external.cornerstone.getEnabledElement(element); if ( !enabledElement.image || toolState.hasOwnProperty(enabledElement.image.imageId) === false ) { return; } delete toolState[enabledElement.image.imag...
[ "function", "clearImageIdSpecificToolStateManager", "(", "element", ")", "{", "const", "enabledElement", "=", "external", ".", "cornerstone", ".", "getEnabledElement", "(", "element", ")", ";", "if", "(", "!", "enabledElement", ".", "image", "||", "toolState", "."...
Clears all tool data from this toolStateManager.
[ "Clears", "all", "tool", "data", "from", "this", "toolStateManager", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/stateManagement/imageIdSpecificStateManager.js#L91-L102
7,122
cornerstonejs/cornerstoneTools
src/stackTools/playClip.js
stopClip
function stopClip(element) { const playClipToolData = getToolState(element, toolType); if ( !playClipToolData || !playClipToolData.data || !playClipToolData.data.length ) { return; } stopClipWithData(playClipToolData.data[0]); }
javascript
function stopClip(element) { const playClipToolData = getToolState(element, toolType); if ( !playClipToolData || !playClipToolData.data || !playClipToolData.data.length ) { return; } stopClipWithData(playClipToolData.data[0]); }
[ "function", "stopClip", "(", "element", ")", "{", "const", "playClipToolData", "=", "getToolState", "(", "element", ",", "toolType", ")", ";", "if", "(", "!", "playClipToolData", "||", "!", "playClipToolData", ".", "data", "||", "!", "playClipToolData", ".", ...
Stops an already playing clip. @param {HTMLElement} element @returns {void}
[ "Stops", "an", "already", "playing", "clip", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/stackTools/playClip.js#L289-L301
7,123
cornerstonejs/cornerstoneTools
src/store/modules/brushModule.js
removeEnabledElementCallback
function removeEnabledElementCallback(enabledElement) { if (!external.cornerstone) { return; } const cornerstoneEnabledElement = external.cornerstone.getEnabledElement( enabledElement ); const enabledElementUID = cornerstoneEnabledElement.uuid; const colormap = external.cornerstone.colors.getColor...
javascript
function removeEnabledElementCallback(enabledElement) { if (!external.cornerstone) { return; } const cornerstoneEnabledElement = external.cornerstone.getEnabledElement( enabledElement ); const enabledElementUID = cornerstoneEnabledElement.uuid; const colormap = external.cornerstone.colors.getColor...
[ "function", "removeEnabledElementCallback", "(", "enabledElement", ")", "{", "if", "(", "!", "external", ".", "cornerstone", ")", "{", "return", ";", "}", "const", "cornerstoneEnabledElement", "=", "external", ".", "cornerstone", ".", "getEnabledElement", "(", "en...
RemoveEnabledElementCallback - Element specific memory cleanup. @public @param {Object} enabledElement The element being removed. @returns {void} TODO -> Test this before adding it to the module.
[ "RemoveEnabledElementCallback", "-", "Element", "specific", "memory", "cleanup", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/modules/brushModule.js#L146-L162
7,124
cornerstonejs/cornerstoneTools
src/store/modules/brushModule.js
_getNextColorPair
function _getNextColorPair() { const indexPair = [colorPairIndex]; if (colorPairIndex < distinctColors.length - 1) { colorPairIndex++; indexPair.push(colorPairIndex); } else { colorPairIndex = 0; indexPair.push(colorPairIndex); } return indexPair; }
javascript
function _getNextColorPair() { const indexPair = [colorPairIndex]; if (colorPairIndex < distinctColors.length - 1) { colorPairIndex++; indexPair.push(colorPairIndex); } else { colorPairIndex = 0; indexPair.push(colorPairIndex); } return indexPair; }
[ "function", "_getNextColorPair", "(", ")", "{", "const", "indexPair", "=", "[", "colorPairIndex", "]", ";", "if", "(", "colorPairIndex", "<", "distinctColors", ".", "length", "-", "1", ")", "{", "colorPairIndex", "++", ";", "indexPair", ".", "push", "(", "...
_getNextColorPair - returns the next pair of indicies to interpolate between. @private @returns {Array} An array containing the two indicies.
[ "_getNextColorPair", "-", "returns", "the", "next", "pair", "of", "indicies", "to", "interpolate", "between", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/modules/brushModule.js#L258-L270
7,125
cornerstonejs/cornerstoneTools
src/store/internals/removeEnabledElement.js
function(enabledElement) { // Note: We may want to `setToolDisabled` before removing from store // Or take other action to remove any lingering eventListeners/state store.state.tools = store.state.tools.filter( tool => tool.element !== enabledElement ); }
javascript
function(enabledElement) { // Note: We may want to `setToolDisabled` before removing from store // Or take other action to remove any lingering eventListeners/state store.state.tools = store.state.tools.filter( tool => tool.element !== enabledElement ); }
[ "function", "(", "enabledElement", ")", "{", "// Note: We may want to `setToolDisabled` before removing from store", "// Or take other action to remove any lingering eventListeners/state", "store", ".", "state", ".", "tools", "=", "store", ".", "state", ".", "tools", ".", "filt...
Remove all tools associated with enabled element. @private @method @param {HTMLElement} enabledElement @returns {void}
[ "Remove", "all", "tools", "associated", "with", "enabled", "element", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/internals/removeEnabledElement.js#L70-L76
7,126
cornerstonejs/cornerstoneTools
src/store/internals/removeEnabledElement.js
function(enabledElement) { if (store.modules) { _cleanModulesOnElement(enabledElement); } const foundElementIndex = store.state.enabledElements.findIndex( element => element === enabledElement ); if (foundElementIndex > -1) { store.state.enabledElements.splice(foundElementIndex, 1); } else { ...
javascript
function(enabledElement) { if (store.modules) { _cleanModulesOnElement(enabledElement); } const foundElementIndex = store.state.enabledElements.findIndex( element => element === enabledElement ); if (foundElementIndex > -1) { store.state.enabledElements.splice(foundElementIndex, 1); } else { ...
[ "function", "(", "enabledElement", ")", "{", "if", "(", "store", ".", "modules", ")", "{", "_cleanModulesOnElement", "(", "enabledElement", ")", ";", "}", "const", "foundElementIndex", "=", "store", ".", "state", ".", "enabledElements", ".", "findIndex", "(", ...
Remove the enabled element from the store if it exists. @private @method @param {HTMLElement} enabledElement @returns {void}
[ "Remove", "the", "enabled", "element", "from", "the", "store", "if", "it", "exists", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/internals/removeEnabledElement.js#L85-L99
7,127
cornerstonejs/cornerstoneTools
src/store/internals/removeEnabledElement.js
_cleanModulesOnElement
function _cleanModulesOnElement(enabledElement) { const modules = store.modules; Object.keys(modules).forEach(function(key) { if (typeof modules[key].removeEnabledElementCallback === 'function') { modules[key].removeEnabledElementCallback(enabledElement); } }); }
javascript
function _cleanModulesOnElement(enabledElement) { const modules = store.modules; Object.keys(modules).forEach(function(key) { if (typeof modules[key].removeEnabledElementCallback === 'function') { modules[key].removeEnabledElementCallback(enabledElement); } }); }
[ "function", "_cleanModulesOnElement", "(", "enabledElement", ")", "{", "const", "modules", "=", "store", ".", "modules", ";", "Object", ".", "keys", "(", "modules", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "typeof", "modules",...
Iterate over our store's modules. If the module has a `removeEnabledElementCallback` call it and clean up unneeded metadata. @private @method @param {Object} enabledElement @returns {void}
[ "Iterate", "over", "our", "store", "s", "modules", ".", "If", "the", "module", "has", "a", "removeEnabledElementCallback", "call", "it", "and", "clean", "up", "unneeded", "metadata", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/internals/removeEnabledElement.js#L109-L117
7,128
cornerstonejs/cornerstoneTools
src/eventListeners/onImageRenderedBrushEventHandler.js
_drawImageBitmap
function _drawImageBitmap(evt, imageBitmap, alwaysVisible) { const eventData = evt.detail; const context = getNewContext(eventData.canvasContext.canvas); const canvasTopLeft = external.cornerstone.pixelToCanvas(eventData.element, { x: 0, y: 0, }); const canvasTopRight = external.cornerstone.pixelToC...
javascript
function _drawImageBitmap(evt, imageBitmap, alwaysVisible) { const eventData = evt.detail; const context = getNewContext(eventData.canvasContext.canvas); const canvasTopLeft = external.cornerstone.pixelToCanvas(eventData.element, { x: 0, y: 0, }); const canvasTopRight = external.cornerstone.pixelToC...
[ "function", "_drawImageBitmap", "(", "evt", ",", "imageBitmap", ",", "alwaysVisible", ")", "{", "const", "eventData", "=", "evt", ".", "detail", ";", "const", "context", "=", "getNewContext", "(", "eventData", ".", "canvasContext", ".", "canvas", ")", ";", "...
Draws the ImageBitmap the canvas. @private @param {Object} evt description @param {ImageBitmap} imageBitmap @param {Boolean} alwaysVisible @returns {void}
[ "Draws", "the", "ImageBitmap", "the", "canvas", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/eventListeners/onImageRenderedBrushEventHandler.js#L198-L255
7,129
cornerstonejs/cornerstoneTools
src/tools/FreehandSculpterMouseTool.js
getDefaultFreehandSculpterMouseToolConfiguration
function getDefaultFreehandSculpterMouseToolConfiguration() { return { mouseLocation: { handles: { start: { highlight: true, active: true, }, }, }, minSpacing: 1, currentTool: null, dragColor: toolColors.getActiveColor(), hoverColor: toolColors.g...
javascript
function getDefaultFreehandSculpterMouseToolConfiguration() { return { mouseLocation: { handles: { start: { highlight: true, active: true, }, }, }, minSpacing: 1, currentTool: null, dragColor: toolColors.getActiveColor(), hoverColor: toolColors.g...
[ "function", "getDefaultFreehandSculpterMouseToolConfiguration", "(", ")", "{", "return", "{", "mouseLocation", ":", "{", "handles", ":", "{", "start", ":", "{", "highlight", ":", "true", ",", "active", ":", "true", ",", "}", ",", "}", ",", "}", ",", "minSp...
Returns the default freehandSculpterMouseTool configuration. @returns {Object} The default configuration object.
[ "Returns", "the", "default", "freehandSculpterMouseTool", "configuration", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/tools/FreehandSculpterMouseTool.js#L1247-L1276
7,130
cornerstonejs/cornerstoneTools
src/store/setToolCursor.js
setToolCursor
function setToolCursor(element, svgCursor) { if (!globalConfiguration.state.showSVGCursors) { return; } // TODO: (state vs options) Exit if cursor wasn't updated // TODO: Exit if invalid options to create cursor // Note: Max size of an SVG cursor is 128x128, default is 32x32. const cursorBlob = svgCurs...
javascript
function setToolCursor(element, svgCursor) { if (!globalConfiguration.state.showSVGCursors) { return; } // TODO: (state vs options) Exit if cursor wasn't updated // TODO: Exit if invalid options to create cursor // Note: Max size of an SVG cursor is 128x128, default is 32x32. const cursorBlob = svgCurs...
[ "function", "setToolCursor", "(", "element", ",", "svgCursor", ")", "{", "if", "(", "!", "globalConfiguration", ".", "state", ".", "showSVGCursors", ")", "{", "return", ";", "}", "// TODO: (state vs options) Exit if cursor wasn't updated", "// TODO: Exit if invalid option...
Creates an SVG Cursor for the target element @param {MouseCursor} svgCursor - The cursor.
[ "Creates", "an", "SVG", "Cursor", "for", "the", "target", "element" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/setToolCursor.js#L12-L27
7,131
cornerstonejs/cornerstoneTools
src/tools/annotation/EllipticalRoiTool.js
_getEllipseImageCoordinates
function _getEllipseImageCoordinates(startHandle, endHandle) { return { left: Math.round(Math.min(startHandle.x, endHandle.x)), top: Math.round(Math.min(startHandle.y, endHandle.y)), width: Math.round(Math.abs(startHandle.x - endHandle.x)), height: Math.round(Math.abs(startHandle.y - endHandle.y)), ...
javascript
function _getEllipseImageCoordinates(startHandle, endHandle) { return { left: Math.round(Math.min(startHandle.x, endHandle.x)), top: Math.round(Math.min(startHandle.y, endHandle.y)), width: Math.round(Math.abs(startHandle.x - endHandle.x)), height: Math.round(Math.abs(startHandle.y - endHandle.y)), ...
[ "function", "_getEllipseImageCoordinates", "(", "startHandle", ",", "endHandle", ")", "{", "return", "{", "left", ":", "Math", ".", "round", "(", "Math", ".", "min", "(", "startHandle", ".", "x", ",", "endHandle", ".", "x", ")", ")", ",", "top", ":", "...
Retrieve the bounds of the ellipse in image coordinates @param {*} startHandle @param {*} endHandle @returns {{ left: number, top: number, width: number, height: number }}
[ "Retrieve", "the", "bounds", "of", "the", "ellipse", "in", "image", "coordinates" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/tools/annotation/EllipticalRoiTool.js#L498-L505
7,132
cornerstonejs/cornerstoneTools
src/store/internals/addEnabledElement.js
function(enabledElement) { store.state.enabledElements.push(enabledElement); if (store.modules) { _initModulesOnElement(enabledElement); } _addGlobalToolsToElement(enabledElement); _repeatGlobalToolHistory(enabledElement); }
javascript
function(enabledElement) { store.state.enabledElements.push(enabledElement); if (store.modules) { _initModulesOnElement(enabledElement); } _addGlobalToolsToElement(enabledElement); _repeatGlobalToolHistory(enabledElement); }
[ "function", "(", "enabledElement", ")", "{", "store", ".", "state", ".", "enabledElements", ".", "push", "(", "enabledElement", ")", ";", "if", "(", "store", ".", "modules", ")", "{", "_initModulesOnElement", "(", "enabledElement", ")", ";", "}", "_addGlobal...
Adds the enabled element to the store. @private @method @param {HTMLElement} enabledElement @returns {void}
[ "Adds", "the", "enabled", "element", "to", "the", "store", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/internals/addEnabledElement.js#L83-L90
7,133
cornerstonejs/cornerstoneTools
src/store/internals/addEnabledElement.js
_initModulesOnElement
function _initModulesOnElement(enabledElement) { const modules = store.modules; Object.keys(modules).forEach(function(key) { if (typeof modules[key].enabledElementCallback === 'function') { modules[key].enabledElementCallback(enabledElement); } }); }
javascript
function _initModulesOnElement(enabledElement) { const modules = store.modules; Object.keys(modules).forEach(function(key) { if (typeof modules[key].enabledElementCallback === 'function') { modules[key].enabledElementCallback(enabledElement); } }); }
[ "function", "_initModulesOnElement", "(", "enabledElement", ")", "{", "const", "modules", "=", "store", ".", "modules", ";", "Object", ".", "keys", "(", "modules", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "typeof", "modules", ...
Iterate over our store's modules. If the module has an `enabledElementCallback` call it and pass it a reference to our enabled element. @private @method @param {Object} enabledElement @returns {void}
[ "Iterate", "over", "our", "store", "s", "modules", ".", "If", "the", "module", "has", "an", "enabledElementCallback", "call", "it", "and", "pass", "it", "a", "reference", "to", "our", "enabled", "element", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/internals/addEnabledElement.js#L100-L108
7,134
cornerstonejs/cornerstoneTools
src/store/internals/addEnabledElement.js
_addGlobalToolsToElement
function _addGlobalToolsToElement(enabledElement) { if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) { return; } Object.keys(store.state.globalTools).forEach(function(key) { const { tool, configuration } = store.state.globalTools[key]; addToolForElement(enabledElement, tool, confi...
javascript
function _addGlobalToolsToElement(enabledElement) { if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) { return; } Object.keys(store.state.globalTools).forEach(function(key) { const { tool, configuration } = store.state.globalTools[key]; addToolForElement(enabledElement, tool, confi...
[ "function", "_addGlobalToolsToElement", "(", "enabledElement", ")", "{", "if", "(", "!", "store", ".", "modules", ".", "globalConfiguration", ".", "state", ".", "globalToolSyncEnabled", ")", "{", "return", ";", "}", "Object", ".", "keys", "(", "store", ".", ...
Iterate over our stores globalTools adding each one to `enabledElement` @private @method @param {HTMLElement} enabledElement @returns {void}
[ "Iterate", "over", "our", "stores", "globalTools", "adding", "each", "one", "to", "enabledElement" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/internals/addEnabledElement.js#L117-L127
7,135
cornerstonejs/cornerstoneTools
src/store/internals/addEnabledElement.js
_repeatGlobalToolHistory
function _repeatGlobalToolHistory(enabledElement) { if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) { return; } const setToolModeFns = { active: setToolActiveForElement, passive: setToolPassiveForElement, enabled: setToolEnabledForElement, disabled: setToolDisabledForEleme...
javascript
function _repeatGlobalToolHistory(enabledElement) { if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) { return; } const setToolModeFns = { active: setToolActiveForElement, passive: setToolPassiveForElement, enabled: setToolEnabledForElement, disabled: setToolDisabledForEleme...
[ "function", "_repeatGlobalToolHistory", "(", "enabledElement", ")", "{", "if", "(", "!", "store", ".", "modules", ".", "globalConfiguration", ".", "state", ".", "globalToolSyncEnabled", ")", "{", "return", ";", "}", "const", "setToolModeFns", "=", "{", "active",...
Iterate over the globalToolChangeHistory and apply each `historyEvent` to the supplied `enabledElement`. @private @method @param {HTMLElement} enabledElement @returns {void}
[ "Iterate", "over", "the", "globalToolChangeHistory", "and", "apply", "each", "historyEvent", "to", "the", "supplied", "enabledElement", "." ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/store/internals/addEnabledElement.js#L137-L155
7,136
cornerstonejs/cornerstoneTools
src/synchronization/Synchronizer.js
fireEvent
function fireEvent(sourceElement, eventData) { const isDisabled = !that.enabled; const noElements = !sourceElements.length || !targetElements.length; if (isDisabled || noElements) { return; } ignoreFiredEvents = true; targetElements.forEach(function(targetElement) { const targetInd...
javascript
function fireEvent(sourceElement, eventData) { const isDisabled = !that.enabled; const noElements = !sourceElements.length || !targetElements.length; if (isDisabled || noElements) { return; } ignoreFiredEvents = true; targetElements.forEach(function(targetElement) { const targetInd...
[ "function", "fireEvent", "(", "sourceElement", ",", "eventData", ")", "{", "const", "isDisabled", "=", "!", "that", ".", "enabled", ";", "const", "noElements", "=", "!", "sourceElements", ".", "length", "||", "!", "targetElements", ".", "length", ";", "if", ...
Gather necessary event data and call synchronization handler @private @param {HTMLElement} sourceElement - The source element for the event @param {Object} eventData - The data object for the source event @returns {void}
[ "Gather", "necessary", "event", "data", "and", "call", "synchronization", "handler" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/synchronization/Synchronizer.js#L159-L202
7,137
cornerstonejs/cornerstoneTools
src/synchronization/Synchronizer.js
onEvent
function onEvent(e) { const eventData = e.detail; if (ignoreFiredEvents === true) { return; } fireEvent(e.currentTarget, eventData); }
javascript
function onEvent(e) { const eventData = e.detail; if (ignoreFiredEvents === true) { return; } fireEvent(e.currentTarget, eventData); }
[ "function", "onEvent", "(", "e", ")", "{", "const", "eventData", "=", "e", ".", "detail", ";", "if", "(", "ignoreFiredEvents", "===", "true", ")", "{", "return", ";", "}", "fireEvent", "(", "e", ".", "currentTarget", ",", "eventData", ")", ";", "}" ]
Call fireEvent if not ignoring events, and pass along event data @private @param {Event} e - The source event object @returns {void}
[ "Call", "fireEvent", "if", "not", "ignoring", "events", "and", "pass", "along", "event", "data" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/synchronization/Synchronizer.js#L211-L219
7,138
cornerstonejs/cornerstoneTools
src/synchronization/Synchronizer.js
disableHandler
function disableHandler(e) { const element = e.detail.element; that.remove(element); clearToolOptionsByElement(element); }
javascript
function disableHandler(e) { const element = e.detail.element; that.remove(element); clearToolOptionsByElement(element); }
[ "function", "disableHandler", "(", "e", ")", "{", "const", "element", "=", "e", ".", "detail", ".", "element", ";", "that", ".", "remove", "(", "element", ")", ";", "clearToolOptionsByElement", "(", "element", ")", ";", "}" ]
Remove an element from the synchronizer based on an event from that element @private @param {Event} e - The event whose element will be removed @returns {void}
[ "Remove", "an", "element", "from", "the", "synchronizer", "based", "on", "an", "event", "from", "that", "element" ]
8480029f4f42da521d5d5fb9351afee98d84d58e
https://github.com/cornerstonejs/cornerstoneTools/blob/8480029f4f42da521d5d5fb9351afee98d84d58e/src/synchronization/Synchronizer.js#L404-L409
7,139
thheller/shadow-cljs
src/main/shadow/cljs/ui/bundle_renderer.js
createVisualization
function createVisualization(data) { var json = buildHierarchy(data); // Basic setup of page elements. initializeBreadcrumbTrail(); // Bounding circle underneath the sunburst, to make it easier to detect // when the mouse leaves the parent g. vis.append("svg:circle") .attr("r", radius) .style(...
javascript
function createVisualization(data) { var json = buildHierarchy(data); // Basic setup of page elements. initializeBreadcrumbTrail(); // Bounding circle underneath the sunburst, to make it easier to detect // when the mouse leaves the parent g. vis.append("svg:circle") .attr("r", radius) .style(...
[ "function", "createVisualization", "(", "data", ")", "{", "var", "json", "=", "buildHierarchy", "(", "data", ")", ";", "// Basic setup of page elements.", "initializeBreadcrumbTrail", "(", ")", ";", "// Bounding circle underneath the sunburst, to make it easier to detect", "/...
Main function to draw and set up the visualization, once we have the data.
[ "Main", "function", "to", "draw", "and", "set", "up", "the", "visualization", "once", "we", "have", "the", "data", "." ]
4c1718ebe721840812f2b406bd428225d6bfb8a5
https://github.com/thheller/shadow-cljs/blob/4c1718ebe721840812f2b406bd428225d6bfb8a5/src/main/shadow/cljs/ui/bundle_renderer.js#L45-L78
7,140
thheller/shadow-cljs
src/main/shadow/cljs/ui/bundle_renderer.js
mouseover
function mouseover(d) { var percentage = (100 * d.value / totalSize).toPrecision(3); var percentageString = percentage + "%"; if (percentage < 0.1) { percentageString = "< 0.1%"; } d3.select("#percentage") .text(percentageString); d3.select("#explanation") .style("visibility", ""); var...
javascript
function mouseover(d) { var percentage = (100 * d.value / totalSize).toPrecision(3); var percentageString = percentage + "%"; if (percentage < 0.1) { percentageString = "< 0.1%"; } d3.select("#percentage") .text(percentageString); d3.select("#explanation") .style("visibility", ""); var...
[ "function", "mouseover", "(", "d", ")", "{", "var", "percentage", "=", "(", "100", "*", "d", ".", "value", "/", "totalSize", ")", ".", "toPrecision", "(", "3", ")", ";", "var", "percentageString", "=", "percentage", "+", "\"%\"", ";", "if", "(", "per...
Fade all but the current sequence, and show it in the breadcrumb trail.
[ "Fade", "all", "but", "the", "current", "sequence", "and", "show", "it", "in", "the", "breadcrumb", "trail", "." ]
4c1718ebe721840812f2b406bd428225d6bfb8a5
https://github.com/thheller/shadow-cljs/blob/4c1718ebe721840812f2b406bd428225d6bfb8a5/src/main/shadow/cljs/ui/bundle_renderer.js#L83-L110
7,141
thheller/shadow-cljs
src/main/shadow/cljs/ui/bundle_renderer.js
mouseleave
function mouseleave(d) { // Hide the breadcrumb trail d3.select("#trail") .style("visibility", "hidden"); // Deactivate all segments during transition. d3.selectAll("path").on("mouseover", null); // Transition each segment to full opacity and then reactivate it. d3.selectAll("path") .transiti...
javascript
function mouseleave(d) { // Hide the breadcrumb trail d3.select("#trail") .style("visibility", "hidden"); // Deactivate all segments during transition. d3.selectAll("path").on("mouseover", null); // Transition each segment to full opacity and then reactivate it. d3.selectAll("path") .transiti...
[ "function", "mouseleave", "(", "d", ")", "{", "// Hide the breadcrumb trail", "d3", ".", "select", "(", "\"#trail\"", ")", ".", "style", "(", "\"visibility\"", ",", "\"hidden\"", ")", ";", "// Deactivate all segments during transition.", "d3", ".", "selectAll", "(",...
Restore everything to full opacity when moving off the visualization.
[ "Restore", "everything", "to", "full", "opacity", "when", "moving", "off", "the", "visualization", "." ]
4c1718ebe721840812f2b406bd428225d6bfb8a5
https://github.com/thheller/shadow-cljs/blob/4c1718ebe721840812f2b406bd428225d6bfb8a5/src/main/shadow/cljs/ui/bundle_renderer.js#L113-L133
7,142
thheller/shadow-cljs
src/main/shadow/cljs/ui/bundle_renderer.js
getAncestors
function getAncestors(node) { var path = []; var current = node; while (current.parent) { path.unshift(current); current = current.parent; } return path; }
javascript
function getAncestors(node) { var path = []; var current = node; while (current.parent) { path.unshift(current); current = current.parent; } return path; }
[ "function", "getAncestors", "(", "node", ")", "{", "var", "path", "=", "[", "]", ";", "var", "current", "=", "node", ";", "while", "(", "current", ".", "parent", ")", "{", "path", ".", "unshift", "(", "current", ")", ";", "current", "=", "current", ...
Given a node in a partition layout, return an array of all of its ancestor nodes, highest first, but excluding the root.
[ "Given", "a", "node", "in", "a", "partition", "layout", "return", "an", "array", "of", "all", "of", "its", "ancestor", "nodes", "highest", "first", "but", "excluding", "the", "root", "." ]
4c1718ebe721840812f2b406bd428225d6bfb8a5
https://github.com/thheller/shadow-cljs/blob/4c1718ebe721840812f2b406bd428225d6bfb8a5/src/main/shadow/cljs/ui/bundle_renderer.js#L137-L145
7,143
thheller/shadow-cljs
src/main/shadow/cljs/ui/bundle_renderer.js
breadcrumbPoints
function breadcrumbPoints(d, i) { var points = []; points.push("0,0"); points.push(b.w + ",0"); points.push(b.w + b.t + "," + (b.h / 2)); points.push(b.w + "," + b.h); points.push("0," + b.h); if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex. points.push(b.t + "," + (b.h / 2)); } retu...
javascript
function breadcrumbPoints(d, i) { var points = []; points.push("0,0"); points.push(b.w + ",0"); points.push(b.w + b.t + "," + (b.h / 2)); points.push(b.w + "," + b.h); points.push("0," + b.h); if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex. points.push(b.t + "," + (b.h / 2)); } retu...
[ "function", "breadcrumbPoints", "(", "d", ",", "i", ")", "{", "var", "points", "=", "[", "]", ";", "points", ".", "push", "(", "\"0,0\"", ")", ";", "points", ".", "push", "(", "b", ".", "w", "+", "\",0\"", ")", ";", "points", ".", "push", "(", ...
Generate a string that describes the points of a breadcrumb polygon.
[ "Generate", "a", "string", "that", "describes", "the", "points", "of", "a", "breadcrumb", "polygon", "." ]
4c1718ebe721840812f2b406bd428225d6bfb8a5
https://github.com/thheller/shadow-cljs/blob/4c1718ebe721840812f2b406bd428225d6bfb8a5/src/main/shadow/cljs/ui/bundle_renderer.js#L160-L171
7,144
thheller/shadow-cljs
src/main/shadow/cljs/ui/bundle_renderer.js
updateBreadcrumbs
function updateBreadcrumbs(nodeArray, percentageString) { // Data join; key function combines name and depth (= position in sequence). var g = d3.select("#trail") .selectAll("g") .data(nodeArray, function(d) { return d.name + d.depth; }); // Add breadcrumb and label for entering nodes. var enterin...
javascript
function updateBreadcrumbs(nodeArray, percentageString) { // Data join; key function combines name and depth (= position in sequence). var g = d3.select("#trail") .selectAll("g") .data(nodeArray, function(d) { return d.name + d.depth; }); // Add breadcrumb and label for entering nodes. var enterin...
[ "function", "updateBreadcrumbs", "(", "nodeArray", ",", "percentageString", ")", "{", "// Data join; key function combines name and depth (= position in sequence).", "var", "g", "=", "d3", ".", "select", "(", "\"#trail\"", ")", ".", "selectAll", "(", "\"g\"", ")", ".", ...
Update the breadcrumb trail to show the current sequence and percentage.
[ "Update", "the", "breadcrumb", "trail", "to", "show", "the", "current", "sequence", "and", "percentage", "." ]
4c1718ebe721840812f2b406bd428225d6bfb8a5
https://github.com/thheller/shadow-cljs/blob/4c1718ebe721840812f2b406bd428225d6bfb8a5/src/main/shadow/cljs/ui/bundle_renderer.js#L174-L215
7,145
thheller/shadow-cljs
src/main/shadow/cljs/ui/bundle_renderer.js
buildHierarchy
function buildHierarchy(csv) { var root = {"name": "root", "children": []}; for (var i = 0; i < csv.length; i++) { var sequence = csv[i][0]; var size = +csv[i][1]; if (isNaN(size)) { // e.g. if this is a header row continue; } var parts = sequence.split("/"); var currentNode = root; ...
javascript
function buildHierarchy(csv) { var root = {"name": "root", "children": []}; for (var i = 0; i < csv.length; i++) { var sequence = csv[i][0]; var size = +csv[i][1]; if (isNaN(size)) { // e.g. if this is a header row continue; } var parts = sequence.split("/"); var currentNode = root; ...
[ "function", "buildHierarchy", "(", "csv", ")", "{", "var", "root", "=", "{", "\"name\"", ":", "\"root\"", ",", "\"children\"", ":", "[", "]", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "csv", ".", "length", ";", "i", "++", ")", ...
Take a 2-column CSV and transform it into a hierarchical structure suitable for a partition layout. The first column is a sequence of step names, from root to leaf, separated by hyphens. The second column is a count of how often that sequence occurred.
[ "Take", "a", "2", "-", "column", "CSV", "and", "transform", "it", "into", "a", "hierarchical", "structure", "suitable", "for", "a", "partition", "layout", ".", "The", "first", "column", "is", "a", "sequence", "of", "step", "names", "from", "root", "to", ...
4c1718ebe721840812f2b406bd428225d6bfb8a5
https://github.com/thheller/shadow-cljs/blob/4c1718ebe721840812f2b406bd428225d6bfb8a5/src/main/shadow/cljs/ui/bundle_renderer.js#L221-L259
7,146
APIDevTools/swagger-express-middleware
lib/mock/query-resource.js
queryResource
function queryResource (req, res, next, dataStore) { let resource = new Resource(req.path); dataStore.get(resource, (err, result) => { if (err) { next(err); } else if (!result) { let defaultValue = getDefaultValue(res); if (defaultValue === undefined) { util.debug("ERROR! 404...
javascript
function queryResource (req, res, next, dataStore) { let resource = new Resource(req.path); dataStore.get(resource, (err, result) => { if (err) { next(err); } else if (!result) { let defaultValue = getDefaultValue(res); if (defaultValue === undefined) { util.debug("ERROR! 404...
[ "function", "queryResource", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", "{", "let", "resource", "=", "new", "Resource", "(", "req", ".", "path", ")", ";", "dataStore", ".", "get", "(", "resource", ",", "(", "err", ",", "result", ")",...
Returns the REST resource at the URL. If there's no resource that matches the URL, then a 404 error is returned. @param {Request} req @param {Response} res @param {function} next @param {DataStore} dataStore
[ "Returns", "the", "REST", "resource", "at", "the", "URL", ".", "If", "there", "s", "no", "resource", "that", "matches", "the", "URL", "then", "a", "404", "error", "is", "returned", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/query-resource.js#L22-L56
7,147
APIDevTools/swagger-express-middleware
lib/index.js
createMiddleware
function createMiddleware (swagger, router, callback) { // Shift args if needed if (util.isExpressRouter(swagger)) { router = swagger; swagger = callback = undefined; } else if (!util.isExpressRouter(router)) { callback = router; router = undefined; } let middleware = new module.exports.Mid...
javascript
function createMiddleware (swagger, router, callback) { // Shift args if needed if (util.isExpressRouter(swagger)) { router = swagger; swagger = callback = undefined; } else if (!util.isExpressRouter(router)) { callback = router; router = undefined; } let middleware = new module.exports.Mid...
[ "function", "createMiddleware", "(", "swagger", ",", "router", ",", "callback", ")", "{", "// Shift args if needed", "if", "(", "util", ".", "isExpressRouter", "(", "swagger", ")", ")", "{", "router", "=", "swagger", ";", "swagger", "=", "callback", "=", "un...
Creates Express middleware for the given Swagger API. @param {string|object} [swagger] - The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format. Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object). @param {express#Router} ...
[ "Creates", "Express", "middleware", "for", "the", "given", "Swagger", "API", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/index.js#L30-L48
7,148
APIDevTools/swagger-express-middleware
lib/mock/edit-resource.js
mergeResource
function mergeResource (req, res, next, dataStore) { let resource = createResource(req); // Save/Update the resource util.debug("Saving data at %s", resource.toString()); dataStore.save(resource, sendResponse(req, res, next, dataStore)); }
javascript
function mergeResource (req, res, next, dataStore) { let resource = createResource(req); // Save/Update the resource util.debug("Saving data at %s", resource.toString()); dataStore.save(resource, sendResponse(req, res, next, dataStore)); }
[ "function", "mergeResource", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", "{", "let", "resource", "=", "createResource", "(", "req", ")", ";", "// Save/Update the resource", "util", ".", "debug", "(", "\"Saving data at %s\"", ",", "resource", "....
Creates or updates the REST resource at the URL. If the resource already exists, then the new data is merged with the existing data. To completely overwrite the existing data, use PUT instead of POST or PATCH. @param {Request} req @param {Response} res @param {function} next @param {DataStore} dataStore
[ "Creates", "or", "updates", "the", "REST", "resource", "at", "the", "URL", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/edit-resource.js#L25-L31
7,149
APIDevTools/swagger-express-middleware
lib/mock/edit-resource.js
overwriteResource
function overwriteResource (req, res, next, dataStore) { let resource = createResource(req); // Delete the existing resource, if any dataStore.delete(resource, (err) => { if (err) { next(err); } else { // Save the new resource util.debug("Saving data at %s", resource.toString()); ...
javascript
function overwriteResource (req, res, next, dataStore) { let resource = createResource(req); // Delete the existing resource, if any dataStore.delete(resource, (err) => { if (err) { next(err); } else { // Save the new resource util.debug("Saving data at %s", resource.toString()); ...
[ "function", "overwriteResource", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", "{", "let", "resource", "=", "createResource", "(", "req", ")", ";", "// Delete the existing resource, if any", "dataStore", ".", "delete", "(", "resource", ",", "(", ...
Creates or overwrites the REST resource at the URL. If the resource already exists, it is overwritten. To merge with the existing data, use POST or PATCH instead of PUT. @param {Request} req @param {Response} res @param {function} next @param {DataStore} dataStore
[ "Creates", "or", "overwrites", "the", "REST", "resource", "at", "the", "URL", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/edit-resource.js#L44-L58
7,150
APIDevTools/swagger-express-middleware
lib/mock/edit-resource.js
deleteResource
function deleteResource (req, res, next, dataStore) { // jshint ignore:line let resource = createResource(req); // Delete the resource dataStore.delete(resource, (err, deletedResource) => { // Respond with the deleted resource, if possible; otherwise, use the empty resource we just created. sendResponse(...
javascript
function deleteResource (req, res, next, dataStore) { // jshint ignore:line let resource = createResource(req); // Delete the resource dataStore.delete(resource, (err, deletedResource) => { // Respond with the deleted resource, if possible; otherwise, use the empty resource we just created. sendResponse(...
[ "function", "deleteResource", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", "{", "// jshint ignore:line", "let", "resource", "=", "createResource", "(", "req", ")", ";", "// Delete the resource", "dataStore", ".", "delete", "(", "resource", ",", ...
Deletes the REST resource at the URL. If the resource does not exist, then nothing happens. No error is thrown. @param {Request} req @param {Response} res @param {function} next @param {DataStore} dataStore
[ "Deletes", "the", "REST", "resource", "at", "the", "URL", ".", "If", "the", "resource", "does", "not", "exist", "then", "nothing", "happens", ".", "No", "error", "is", "thrown", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/edit-resource.js#L69-L77
7,151
APIDevTools/swagger-express-middleware
lib/middleware.js
Middleware
function Middleware (sharedRouter) { sharedRouter = util.isExpressRouter(sharedRouter) ? sharedRouter : undefined; let self = this; let context = new MiddlewareContext(sharedRouter); /** * Initializes the middleware with the given Swagger API. * This method can be called again to re-initialize with a ne...
javascript
function Middleware (sharedRouter) { sharedRouter = util.isExpressRouter(sharedRouter) ? sharedRouter : undefined; let self = this; let context = new MiddlewareContext(sharedRouter); /** * Initializes the middleware with the given Swagger API. * This method can be called again to re-initialize with a ne...
[ "function", "Middleware", "(", "sharedRouter", ")", "{", "sharedRouter", "=", "util", ".", "isExpressRouter", "(", "sharedRouter", ")", "?", "sharedRouter", ":", "undefined", ";", "let", "self", "=", "this", ";", "let", "context", "=", "new", "MiddlewareContex...
Express middleware for the given Swagger API. @param {express#Router} [sharedRouter] - An Express Application or Router. If provided, this will be used to determine routing settings (case sensitivity, strictness), and to register path-param middleware via {@link Router#param} (see http://expressjs.com/4x/api.html...
[ "Express", "middleware", "for", "the", "given", "Swagger", "API", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/middleware.js#L29-L180
7,152
APIDevTools/swagger-express-middleware
lib/data-store/resource.js
Resource
function Resource (path, name, data) { switch (arguments.length) { case 0: this.collection = ""; this.name = "/"; this.data = undefined; break; case 1: this.collection = getCollectionFromPath(path); this.name = getNameFromPath(path); this.data = undefined; break...
javascript
function Resource (path, name, data) { switch (arguments.length) { case 0: this.collection = ""; this.name = "/"; this.data = undefined; break; case 1: this.collection = getCollectionFromPath(path); this.name = getNameFromPath(path); this.data = undefined; break...
[ "function", "Resource", "(", "path", ",", "name", ",", "data", ")", "{", "switch", "(", "arguments", ".", "length", ")", "{", "case", "0", ":", "this", ".", "collection", "=", "\"\"", ";", "this", ".", "name", "=", "\"/\"", ";", "this", ".", "data"...
Represents a single REST resource, such as a web page, a file, a piece of JSON data, etc. Each Resource is uniquely identifiable by its collection and its name. Examples: /static/pages/index.html - Collection: /static/pages - Name: /index.html /restaurants/washington/seattle/ - Collection: /restaurants/washington - N...
[ "Represents", "a", "single", "REST", "resource", "such", "as", "a", "web", "page", "a", "file", "a", "piece", "of", "JSON", "data", "etc", ".", "Each", "Resource", "is", "uniquely", "identifiable", "by", "its", "collection", "and", "its", "name", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/resource.js#L35-L60
7,153
APIDevTools/swagger-express-middleware
lib/data-store/resource.js
getCollectionFromPath
function getCollectionFromPath (path) { path = _(path).toString(); let lastSlash = path.substring(0, path.length - 1).lastIndexOf("/"); if (lastSlash === -1) { return ""; } else { return normalizeCollection(path.substring(0, lastSlash)); } }
javascript
function getCollectionFromPath (path) { path = _(path).toString(); let lastSlash = path.substring(0, path.length - 1).lastIndexOf("/"); if (lastSlash === -1) { return ""; } else { return normalizeCollection(path.substring(0, lastSlash)); } }
[ "function", "getCollectionFromPath", "(", "path", ")", "{", "path", "=", "_", "(", "path", ")", ".", "toString", "(", ")", ";", "let", "lastSlash", "=", "path", ".", "substring", "(", "0", ",", "path", ".", "length", "-", "1", ")", ".", "lastIndexOf"...
Returns the normalized collection path from the given full resource path. @param {string} path - The full resource path (e.g. "/restaurants/washington/seattle/joes-diner") @returns {string} - The normalized collection path (e.g. "/restaurants/washington/seattle")
[ "Returns", "the", "normalized", "collection", "path", "from", "the", "given", "full", "resource", "path", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/resource.js#L173-L182
7,154
APIDevTools/swagger-express-middleware
lib/data-store/resource.js
getNameFromPath
function getNameFromPath (path) { path = _(path).toString(); let lastSlash = path.substring(0, path.length - 1).lastIndexOf("/"); if (lastSlash === -1) { return normalizeName(path); } else { return normalizeName(path.substring(lastSlash)); } }
javascript
function getNameFromPath (path) { path = _(path).toString(); let lastSlash = path.substring(0, path.length - 1).lastIndexOf("/"); if (lastSlash === -1) { return normalizeName(path); } else { return normalizeName(path.substring(lastSlash)); } }
[ "function", "getNameFromPath", "(", "path", ")", "{", "path", "=", "_", "(", "path", ")", ".", "toString", "(", ")", ";", "let", "lastSlash", "=", "path", ".", "substring", "(", "0", ",", "path", ".", "length", "-", "1", ")", ".", "lastIndexOf", "(...
Returns the normalized resource name from the given full resource path. @param {string} path - The full resource path (e.g. "/restaurants/washington/seattle/joes-diner") @returns {string} - The normalized resource name (e.g. "/joes-diner")
[ "Returns", "the", "normalized", "resource", "name", "from", "the", "given", "full", "resource", "path", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/resource.js#L190-L199
7,155
APIDevTools/swagger-express-middleware
lib/data-store/resource.js
normalizeCollection
function normalizeCollection (collection) { // Normalize the root path as an empty string collection = _(collection).toString(); if (_.isEmpty(collection) || collection === "/" || collection === "//") { return ""; } // Add a leading slash if (!_.startsWith(collection, "/")) { collection = "/" + col...
javascript
function normalizeCollection (collection) { // Normalize the root path as an empty string collection = _(collection).toString(); if (_.isEmpty(collection) || collection === "/" || collection === "//") { return ""; } // Add a leading slash if (!_.startsWith(collection, "/")) { collection = "/" + col...
[ "function", "normalizeCollection", "(", "collection", ")", "{", "// Normalize the root path as an empty string", "collection", "=", "_", "(", "collection", ")", ".", "toString", "(", ")", ";", "if", "(", "_", ".", "isEmpty", "(", "collection", ")", "||", "collec...
Normalizes collection paths. Examples: / => (empty string) /users => /users /users/jdoe/ => /users/jdoe @param {string} collection @returns {string}
[ "Normalizes", "collection", "paths", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/resource.js#L212-L230
7,156
APIDevTools/swagger-express-middleware
lib/data-store/resource.js
normalizeName
function normalizeName (name) { // Normalize directories as a single slash name = _(name).toString(); if (_.isEmpty(name) || name === "/" || name === "//") { return "/"; } // Add a leading slash if (!_.startsWith(name, "/")) { name = "/" + name; } // Don't allow slashes in the middle if (_.i...
javascript
function normalizeName (name) { // Normalize directories as a single slash name = _(name).toString(); if (_.isEmpty(name) || name === "/" || name === "//") { return "/"; } // Add a leading slash if (!_.startsWith(name, "/")) { name = "/" + name; } // Don't allow slashes in the middle if (_.i...
[ "function", "normalizeName", "(", "name", ")", "{", "// Normalize directories as a single slash", "name", "=", "_", "(", "name", ")", ".", "toString", "(", ")", ";", "if", "(", "_", ".", "isEmpty", "(", "name", ")", "||", "name", "===", "\"/\"", "||", "n...
Normalizes resource names. Examples: / => / /users => /users users/ => /users/ /users/jdoe => ERROR! Slashes aren't allowed in the middle @param {string} name @returns {string}
[ "Normalizes", "resource", "names", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/resource.js#L244-L262
7,157
APIDevTools/swagger-express-middleware
lib/data-store/index.js
save
function save (dataStore, collectionName, resources, callback) { // Open the data store dataStore.__openDataStore(collectionName, (err, existingResources) => { if (err) { return callback(err); } resources.forEach((resource) => { // Set the timestamp properties let now = Date.now(); ...
javascript
function save (dataStore, collectionName, resources, callback) { // Open the data store dataStore.__openDataStore(collectionName, (err, existingResources) => { if (err) { return callback(err); } resources.forEach((resource) => { // Set the timestamp properties let now = Date.now(); ...
[ "function", "save", "(", "dataStore", ",", "collectionName", ",", "resources", ",", "callback", ")", "{", "// Open the data store", "dataStore", ".", "__openDataStore", "(", "collectionName", ",", "(", "err", ",", "existingResources", ")", "=>", "{", "if", "(", ...
Saves the given resources to the data store. If any of the resources already exist, the new data is merged with the existing data. @param {DataStore} dataStore - The DataStore to operate on @param {string} collectionName - The collection that all the resources belong to @param {Resource[]} res...
[ "Saves", "the", "given", "resources", "to", "the", "data", "store", ".", "If", "any", "of", "the", "resources", "already", "exist", "the", "new", "data", "is", "merged", "with", "the", "existing", "data", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/index.js#L196-L229
7,158
APIDevTools/swagger-express-middleware
lib/data-store/index.js
remove
function remove (dataStore, collectionName, resources, callback) { // Open the data store dataStore.__openDataStore(collectionName, (err, existingResources) => { if (err) { return callback(err); } // Remove the resources from the existing resources let removedResources = []; resources.for...
javascript
function remove (dataStore, collectionName, resources, callback) { // Open the data store dataStore.__openDataStore(collectionName, (err, existingResources) => { if (err) { return callback(err); } // Remove the resources from the existing resources let removedResources = []; resources.for...
[ "function", "remove", "(", "dataStore", ",", "collectionName", ",", "resources", ",", "callback", ")", "{", "// Open the data store", "dataStore", ".", "__openDataStore", "(", "collectionName", ",", "(", "err", ",", "existingResources", ")", "=>", "{", "if", "("...
Removes the given resource from the data store. @param {DataStore} dataStore - The DataStore to operate on @param {string} collectionName - The collection that all the resources belong to @param {Resource[]} resources - The Resources to be removed @param {function} callback -...
[ "Removes", "the", "given", "resource", "from", "the", "data", "store", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/index.js#L239-L268
7,159
APIDevTools/swagger-express-middleware
lib/data-store/index.js
openCollection
function openCollection (dataStore, collection, callback) { if (_.isString(collection)) { collection = new Resource(collection, "", ""); } else if (!(collection instanceof Resource)) { throw ono("Expected a string or Resource object. Got a %s instead.", typeof (collection)); } // Normalize the collec...
javascript
function openCollection (dataStore, collection, callback) { if (_.isString(collection)) { collection = new Resource(collection, "", ""); } else if (!(collection instanceof Resource)) { throw ono("Expected a string or Resource object. Got a %s instead.", typeof (collection)); } // Normalize the collec...
[ "function", "openCollection", "(", "dataStore", ",", "collection", ",", "callback", ")", "{", "if", "(", "_", ".", "isString", "(", "collection", ")", ")", "{", "collection", "=", "new", "Resource", "(", "collection", ",", "\"\"", ",", "\"\"", ")", ";", ...
Opens the given collection. @param {DataStore} dataStore - The DataStore to operate on @param {string|Resource} collection - The collection path or a Resource object @param {function} callback - Called with Error, collection Resource, and Resource array
[ "Opens", "the", "given", "collection", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/index.js#L277-L292
7,160
APIDevTools/swagger-express-middleware
lib/data-store/index.js
doCallback
function doCallback (callback, err, arg) { if (_.isFunction(callback)) { callback(err, arg); } }
javascript
function doCallback (callback, err, arg) { if (_.isFunction(callback)) { callback(err, arg); } }
[ "function", "doCallback", "(", "callback", ",", "err", ",", "arg", ")", "{", "if", "(", "_", ".", "isFunction", "(", "callback", ")", ")", "{", "callback", "(", "err", ",", "arg", ")", ";", "}", "}" ]
Calls the given callback with the given arguments, if the callback is defined. @param {function|*} callback @param {Error|null} err @param {*} arg
[ "Calls", "the", "given", "callback", "with", "the", "given", "arguments", "if", "the", "callback", "is", "defined", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/index.js#L301-L305
7,161
APIDevTools/swagger-express-middleware
lib/param-parser.js
parseSimpleParams
function parseSimpleParams (req, res, next) { let params = getParams(req); if (params.length > 0) { util.debug("Parsing %d request parameters...", params.length); params.forEach((param) => { // Get the raw value of the parameter switch (param.in) { case "query": util.debug(' ...
javascript
function parseSimpleParams (req, res, next) { let params = getParams(req); if (params.length > 0) { util.debug("Parsing %d request parameters...", params.length); params.forEach((param) => { // Get the raw value of the parameter switch (param.in) { case "query": util.debug(' ...
[ "function", "parseSimpleParams", "(", "req", ",", "res", ",", "next", ")", "{", "let", "params", "=", "getParams", "(", "req", ")", ";", "if", "(", "params", ".", "length", ">", "0", ")", "{", "util", ".", "debug", "(", "\"Parsing %d request parameters.....
Parses all Swagger parameters in the query string and headers
[ "Parses", "all", "Swagger", "parameters", "in", "the", "query", "string", "and", "headers" ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/param-parser.js#L24-L47
7,162
APIDevTools/swagger-express-middleware
lib/param-parser.js
parseFormDataParams
function parseFormDataParams (req, res, next) { getParams(req).forEach((param) => { if (param.in === "formData") { util.debug(' Parsing the "%s" form-data parameter', param.name); if (param.type === "file") { // Validate the file (min/max size, etc.) req.files[param.name] = parsePa...
javascript
function parseFormDataParams (req, res, next) { getParams(req).forEach((param) => { if (param.in === "formData") { util.debug(' Parsing the "%s" form-data parameter', param.name); if (param.type === "file") { // Validate the file (min/max size, etc.) req.files[param.name] = parsePa...
[ "function", "parseFormDataParams", "(", "req", ",", "res", ",", "next", ")", "{", "getParams", "(", "req", ")", ".", "forEach", "(", "(", "param", ")", "=>", "{", "if", "(", "param", ".", "in", "===", "\"formData\"", ")", "{", "util", ".", "debug", ...
Parses all Swagger parameters in the form data.
[ "Parses", "all", "Swagger", "parameters", "in", "the", "form", "data", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/param-parser.js#L52-L69
7,163
APIDevTools/swagger-express-middleware
lib/param-parser.js
parseBodyParam
function parseBodyParam (req, res, next) { let params = getParams(req); params.some((param) => { if (param.in === "body") { util.debug(' Parsing the "%s" body parameter', param.name); if (_.isPlainObject(req.body) && _.isEmpty(req.body)) { if (param.type === "string" || (param.schema &&...
javascript
function parseBodyParam (req, res, next) { let params = getParams(req); params.some((param) => { if (param.in === "body") { util.debug(' Parsing the "%s" body parameter', param.name); if (_.isPlainObject(req.body) && _.isEmpty(req.body)) { if (param.type === "string" || (param.schema &&...
[ "function", "parseBodyParam", "(", "req", ",", "res", ",", "next", ")", "{", "let", "params", "=", "getParams", "(", "req", ")", ";", "params", ".", "some", "(", "(", "param", ")", "=>", "{", "if", "(", "param", ".", "in", "===", "\"body\"", ")", ...
Parses the Swagger "body" parameter.
[ "Parses", "the", "Swagger", "body", "parameter", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/param-parser.js#L74-L112
7,164
APIDevTools/swagger-express-middleware
lib/param-parser.js
parseParameter
function parseParameter (param, value, schema) { if (value === undefined) { if (param.required) { // The parameter is required, but was not provided, so throw a 400 error let errCode = 400; if (param.in === "header" && param.name.toLowerCase() === "content-length") { // Special case for...
javascript
function parseParameter (param, value, schema) { if (value === undefined) { if (param.required) { // The parameter is required, but was not provided, so throw a 400 error let errCode = 400; if (param.in === "header" && param.name.toLowerCase() === "content-length") { // Special case for...
[ "function", "parseParameter", "(", "param", ",", "value", ",", "schema", ")", "{", "if", "(", "value", "===", "undefined", ")", "{", "if", "(", "param", ".", "required", ")", "{", "// The parameter is required, but was not provided, so throw a 400 error", "let", "...
Parses the given parameter, using the given JSON schema definition. @param {object} param - The Parameter API object @param {*} value - The value to be parsed (it will be coerced if needed) @param {object} schema - The JSON schema definition for the parameter @returns {*} - The par...
[ "Parses", "the", "given", "parameter", "using", "the", "given", "JSON", "schema", "definition", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/param-parser.js#L122-L154
7,165
APIDevTools/swagger-express-middleware
lib/param-parser.js
getParams
function getParams (req) { if (req.swagger && req.swagger.params) { return req.swagger.params; } return []; }
javascript
function getParams (req) { if (req.swagger && req.swagger.params) { return req.swagger.params; } return []; }
[ "function", "getParams", "(", "req", ")", "{", "if", "(", "req", ".", "swagger", "&&", "req", ".", "swagger", ".", "params", ")", "{", "return", "req", ".", "swagger", ".", "params", ";", "}", "return", "[", "]", ";", "}" ]
Returns an array of the `req.swagger.params` properties. @returns {object[]}
[ "Returns", "an", "array", "of", "the", "req", ".", "swagger", ".", "params", "properties", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/param-parser.js#L161-L166
7,166
APIDevTools/swagger-express-middleware
lib/data-store/file-data-store.js
getDirectory
function getDirectory (baseDir, collection) { let dir = collection.substring(0, collection.lastIndexOf("/")); dir = dir.toLowerCase(); return path.normalize(path.join(baseDir, dir)); }
javascript
function getDirectory (baseDir, collection) { let dir = collection.substring(0, collection.lastIndexOf("/")); dir = dir.toLowerCase(); return path.normalize(path.join(baseDir, dir)); }
[ "function", "getDirectory", "(", "baseDir", ",", "collection", ")", "{", "let", "dir", "=", "collection", ".", "substring", "(", "0", ",", "collection", ".", "lastIndexOf", "(", "\"/\"", ")", ")", ";", "dir", "=", "dir", ".", "toLowerCase", "(", ")", "...
Returns the directory where the given collection's JSON file is stored. @param {string} baseDir - (e.g. "/some/base/path") @param {string} collection - (e.g. "/users/jdoe/orders") @returns {string} - (e.g. "/some/base/path/users/jdoe")
[ "Returns", "the", "directory", "where", "the", "given", "collection", "s", "JSON", "file", "is", "stored", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/file-data-store.js#L88-L92
7,167
APIDevTools/swagger-express-middleware
lib/data-store/file-data-store.js
getFilePath
function getFilePath (baseDir, collection) { let directory = getDirectory(baseDir, collection); let fileName = collection.substring(collection.lastIndexOf("/") + 1) + ".json"; fileName = fileName.toLowerCase(); return path.join(directory, fileName); }
javascript
function getFilePath (baseDir, collection) { let directory = getDirectory(baseDir, collection); let fileName = collection.substring(collection.lastIndexOf("/") + 1) + ".json"; fileName = fileName.toLowerCase(); return path.join(directory, fileName); }
[ "function", "getFilePath", "(", "baseDir", ",", "collection", ")", "{", "let", "directory", "=", "getDirectory", "(", "baseDir", ",", "collection", ")", ";", "let", "fileName", "=", "collection", ".", "substring", "(", "collection", ".", "lastIndexOf", "(", ...
Returns the full path of the JSON file for the given collection. @param {string} baseDir - (e.g. "/some/base/path") @param {string} collection - (e.g. "/users/jdoe/orders") @returns {string} - (e.g. "/some/base/path/users/jdoe/orders.json")
[ "Returns", "the", "full", "path", "of", "the", "JSON", "file", "for", "the", "given", "collection", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/data-store/file-data-store.js#L101-L106
7,168
APIDevTools/swagger-express-middleware
lib/request-validator.js
requestValidator
function requestValidator (context) { return [http500, http401, http404, http405, http406, http413, http415]; /** * Throws an HTTP 500 error if the Swagger API is invalid. * Calling {@link Middleware#init} again with a valid Swagger API will clear the error. */ function http500 (req, res, next) { if...
javascript
function requestValidator (context) { return [http500, http401, http404, http405, http406, http413, http415]; /** * Throws an HTTP 500 error if the Swagger API is invalid. * Calling {@link Middleware#init} again with a valid Swagger API will clear the error. */ function http500 (req, res, next) { if...
[ "function", "requestValidator", "(", "context", ")", "{", "return", "[", "http500", ",", "http401", ",", "http404", ",", "http405", ",", "http406", ",", "http413", ",", "http415", "]", ";", "/**\n * Throws an HTTP 500 error if the Swagger API is invalid.\n * Calling...
Validates the HTTP request against the Swagger API. An error is sent downstream if the request is invalid for any reason. @param {MiddlewareContext} context @returns {function[]}
[ "Validates", "the", "HTTP", "request", "against", "the", "Swagger", "API", ".", "An", "error", "is", "sent", "downstream", "if", "the", "request", "is", "invalid", "for", "any", "reason", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-validator.js#L16-L31
7,169
APIDevTools/swagger-express-middleware
lib/mock/query-collection.js
queryCollection
function queryCollection (req, res, next, dataStore) { dataStore.getCollection(req.path, (err, resources) => { if (!err) { resources = filter(resources, req); if (resources.length === 0) { // There is no data, so use the current date/time as the "last-modified" header res.swagger.last...
javascript
function queryCollection (req, res, next, dataStore) { dataStore.getCollection(req.path, (err, resources) => { if (!err) { resources = filter(resources, req); if (resources.length === 0) { // There is no data, so use the current date/time as the "last-modified" header res.swagger.last...
[ "function", "queryCollection", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", "{", "dataStore", ".", "getCollection", "(", "req", ".", "path", ",", "(", "err", ",", "resources", ")", "=>", "{", "if", "(", "!", "err", ")", "{", "resources...
Returns an array of all resources in the collection. If there are no resources, then an empty array is returned. No 404 error is thrown. If the Swagger API includes "query" parameters, they can be used to filter the results. Deep property names are allowed (e.g. "?address.city=New+York"). Query string params that are...
[ "Returns", "an", "array", "of", "all", "resources", "in", "the", "collection", ".", "If", "there", "are", "no", "resources", "then", "an", "empty", "array", "is", "returned", ".", "No", "404", "error", "is", "thrown", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/query-collection.js#L26-L54
7,170
APIDevTools/swagger-express-middleware
lib/mock/query-collection.js
deleteCollection
function deleteCollection (req, res, next, dataStore) { dataStore.getCollection(req.path, (err, resources) => { if (err) { next(err); } else { // Determine which resources to delete, based on query params let resourcesToDelete = filter(resources, req); if (resourcesToDelete.length...
javascript
function deleteCollection (req, res, next, dataStore) { dataStore.getCollection(req.path, (err, resources) => { if (err) { next(err); } else { // Determine which resources to delete, based on query params let resourcesToDelete = filter(resources, req); if (resourcesToDelete.length...
[ "function", "deleteCollection", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", "{", "dataStore", ".", "getCollection", "(", "req", ".", "path", ",", "(", "err", ",", "resources", ")", "=>", "{", "if", "(", "err", ")", "{", "next", "(", ...
Deletes all resources in the collection. If there are no resources, then nothing happens. No error is thrown. If the Swagger API includes "query" parameters, they can be used to filter what gets deleted. Deep property names are allowed (e.g. "?address.city=New+York"). Query string params that are not defined in the S...
[ "Deletes", "all", "resources", "in", "the", "collection", ".", "If", "there", "are", "no", "resources", "then", "nothing", "happens", ".", "No", "error", "is", "thrown", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/query-collection.js#L69-L115
7,171
APIDevTools/swagger-express-middleware
lib/mock/query-collection.js
sendResponse
function sendResponse (err, resources) { // Extract the "data" of each Resource resources = _.map(resources, "data"); // Use the current date/time as the "last-modified" header res.swagger.lastModified = new Date(); // Set the response body (unless it's already been set by other middleware) if...
javascript
function sendResponse (err, resources) { // Extract the "data" of each Resource resources = _.map(resources, "data"); // Use the current date/time as the "last-modified" header res.swagger.lastModified = new Date(); // Set the response body (unless it's already been set by other middleware) if...
[ "function", "sendResponse", "(", "err", ",", "resources", ")", "{", "// Extract the \"data\" of each Resource", "resources", "=", "_", ".", "map", "(", "resources", ",", "\"data\"", ")", ";", "// Use the current date/time as the \"last-modified\" header", "res", ".", "s...
Responds with the deleted resources
[ "Responds", "with", "the", "deleted", "resources" ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/query-collection.js#L93-L114
7,172
APIDevTools/swagger-express-middleware
lib/mock/query-collection.js
setDeepProperty
function setDeepProperty (obj, propName, propValue) { propName = propName.split("."); for (let i = 0; i < propName.length - 1; i++) { obj = obj[propName[i]] = obj[propName[i]] || {}; } obj[propName[propName.length - 1]] = propValue; }
javascript
function setDeepProperty (obj, propName, propValue) { propName = propName.split("."); for (let i = 0; i < propName.length - 1; i++) { obj = obj[propName[i]] = obj[propName[i]] || {}; } obj[propName[propName.length - 1]] = propValue; }
[ "function", "setDeepProperty", "(", "obj", ",", "propName", ",", "propValue", ")", "{", "propName", "=", "propName", ".", "split", "(", "\".\"", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "propName", ".", "length", "-", "1", ";", "i...
Sets a deep property of the given object. @param {object} obj - The object whose property is to be set. @param {string} propName - The deep property name (e.g. "Vet.Address.State") @param {*} propValue - The value to set
[ "Sets", "a", "deep", "property", "of", "the", "given", "object", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/query-collection.js#L158-L164
7,173
APIDevTools/swagger-express-middleware
lib/request-metadata.js
swaggerApiMetadata
function swaggerApiMetadata (req, res, next) { // Only set req.swagger.api if the request is under the API's basePath if (context.api) { let basePath = util.normalizePath(context.api.basePath, router); let reqPath = util.normalizePath(req.path, router); if (_.startsWith(reqPath, basePath)) { ...
javascript
function swaggerApiMetadata (req, res, next) { // Only set req.swagger.api if the request is under the API's basePath if (context.api) { let basePath = util.normalizePath(context.api.basePath, router); let reqPath = util.normalizePath(req.path, router); if (_.startsWith(reqPath, basePath)) { ...
[ "function", "swaggerApiMetadata", "(", "req", ",", "res", ",", "next", ")", "{", "// Only set req.swagger.api if the request is under the API's basePath", "if", "(", "context", ".", "api", ")", "{", "let", "basePath", "=", "util", ".", "normalizePath", "(", "context...
Sets `req.swagger.api`
[ "Sets", "req", ".", "swagger", ".", "api" ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L30-L41
7,174
APIDevTools/swagger-express-middleware
lib/request-metadata.js
swaggerPathMetadata
function swaggerPathMetadata (req, res, next) { if (req.swagger.api) { let relPath = getRelativePath(req); let relPathNormalized = util.normalizePath(relPath, router); // Search for a matching path Object.keys(req.swagger.api.paths).some((swaggerPath) => { let swaggerPathNormalized ...
javascript
function swaggerPathMetadata (req, res, next) { if (req.swagger.api) { let relPath = getRelativePath(req); let relPathNormalized = util.normalizePath(relPath, router); // Search for a matching path Object.keys(req.swagger.api.paths).some((swaggerPath) => { let swaggerPathNormalized ...
[ "function", "swaggerPathMetadata", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "swagger", ".", "api", ")", "{", "let", "relPath", "=", "getRelativePath", "(", "req", ")", ";", "let", "relPathNormalized", "=", "util", ".", "nor...
Sets `req.swagger.path`
[ "Sets", "req", ".", "swagger", ".", "path" ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L46-L77
7,175
APIDevTools/swagger-express-middleware
lib/request-metadata.js
swaggerMetadata
function swaggerMetadata (req, res, next) { /** * The Swagger Metadata that is added to each HTTP request. * This object is exposed as `req.swagger`. * * @name Request#swagger */ req.swagger = { /** * The complete Swagger API object. * (see https://github.com/swagger-api/swagger-spec/bl...
javascript
function swaggerMetadata (req, res, next) { /** * The Swagger Metadata that is added to each HTTP request. * This object is exposed as `req.swagger`. * * @name Request#swagger */ req.swagger = { /** * The complete Swagger API object. * (see https://github.com/swagger-api/swagger-spec/bl...
[ "function", "swaggerMetadata", "(", "req", ",", "res", ",", "next", ")", "{", "/**\n * The Swagger Metadata that is added to each HTTP request.\n * This object is exposed as `req.swagger`.\n *\n * @name Request#swagger\n */", "req", ".", "swagger", "=", "{", "/**\n * Th...
Creates the `req.swagger` object.
[ "Creates", "the", "req", ".", "swagger", "object", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L83-L135
7,176
APIDevTools/swagger-express-middleware
lib/request-metadata.js
swaggerOperationMetadata
function swaggerOperationMetadata (req, res, next) { if (req.swagger.path) { let method = req.method.toLowerCase(); if (method in req.swagger.path) { req.swagger.operation = req.swagger.path[method]; } else { util.warn("WARNING! Unable to find a Swagger operation that matches %s %s", req....
javascript
function swaggerOperationMetadata (req, res, next) { if (req.swagger.path) { let method = req.method.toLowerCase(); if (method in req.swagger.path) { req.swagger.operation = req.swagger.path[method]; } else { util.warn("WARNING! Unable to find a Swagger operation that matches %s %s", req....
[ "function", "swaggerOperationMetadata", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "swagger", ".", "path", ")", "{", "let", "method", "=", "req", ".", "method", ".", "toLowerCase", "(", ")", ";", "if", "(", "method", "in", ...
Sets `req.swagger.operation`
[ "Sets", "req", ".", "swagger", ".", "operation" ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L140-L153
7,177
APIDevTools/swagger-express-middleware
lib/request-metadata.js
swaggerParamsMetadata
function swaggerParamsMetadata (req, res, next) { req.swagger.params = util.getParameters(req.swagger.path, req.swagger.operation); next(); }
javascript
function swaggerParamsMetadata (req, res, next) { req.swagger.params = util.getParameters(req.swagger.path, req.swagger.operation); next(); }
[ "function", "swaggerParamsMetadata", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "swagger", ".", "params", "=", "util", ".", "getParameters", "(", "req", ".", "swagger", ".", "path", ",", "req", ".", "swagger", ".", "operation", ")", ";"...
Sets `req.swagger.params`
[ "Sets", "req", ".", "swagger", ".", "params" ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L158-L161
7,178
APIDevTools/swagger-express-middleware
lib/request-metadata.js
swaggerSecurityMetadata
function swaggerSecurityMetadata (req, res, next) { if (req.swagger.operation) { // Get the security requirements for this operation (or the global API security) req.swagger.security = req.swagger.operation.security || req.swagger.api.security || []; } else if (req.swagger.api) { // Get the global sec...
javascript
function swaggerSecurityMetadata (req, res, next) { if (req.swagger.operation) { // Get the security requirements for this operation (or the global API security) req.swagger.security = req.swagger.operation.security || req.swagger.api.security || []; } else if (req.swagger.api) { // Get the global sec...
[ "function", "swaggerSecurityMetadata", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "swagger", ".", "operation", ")", "{", "// Get the security requirements for this operation (or the global API security)", "req", ".", "swagger", ".", "securit...
Sets `req.swagger.security`
[ "Sets", "req", ".", "swagger", ".", "security" ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L166-L177
7,179
APIDevTools/swagger-express-middleware
lib/request-metadata.js
getRelativePath
function getRelativePath (req) { if (!req.swagger.api.basePath) { return req.path; } else { return req.path.substr(req.swagger.api.basePath.length); } }
javascript
function getRelativePath (req) { if (!req.swagger.api.basePath) { return req.path; } else { return req.path.substr(req.swagger.api.basePath.length); } }
[ "function", "getRelativePath", "(", "req", ")", "{", "if", "(", "!", "req", ".", "swagger", ".", "api", ".", "basePath", ")", "{", "return", "req", ".", "path", ";", "}", "else", "{", "return", "req", ".", "path", ".", "substr", "(", "req", ".", ...
Returns the HTTP request path, relative to the Swagger API's basePath. @param {Request} req @returns {string}
[ "Returns", "the", "HTTP", "request", "path", "relative", "to", "the", "Swagger", "API", "s", "basePath", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L185-L192
7,180
APIDevTools/swagger-express-middleware
lib/request-metadata.js
pathMatches
function pathMatches (path, swaggerPath) { // Convert the Swagger path to a RegExp let pathPattern = swaggerPath.replace(util.swaggerParamRegExp, (match, paramName) => { return "([^/]+)"; }); // NOTE: This checks for an EXACT, case-sensitive match let pathRegExp = new RegExp("^" + pathPattern + "$"); ...
javascript
function pathMatches (path, swaggerPath) { // Convert the Swagger path to a RegExp let pathPattern = swaggerPath.replace(util.swaggerParamRegExp, (match, paramName) => { return "([^/]+)"; }); // NOTE: This checks for an EXACT, case-sensitive match let pathRegExp = new RegExp("^" + pathPattern + "$"); ...
[ "function", "pathMatches", "(", "path", ",", "swaggerPath", ")", "{", "// Convert the Swagger path to a RegExp", "let", "pathPattern", "=", "swaggerPath", ".", "replace", "(", "util", ".", "swaggerParamRegExp", ",", "(", "match", ",", "paramName", ")", "=>", "{", ...
Determines whether the given HTTP request path matches the given Swagger path. @param {string} path - The request path (e.g. "/users/jdoe/orders/1234") @param {string} swaggerPath - The Swagger path (e.g. "/users/{username}/orders/{orderId}") @returns {boolean}
[ "Determines", "whether", "the", "given", "HTTP", "request", "path", "matches", "the", "given", "Swagger", "path", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/request-metadata.js#L201-L211
7,181
APIDevTools/swagger-express-middleware
lib/cors.js
corsHeaders
function corsHeaders (req, res, next) { // Get the default CORS response headers as specified in the Swagger API let responseHeaders = getResponseHeaders(req); // Set each CORS header _.each(accessControl, (header) => { if (responseHeaders[header] !== undefined) { // Set the header to the default val...
javascript
function corsHeaders (req, res, next) { // Get the default CORS response headers as specified in the Swagger API let responseHeaders = getResponseHeaders(req); // Set each CORS header _.each(accessControl, (header) => { if (responseHeaders[header] !== undefined) { // Set the header to the default val...
[ "function", "corsHeaders", "(", "req", ",", "res", ",", "next", ")", "{", "// Get the default CORS response headers as specified in the Swagger API", "let", "responseHeaders", "=", "getResponseHeaders", "(", "req", ")", ";", "// Set each CORS header", "_", ".", "each", ...
Sets the CORS headers. If default values are specified in the Swagger API, then those values are used. Otherwise, sensible defaults are used.
[ "Sets", "the", "CORS", "headers", ".", "If", "default", "values", "are", "specified", "in", "the", "Swagger", "API", "then", "those", "values", "are", "used", ".", "Otherwise", "sensible", "defaults", "are", "used", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/cors.js#L31-L88
7,182
APIDevTools/swagger-express-middleware
lib/cors.js
corsPreflight
function corsPreflight (req, res, next) { if (req.method === "OPTIONS") { util.debug("OPTIONS %s is a CORS preflight request. Sending HTTP 200 response.", req.path); res.send(); } else { next(); } }
javascript
function corsPreflight (req, res, next) { if (req.method === "OPTIONS") { util.debug("OPTIONS %s is a CORS preflight request. Sending HTTP 200 response.", req.path); res.send(); } else { next(); } }
[ "function", "corsPreflight", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "method", "===", "\"OPTIONS\"", ")", "{", "util", ".", "debug", "(", "\"OPTIONS %s is a CORS preflight request. Sending HTTP 200 response.\"", ",", "req", ".", "pa...
Handles CORS preflight requests.
[ "Handles", "CORS", "preflight", "requests", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/cors.js#L93-L101
7,183
APIDevTools/swagger-express-middleware
lib/cors.js
getResponseHeaders
function getResponseHeaders (req) { let corsHeaders = {}; if (req.swagger) { let headers = []; if (req.method !== "OPTIONS") { // This isn't a preflight request, so the operation's response headers take precedence over the OPTIONS headers headers = getOperationResponseHeaders(req.swagger.operat...
javascript
function getResponseHeaders (req) { let corsHeaders = {}; if (req.swagger) { let headers = []; if (req.method !== "OPTIONS") { // This isn't a preflight request, so the operation's response headers take precedence over the OPTIONS headers headers = getOperationResponseHeaders(req.swagger.operat...
[ "function", "getResponseHeaders", "(", "req", ")", "{", "let", "corsHeaders", "=", "{", "}", ";", "if", "(", "req", ".", "swagger", ")", "{", "let", "headers", "=", "[", "]", ";", "if", "(", "req", ".", "method", "!==", "\"OPTIONS\"", ")", "{", "//...
Returns an object containing the CORS response headers that are defined in the Swagger API. If the same CORS header is defined for multiple responses, then the first one wins. @param {Request} req @returns {object}
[ "Returns", "an", "object", "containing", "the", "CORS", "response", "headers", "that", "are", "defined", "in", "the", "Swagger", "API", ".", "If", "the", "same", "CORS", "header", "is", "defined", "for", "multiple", "responses", "then", "the", "first", "one"...
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/cors.js#L110-L134
7,184
APIDevTools/swagger-express-middleware
lib/helpers/json-schema.js
JsonSchema
function JsonSchema (schema) { if (!schema) { throw ono({ status: 500 }, "Missing JSON schema"); } if (schema.type !== undefined && dataTypes.indexOf(schema.type) === -1) { throw ono({ status: 500 }, "Invalid JSON schema type: %s", schema.type); } this.schema = schema; }
javascript
function JsonSchema (schema) { if (!schema) { throw ono({ status: 500 }, "Missing JSON schema"); } if (schema.type !== undefined && dataTypes.indexOf(schema.type) === -1) { throw ono({ status: 500 }, "Invalid JSON schema type: %s", schema.type); } this.schema = schema; }
[ "function", "JsonSchema", "(", "schema", ")", "{", "if", "(", "!", "schema", ")", "{", "throw", "ono", "(", "{", "status", ":", "500", "}", ",", "\"Missing JSON schema\"", ")", ";", "}", "if", "(", "schema", ".", "type", "!==", "undefined", "&&", "da...
Parses and validates values against JSON schemas. @constructor
[ "Parses", "and", "validates", "values", "against", "JSON", "schemas", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/helpers/json-schema.js#L61-L70
7,185
APIDevTools/swagger-express-middleware
lib/helpers/json-schema.js
getValueToValidate
function getValueToValidate (schema, value) { // Is the value empty? if (value === undefined || value === "" || (schema.type === "object" && _.isObject(value) && _.isEmpty(value))) { // It's blank, so return the default/example value (if there is one) if (schema.default !== undefined) { value = s...
javascript
function getValueToValidate (schema, value) { // Is the value empty? if (value === undefined || value === "" || (schema.type === "object" && _.isObject(value) && _.isEmpty(value))) { // It's blank, so return the default/example value (if there is one) if (schema.default !== undefined) { value = s...
[ "function", "getValueToValidate", "(", "schema", ",", "value", ")", "{", "// Is the value empty?", "if", "(", "value", "===", "undefined", "||", "value", "===", "\"\"", "||", "(", "schema", ".", "type", "===", "\"object\"", "&&", "_", ".", "isObject", "(", ...
Returns the given value, or the default value if the given value is empty.
[ "Returns", "the", "given", "value", "or", "the", "default", "value", "if", "the", "given", "value", "is", "empty", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/helpers/json-schema.js#L178-L199
7,186
APIDevTools/swagger-express-middleware
lib/path-parser.js
registerPathParamMiddleware
function registerPathParamMiddleware () { let pathParams = getAllPathParamNames(); pathParams.forEach((param) => { if (!alreadyRegistered(param)) { router.param(param, pathParamMiddleware); } }); }
javascript
function registerPathParamMiddleware () { let pathParams = getAllPathParamNames(); pathParams.forEach((param) => { if (!alreadyRegistered(param)) { router.param(param, pathParamMiddleware); } }); }
[ "function", "registerPathParamMiddleware", "(", ")", "{", "let", "pathParams", "=", "getAllPathParamNames", "(", ")", ";", "pathParams", ".", "forEach", "(", "(", "param", ")", "=>", "{", "if", "(", "!", "alreadyRegistered", "(", "param", ")", ")", "{", "r...
Registers middleware to parse path parameters.
[ "Registers", "middleware", "to", "parse", "path", "parameters", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/path-parser.js#L45-L53
7,187
APIDevTools/swagger-express-middleware
lib/path-parser.js
getAllPathParamNames
function getAllPathParamNames () { let params = []; function addParam (param) { if (param.in === "path") { params.push(param.name); } } if (context.api) { _.each(context.api.paths, (path) => { // Add each path parameter _.each(path.parameters, addParam); ...
javascript
function getAllPathParamNames () { let params = []; function addParam (param) { if (param.in === "path") { params.push(param.name); } } if (context.api) { _.each(context.api.paths, (path) => { // Add each path parameter _.each(path.parameters, addParam); ...
[ "function", "getAllPathParamNames", "(", ")", "{", "let", "params", "=", "[", "]", ";", "function", "addParam", "(", "param", ")", "{", "if", "(", "param", ".", "in", "===", "\"path\"", ")", "{", "params", ".", "push", "(", "param", ".", "name", ")",...
Returns the unique names of all path params in the Swagger API. @returns {string[]}
[ "Returns", "the", "unique", "names", "of", "all", "path", "params", "in", "the", "Swagger", "API", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/path-parser.js#L60-L82
7,188
APIDevTools/swagger-express-middleware
lib/path-parser.js
alreadyRegistered
function alreadyRegistered (paramName) { let params = router.params; if (!params && router._router) { params = router._router.params; } return params && params[paramName] && (params[paramName].indexOf(pathParamMiddleware) >= 0); }
javascript
function alreadyRegistered (paramName) { let params = router.params; if (!params && router._router) { params = router._router.params; } return params && params[paramName] && (params[paramName].indexOf(pathParamMiddleware) >= 0); }
[ "function", "alreadyRegistered", "(", "paramName", ")", "{", "let", "params", "=", "router", ".", "params", ";", "if", "(", "!", "params", "&&", "router", ".", "_router", ")", "{", "params", "=", "router", ".", "_router", ".", "params", ";", "}", "retu...
Determines whether we've already registered path-param middleware for the given parameter. @param {string} paramName @returns {boolean}
[ "Determines", "whether", "we", "ve", "already", "registered", "path", "-", "param", "middleware", "for", "the", "given", "parameter", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/path-parser.js#L90-L98
7,189
APIDevTools/swagger-express-middleware
lib/file-server.js
serveDereferencedSwaggerFile
function serveDereferencedSwaggerFile (req, res, next) { if (req.method === "GET" || req.method === "HEAD") { let configPath = getConfiguredPath(options.apiPath); configPath = util.normalizePath(configPath, router); let reqPath = util.normalizePath(req.path, router); if (reqPath === configP...
javascript
function serveDereferencedSwaggerFile (req, res, next) { if (req.method === "GET" || req.method === "HEAD") { let configPath = getConfiguredPath(options.apiPath); configPath = util.normalizePath(configPath, router); let reqPath = util.normalizePath(req.path, router); if (reqPath === configP...
[ "function", "serveDereferencedSwaggerFile", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "method", "===", "\"GET\"", "||", "req", ".", "method", "===", "\"HEAD\"", ")", "{", "let", "configPath", "=", "getConfiguredPath", "(", "opti...
Serves the fully-dereferenced Swagger API in JSON format.
[ "Serves", "the", "fully", "-", "dereferenced", "Swagger", "API", "in", "JSON", "format", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/file-server.js#L36-L56
7,190
APIDevTools/swagger-express-middleware
lib/file-server.js
getConfiguredPath
function getConfiguredPath (path) { if (options.useBasePath && context.api && context.api.basePath) { return context.api.basePath + path; } else { return path; } }
javascript
function getConfiguredPath (path) { if (options.useBasePath && context.api && context.api.basePath) { return context.api.basePath + path; } else { return path; } }
[ "function", "getConfiguredPath", "(", "path", ")", "{", "if", "(", "options", ".", "useBasePath", "&&", "context", ".", "api", "&&", "context", ".", "api", ".", "basePath", ")", "{", "return", "context", ".", "api", ".", "basePath", "+", "path", ";", "...
Prefixes the given path with the API's basePath, if that option is enabled and the API has a basePath. @param {string} path @returns {string}
[ "Prefixes", "the", "given", "path", "with", "the", "API", "s", "basePath", "if", "that", "option", "is", "enabled", "and", "the", "API", "has", "a", "basePath", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/file-server.js#L105-L112
7,191
APIDevTools/swagger-express-middleware
lib/mock/index.js
mockImplementation
function mockImplementation (req, res, next) { if (res.swagger) { // Determine the semantics of this request let request = new SemanticRequest(req); // Determine which mock to run let mock; if (request.isCollection) { mock = queryCollection[req.method] || editCollectio...
javascript
function mockImplementation (req, res, next) { if (res.swagger) { // Determine the semantics of this request let request = new SemanticRequest(req); // Determine which mock to run let mock; if (request.isCollection) { mock = queryCollection[req.method] || editCollectio...
[ "function", "mockImplementation", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "res", ".", "swagger", ")", "{", "// Determine the semantics of this request\r", "let", "request", "=", "new", "SemanticRequest", "(", "req", ")", ";", "// Determine whic...
Runs the appropriate mock implementation.
[ "Runs", "the", "appropriate", "mock", "implementation", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/index.js#L107-L132
7,192
APIDevTools/swagger-express-middleware
lib/mock/index.js
mockResponseHeaders
function mockResponseHeaders (req, res, next) { if (res.swagger) { util.debug("Setting %d response headers...", _.keys(res.swagger.headers).length); if (res.swagger.headers) { _.forEach(res.swagger.headers, (header, name) => { // Set all HTTP headers that are defined in the Swagger API. ...
javascript
function mockResponseHeaders (req, res, next) { if (res.swagger) { util.debug("Setting %d response headers...", _.keys(res.swagger.headers).length); if (res.swagger.headers) { _.forEach(res.swagger.headers, (header, name) => { // Set all HTTP headers that are defined in the Swagger API. ...
[ "function", "mockResponseHeaders", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "res", ".", "swagger", ")", "{", "util", ".", "debug", "(", "\"Setting %d response headers...\"", ",", "_", ".", "keys", "(", "res", ".", "swagger", ".", "header...
Sets response headers, according to the Swagger API.
[ "Sets", "response", "headers", "according", "to", "the", "Swagger", "API", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/index.js#L138-L190
7,193
APIDevTools/swagger-express-middleware
lib/mock/index.js
mockResponseBody
function mockResponseBody (req, res, next) { if (res.swagger) { if (res.swagger.isEmpty) { // There is no response schema, so send an empty response util.debug("%s %s does not have a response schema. Sending an empty response", req.method, req.path); res.send(); } else { //...
javascript
function mockResponseBody (req, res, next) { if (res.swagger) { if (res.swagger.isEmpty) { // There is no response schema, so send an empty response util.debug("%s %s does not have a response schema. Sending an empty response", req.method, req.path); res.send(); } else { //...
[ "function", "mockResponseBody", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "res", ".", "swagger", ")", "{", "if", "(", "res", ".", "swagger", ".", "isEmpty", ")", "{", "// There is no response schema, so send an empty response\r", "util", ".", ...
Tries to make the response body adhere to the Swagger API.
[ "Tries", "to", "make", "the", "response", "body", "adhere", "to", "the", "Swagger", "API", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/index.js#L195-L226
7,194
APIDevTools/swagger-express-middleware
lib/mock/index.js
sendText
function sendText (req, res, next, data) { setContentType(req, res, ["text", "html", "text/*", "application/*"], // allow these types ["json", "*/json", "+json", "application/octet-stream"]); // don't allow these types util.debug("Serializing the response as a string"); res.send(_(...
javascript
function sendText (req, res, next, data) { setContentType(req, res, ["text", "html", "text/*", "application/*"], // allow these types ["json", "*/json", "+json", "application/octet-stream"]); // don't allow these types util.debug("Serializing the response as a string"); res.send(_(...
[ "function", "sendText", "(", "req", ",", "res", ",", "next", ",", "data", ")", "{", "setContentType", "(", "req", ",", "res", ",", "[", "\"text\"", ",", "\"html\"", ",", "\"text/*\"", ",", "\"application/*\"", "]", ",", "// allow these types\r", "[", "\"js...
Sends the given data as plain-text. @param {Request} req @param {Response} res @param {function} next @param {*} data
[ "Sends", "the", "given", "data", "as", "plain", "-", "text", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/index.js#L251-L258
7,195
APIDevTools/swagger-express-middleware
lib/mock/index.js
setContentType
function setContentType (req, res, supported, excluded) { // Get the MIME types that this operation produces let produces = req.swagger.operation.produces || req.swagger.api.produces || []; if (produces.length === 0) { // No MIME types were specified, so just use the first one util.debug('No "produ...
javascript
function setContentType (req, res, supported, excluded) { // Get the MIME types that this operation produces let produces = req.swagger.operation.produces || req.swagger.api.produces || []; if (produces.length === 0) { // No MIME types were specified, so just use the first one util.debug('No "produ...
[ "function", "setContentType", "(", "req", ",", "res", ",", "supported", ",", "excluded", ")", "{", "// Get the MIME types that this operation produces\r", "let", "produces", "=", "req", ".", "swagger", ".", "operation", ".", "produces", "||", "req", ".", "swagger"...
Sets the Content-Type HTTP header to one of the given options. The best option is chosen, based on the MIME types that this operation produces. @param {Request} req @param {Response} res @param {string[]} supported - A list of MIME types that are supported @param {string[]} [excluded] - A list of MIME ty...
[ "Sets", "the", "Content", "-", "Type", "HTTP", "header", "to", "one", "of", "the", "given", "options", ".", "The", "best", "option", "is", "chosen", "based", "on", "the", "MIME", "types", "that", "this", "operation", "produces", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/index.js#L326-L354
7,196
APIDevTools/swagger-express-middleware
lib/mock/semantic-request.js
isCollectionRequest
function isCollectionRequest (req) { let isCollection = responseIsCollection(req); if (isCollection === undefined) { isCollection = !lastPathSegmentIsAParameter(req); } return isCollection; }
javascript
function isCollectionRequest (req) { let isCollection = responseIsCollection(req); if (isCollection === undefined) { isCollection = !lastPathSegmentIsAParameter(req); } return isCollection; }
[ "function", "isCollectionRequest", "(", "req", ")", "{", "let", "isCollection", "=", "responseIsCollection", "(", "req", ")", ";", "if", "(", "isCollection", "===", "undefined", ")", "{", "isCollection", "=", "!", "lastPathSegmentIsAParameter", "(", "req", ")", ...
Determines whether the given path is a "resource path" or a "collection path". Resource paths operate on a single REST resource, whereas collection paths operate on a collection of resources. NOTE: This algorithm is subject to change. Over time, it should get smarter and better at determining request types. @param ...
[ "Determines", "whether", "the", "given", "path", "is", "a", "resource", "path", "or", "a", "collection", "path", ".", "Resource", "paths", "operate", "on", "a", "single", "REST", "resource", "whereas", "collection", "paths", "operate", "on", "a", "collection",...
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/semantic-request.js#L34-L42
7,197
APIDevTools/swagger-express-middleware
lib/mock/semantic-request.js
responseIsCollection
function responseIsCollection (req) { let getter = req.swagger.path.get || req.swagger.path.head; if (getter) { let responses = util.getResponsesBetween(getter, 200, 299); if (responses.length > 0) { let response = new SemanticResponse(responses[0].api, req.swagger.path); if (!response.isEmpty) ...
javascript
function responseIsCollection (req) { let getter = req.swagger.path.get || req.swagger.path.head; if (getter) { let responses = util.getResponsesBetween(getter, 200, 299); if (responses.length > 0) { let response = new SemanticResponse(responses[0].api, req.swagger.path); if (!response.isEmpty) ...
[ "function", "responseIsCollection", "(", "req", ")", "{", "let", "getter", "=", "req", ".", "swagger", ".", "path", ".", "get", "||", "req", ".", "swagger", ".", "path", ".", "head", ";", "if", "(", "getter", ")", "{", "let", "responses", "=", "util"...
Examines the GET or HEAD operation for the path and determines whether it is a collection response. @param {Request} req @returns {boolean|undefined} True if the response schema is a collection. False if it's not a collection. Undefined if there is not response schema.
[ "Examines", "the", "GET", "or", "HEAD", "operation", "for", "the", "path", "and", "determines", "whether", "it", "is", "a", "collection", "response", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/semantic-request.js#L52-L63
7,198
APIDevTools/swagger-express-middleware
lib/mock/semantic-request.js
lastPathSegmentIsAParameter
function lastPathSegmentIsAParameter (req) { let lastSlash = req.swagger.pathName.lastIndexOf("/"); let lastParam = req.swagger.pathName.lastIndexOf("{"); return (lastParam > lastSlash); }
javascript
function lastPathSegmentIsAParameter (req) { let lastSlash = req.swagger.pathName.lastIndexOf("/"); let lastParam = req.swagger.pathName.lastIndexOf("{"); return (lastParam > lastSlash); }
[ "function", "lastPathSegmentIsAParameter", "(", "req", ")", "{", "let", "lastSlash", "=", "req", ".", "swagger", ".", "pathName", ".", "lastIndexOf", "(", "\"/\"", ")", ";", "let", "lastParam", "=", "req", ".", "swagger", ".", "pathName", ".", "lastIndexOf",...
Determines whether the last path segment is a Swagger parameter. For example, the following paths are all considered to be resource requests, because their final path segment contains a parameter: - /users/{username} - /products/{productId}/reviews/review-{reviewId} - /{country}/{state}/{city} Conversely, the follow...
[ "Determines", "whether", "the", "last", "path", "segment", "is", "a", "Swagger", "parameter", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/semantic-request.js#L85-L89
7,199
APIDevTools/swagger-express-middleware
lib/mock/semantic-response.js
SemanticResponse
function SemanticResponse (response, path) { /** * The JSON schema of the response * @type {object|null} */ this.schema = response.schema || null; /** * The response headers, from the Swagger API * @type {object|null} */ this.headers = response.headers || null; /** * If true, then an em...
javascript
function SemanticResponse (response, path) { /** * The JSON schema of the response * @type {object|null} */ this.schema = response.schema || null; /** * The response headers, from the Swagger API * @type {object|null} */ this.headers = response.headers || null; /** * If true, then an em...
[ "function", "SemanticResponse", "(", "response", ",", "path", ")", "{", "/**\n * The JSON schema of the response\n * @type {object|null}\n */", "this", ".", "schema", "=", "response", ".", "schema", "||", "null", ";", "/**\n * The response headers, from the Swagger API\...
Describes the semantics of a Swagger response. @param {object} response - The Response object, from the Swagger API @param {object} path - The Path object that contains the response. Used for semantic analysis. @constructor
[ "Describes", "the", "semantics", "of", "a", "Swagger", "response", "." ]
7544c22045945565f6555419b678fe51ba664a1f
https://github.com/APIDevTools/swagger-express-middleware/blob/7544c22045945565f6555419b678fe51ba664a1f/lib/mock/semantic-response.js#L15-L79