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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
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", "(", "p", "===", "prop", ")", "{", "if", "(", "func", "&&", "typeof", "func", "===", "\"function\"", ")", "{", "func", "(", "obj", ",", "prop", ")", ";", "}", "}", "else", "if", "(", "typeof", "obj", "[", "p", "]", "===", "\"object\"", ")", "{", "filterValue", "(", "obj", "[", "p", "]", ",", "prop", ",", "func", ")", ";", "}", "}", "}" ]
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", "(", "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", ";", "}" ]
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._regionTypeToPredictParameter = new RegionTypeParameter({ terria: this.terria, catalogFunction: this, id: "regionTypeToPredict", name: "Region Type to Predict", description: "The type of region for which to predict characteristics." }); this._coarseDataRegionTypeParameter = new RegionTypeParameter({ terria: this.terria, catalogFunction: this, id: "coarseDataRegionType", name: "Coarse Data Region Type", description: "The type of region with which the coarse-grained input characteristics are associated." }); this._isMeanAggregationParameter = new BooleanParameter({ terria: this.terria, catalogFunction: this, id: "isMeanAggregation", name: "Aggregation", description: "Specifies how coarse region values were aggregated. True if the value is the mean of the values across the region, or False if the value is the sum of the values across the region.", trueName: "Mean Aggregation", trueDescription: "Coarse region values are the mean of samples in the region. For example, average household income.", falseName: "Sum Aggregation", falseDescription: "Coarse region values are the sum of samples in the region. For example, total population.", defaultValue: true }); this._dataParameter = new RegionDataParameter({ terria: this.terria, catalogFunction: this, id: "data", name: "Characteristic to Predict", description: "The characteristic to predict for each region.", regionProvider: this._coarseDataRegionTypeParameter, singleSelect: true }); this._parameters = [ this._coarseDataRegionTypeParameter, this._regionTypeToPredictParameter, this._isMeanAggregationParameter, this._dataParameter ]; }
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._regionTypeToPredictParameter = new RegionTypeParameter({ terria: this.terria, catalogFunction: this, id: "regionTypeToPredict", name: "Region Type to Predict", description: "The type of region for which to predict characteristics." }); this._coarseDataRegionTypeParameter = new RegionTypeParameter({ terria: this.terria, catalogFunction: this, id: "coarseDataRegionType", name: "Coarse Data Region Type", description: "The type of region with which the coarse-grained input characteristics are associated." }); this._isMeanAggregationParameter = new BooleanParameter({ terria: this.terria, catalogFunction: this, id: "isMeanAggregation", name: "Aggregation", description: "Specifies how coarse region values were aggregated. True if the value is the mean of the values across the region, or False if the value is the sum of the values across the region.", trueName: "Mean Aggregation", trueDescription: "Coarse region values are the mean of samples in the region. For example, average household income.", falseName: "Sum Aggregation", falseDescription: "Coarse region values are the sum of samples in the region. For example, total population.", defaultValue: true }); this._dataParameter = new RegionDataParameter({ terria: this.terria, catalogFunction: this, id: "data", name: "Characteristic to Predict", description: "The characteristic to predict for each region.", regionProvider: this._coarseDataRegionTypeParameter, singleSelect: true }); this._parameters = [ this._coarseDataRegionTypeParameter, this._regionTypeToPredictParameter, this._isMeanAggregationParameter, this._dataParameter ]; }
[ "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", ".", "_regionTypeToPredictParameter", "=", "new", "RegionTypeParameter", "(", "{", "terria", ":", "this", ".", "terria", ",", "catalogFunction", ":", "this", ",", "id", ":", "\"regionTypeToPredict\"", ",", "name", ":", "\"Region Type to Predict\"", ",", "description", ":", "\"The type of region for which to predict characteristics.\"", "}", ")", ";", "this", ".", "_coarseDataRegionTypeParameter", "=", "new", "RegionTypeParameter", "(", "{", "terria", ":", "this", ".", "terria", ",", "catalogFunction", ":", "this", ",", "id", ":", "\"coarseDataRegionType\"", ",", "name", ":", "\"Coarse Data Region Type\"", ",", "description", ":", "\"The type of region with which the coarse-grained input characteristics are associated.\"", "}", ")", ";", "this", ".", "_isMeanAggregationParameter", "=", "new", "BooleanParameter", "(", "{", "terria", ":", "this", ".", "terria", ",", "catalogFunction", ":", "this", ",", "id", ":", "\"isMeanAggregation\"", ",", "name", ":", "\"Aggregation\"", ",", "description", ":", "\"Specifies how coarse region values were aggregated. True if the value is the mean of the values across the region, or False if the value is the sum of the values across the region.\"", ",", "trueName", ":", "\"Mean Aggregation\"", ",", "trueDescription", ":", "\"Coarse region values are the mean of samples in the region. For example, average household income.\"", ",", "falseName", ":", "\"Sum Aggregation\"", ",", "falseDescription", ":", "\"Coarse region values are the sum of samples in the region. For example, total population.\"", ",", "defaultValue", ":", "true", "}", ")", ";", "this", ".", "_dataParameter", "=", "new", "RegionDataParameter", "(", "{", "terria", ":", "this", ".", "terria", ",", "catalogFunction", ":", "this", ",", "id", ":", "\"data\"", ",", "name", ":", "\"Characteristic to Predict\"", ",", "description", ":", "\"The characteristic to predict for each region.\"", ",", "regionProvider", ":", "this", ".", "_coarseDataRegionTypeParameter", ",", "singleSelect", ":", "true", "}", ")", ";", "this", ".", "_parameters", "=", "[", "this", ".", "_coarseDataRegionTypeParameter", ",", "this", ".", "_regionTypeToPredictParameter", ",", "this", ".", "_isMeanAggregationParameter", ",", "this", ".", "_dataParameter", "]", ";", "}" ]
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", "characteristics", "." ]
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 one with the closest x to the mouse. const closestXPoint = closestXPoints.reduce((previous, current) => Math.abs(current.x - x) < Math.abs(previous.x - x) ? current : previous ); const nearlyEqualX = thisPoint => Math.abs(thisPoint.x - closestXPoint.x) < threshold; // Only select the chart lines (pointArrays) which have their closest x to the mouse = the overall closest. const selectedPoints = closestXPoints.filter(nearlyEqualX); const isSelectedArray = closestXPoints.map(nearlyEqualX); const selectedData = data.filter((line, i) => isSelectedArray[i]); selectedData.forEach((line, i) => { line.point = selectedPoints[i]; }); // TODO: this adds the property to the original data - bad. return selectedData; }
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 one with the closest x to the mouse. const closestXPoint = closestXPoints.reduce((previous, current) => Math.abs(current.x - x) < Math.abs(previous.x - x) ? current : previous ); const nearlyEqualX = thisPoint => Math.abs(thisPoint.x - closestXPoint.x) < threshold; // Only select the chart lines (pointArrays) which have their closest x to the mouse = the overall closest. const selectedPoints = closestXPoints.filter(nearlyEqualX); const isSelectedArray = closestXPoints.map(nearlyEqualX); const selectedData = data.filter((line, i) => isSelectedArray[i]); selectedData.forEach((line, i) => { line.point = selectedPoints[i]; }); // TODO: this adds the property to the original data - bad. return selectedData; }
[ "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 one with the closest x to the mouse.", "const", "closestXPoint", "=", "closestXPoints", ".", "reduce", "(", "(", "previous", ",", "current", ")", "=>", "Math", ".", "abs", "(", "current", ".", "x", "-", "x", ")", "<", "Math", ".", "abs", "(", "previous", ".", "x", "-", "x", ")", "?", "current", ":", "previous", ")", ";", "const", "nearlyEqualX", "=", "thisPoint", "=>", "Math", ".", "abs", "(", "thisPoint", ".", "x", "-", "closestXPoint", ".", "x", ")", "<", "threshold", ";", "// Only select the chart lines (pointArrays) which have their closest x to the mouse = the overall closest.", "const", "selectedPoints", "=", "closestXPoints", ".", "filter", "(", "nearlyEqualX", ")", ";", "const", "isSelectedArray", "=", "closestXPoints", ".", "map", "(", "nearlyEqualX", ")", ";", "const", "selectedData", "=", "data", ".", "filter", "(", "(", "line", ",", "i", ")", "=>", "isSelectedArray", "[", "i", "]", ")", ";", "selectedData", ".", "forEach", "(", "(", "line", ",", "i", ")", "=>", "{", "line", ".", "point", "=", "selectedPoints", "[", "i", "]", ";", "}", ")", ";", "// TODO: this adds the property to the original data - bad.", "return", "selectedData", ";", "}" ]
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", ".", "getURLProxyIfNecessary", "(", "defaultValue", "(", "overrideUrl", ",", "DATA61_GNAF_BULK_SEARCH_URL", ")", ")", ";", "}" ]
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: sanitiseAddressNumber(jsonInfo.flat.number), level: sanitiseAddressNumber(jsonInfo.level.number), numberFirst: sanitiseAddressNumber(jsonInfo.numberFirst.number), numberLast: sanitiseAddressNumber(jsonInfo.numberLast.number), street: jsonInfo.street, localityName: jsonInfo.localityName, localityVariantNames: jsonInfo.localityVariant.map(function(locality) { return locality.localityName; }), state: { abbreviation: jsonInfo.stateAbbreviation, name: jsonInfo.stateName }, postCode: jsonInfo.postcode, location: { latitude: jsonInfo.location.lat, longitude: jsonInfo.location.lon } }; }
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: sanitiseAddressNumber(jsonInfo.flat.number), level: sanitiseAddressNumber(jsonInfo.level.number), numberFirst: sanitiseAddressNumber(jsonInfo.numberFirst.number), numberLast: sanitiseAddressNumber(jsonInfo.numberLast.number), street: jsonInfo.street, localityName: jsonInfo.localityName, localityVariantNames: jsonInfo.localityVariant.map(function(locality) { return locality.localityName; }), state: { abbreviation: jsonInfo.stateAbbreviation, name: jsonInfo.stateName }, postCode: jsonInfo.postcode, location: { latitude: jsonInfo.location.lat, longitude: jsonInfo.location.lon } }; }
[ "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", ":", "sanitiseAddressNumber", "(", "jsonInfo", ".", "flat", ".", "number", ")", ",", "level", ":", "sanitiseAddressNumber", "(", "jsonInfo", ".", "level", ".", "number", ")", ",", "numberFirst", ":", "sanitiseAddressNumber", "(", "jsonInfo", ".", "numberFirst", ".", "number", ")", ",", "numberLast", ":", "sanitiseAddressNumber", "(", "jsonInfo", ".", "numberLast", ".", "number", ")", ",", "street", ":", "jsonInfo", ".", "street", ",", "localityName", ":", "jsonInfo", ".", "localityName", ",", "localityVariantNames", ":", "jsonInfo", ".", "localityVariant", ".", "map", "(", "function", "(", "locality", ")", "{", "return", "locality", ".", "localityName", ";", "}", ")", ",", "state", ":", "{", "abbreviation", ":", "jsonInfo", ".", "stateAbbreviation", ",", "name", ":", "jsonInfo", ".", "stateName", "}", ",", "postCode", ":", "jsonInfo", ".", "postcode", ",", "location", ":", "{", "latitude", ":", "jsonInfo", ".", "location", ".", "lat", ",", "longitude", ":", "jsonInfo", ".", "location", ".", "lon", "}", "}", ";", "}" ]
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"] = processAddress(searchTerm); } return requestData; }
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"] = processAddress(searchTerm); } return requestData; }
[ "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\"", "]", "=", "processAddress", "(", "searchTerm", ")", ";", "}", "return", "requestData", ";", "}" ]
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", "(", "rectangle", ".", "east", ")", ",", "maxLat", ":", "CesiumMath", ".", "toDegrees", "(", "rectangle", ".", "north", ")", ",", "minLon", ":", "CesiumMath", ".", "toDegrees", "(", "rectangle", ".", "west", ")", "}", ";", "}" ]
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; } arrayBatches.push(arrayToSplit.slice(minSlice, maxSlice)); minSlice = maxSlice; if (finish) { break; } } return arrayBatches; }
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; } arrayBatches.push(arrayToSplit.slice(minSlice, maxSlice)); minSlice = maxSlice; if (finish) { break; } } return arrayBatches; }
[ "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", ";", "}", "arrayBatches", ".", "push", "(", "arrayToSplit", ".", "slice", "(", "minSlice", ",", "maxSlice", ")", ")", ";", "minSlice", "=", "maxSlice", ";", "if", "(", "finish", ")", "{", "break", ";", "}", "}", "return", "arrayBatches", ";", "}" ]
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.org result = false; return result; } var canvas = document.createElement("canvas"); var webglOptions = { alpha: false, stencil: false, failIfMajorPerformanceCaveat: true }; var gl = canvas.getContext("webgl", webglOptions) || canvas.getContext("experimental-webgl", webglOptions); if (!gl) { // We couldn't get a WebGL context without a major performance caveat. Let's see if we can get one at all. webglOptions.failIfMajorPerformanceCaveat = false; gl = canvas.getContext("webgl", webglOptions) || canvas.getContext("experimental-webgl", webglOptions); if (!gl) { // No WebGL at all. result = false; } else { // We can do WebGL, but only with software rendering (or similar). result = "slow"; } } else { // WebGL is good to go! result = true; } return result; }
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.org result = false; return result; } var canvas = document.createElement("canvas"); var webglOptions = { alpha: false, stencil: false, failIfMajorPerformanceCaveat: true }; var gl = canvas.getContext("webgl", webglOptions) || canvas.getContext("experimental-webgl", webglOptions); if (!gl) { // We couldn't get a WebGL context without a major performance caveat. Let's see if we can get one at all. webglOptions.failIfMajorPerformanceCaveat = false; gl = canvas.getContext("webgl", webglOptions) || canvas.getContext("experimental-webgl", webglOptions); if (!gl) { // No WebGL at all. result = false; } else { // We can do WebGL, but only with software rendering (or similar). result = "slow"; } } else { // WebGL is good to go! result = true; } return result; }
[ "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.org", "result", "=", "false", ";", "return", "result", ";", "}", "var", "canvas", "=", "document", ".", "createElement", "(", "\"canvas\"", ")", ";", "var", "webglOptions", "=", "{", "alpha", ":", "false", ",", "stencil", ":", "false", ",", "failIfMajorPerformanceCaveat", ":", "true", "}", ";", "var", "gl", "=", "canvas", ".", "getContext", "(", "\"webgl\"", ",", "webglOptions", ")", "||", "canvas", ".", "getContext", "(", "\"experimental-webgl\"", ",", "webglOptions", ")", ";", "if", "(", "!", "gl", ")", "{", "// We couldn't get a WebGL context without a major performance caveat. Let's see if we can get one at all.", "webglOptions", ".", "failIfMajorPerformanceCaveat", "=", "false", ";", "gl", "=", "canvas", ".", "getContext", "(", "\"webgl\"", ",", "webglOptions", ")", "||", "canvas", ".", "getContext", "(", "\"experimental-webgl\"", ",", "webglOptions", ")", ";", "if", "(", "!", "gl", ")", "{", "// No WebGL at all.", "result", "=", "false", ";", "}", "else", "{", "// We can do WebGL, but only with software rendering (or similar).", "result", "=", "\"slow\"", ";", "}", "}", "else", "{", "// WebGL is good to go!", "result", "=", "true", ";", "}", "return", "result", ";", "}" ]
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", "(", "catalogMember", ".", "parent", ",", "parentIds", ".", "concat", "(", "[", "catalogMember", ".", "uniqueId", "]", ")", ")", ";", "}", "return", "parentIds", ";", "}" ]
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.addEventListener( dataChanged.bind(null, item), item ); // Activate a column. This needed to wait until we had a dataSource, so it can trigger the legendHelper build. item.activateColumnFromTableStyle(); ensureActiveColumn(tableStructure, item._tableStyle); item.startPolling(); return when(true); // We're done - nothing to wait for. }
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.addEventListener( dataChanged.bind(null, item), item ); // Activate a column. This needed to wait until we had a dataSource, so it can trigger the legendHelper build. item.activateColumnFromTableStyle(); ensureActiveColumn(tableStructure, item._tableStyle); item.startPolling(); return when(true); // We're done - nothing to wait for. }
[ "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", ".", "addEventListener", "(", "dataChanged", ".", "bind", "(", "null", ",", "item", ")", ",", "item", ")", ";", "// Activate a column. This needed to wait until we had a dataSource, so it can trigger the legendHelper build.", "item", ".", "activateColumnFromTableStyle", "(", ")", ";", "ensureActiveColumn", "(", "tableStructure", ",", "item", ".", "_tableStyle", ")", ";", "item", ".", "startPolling", "(", ")", ";", "return", "when", "(", "true", ")", ";", "// We're done - nothing to wait for.", "}" ]
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; /** * Gets the {@link LeafletDataSourceDisplay} used to render a {@link DataSource}. * @type {LeafletDataSourceDisplay} */ this.dataSourceDisplay = undefined; this._tweens = new TweenCollection(); this._tweensAreRunning = false; this._selectionIndicatorTween = undefined; this._selectionIndicatorIsAppearing = undefined; this._pickedFeatures = undefined; this._selectionIndicator = L.marker([0, 0], { icon: L.divIcon({ className: "", html: '<img src="' + selectionIndicatorUrl + '" width="50" height="50" alt="" />', iconSize: L.point(50, 50) }), zIndexOffset: 1, // We increment the z index so that the selection marker appears above the item. interactive: false, keyboard: false }); this._selectionIndicator.addTo(this.map); this._selectionIndicatorDomElement = this._selectionIndicator._icon.children[0]; this._dragboxcompleted = false; this._pauseMapInteractionCount = 0; this.scene.featureClicked.addEventListener( featurePicked.bind(undefined, this) ); var that = this; // if we receive dragboxend (see LeafletDragBox) and we are currently // accepting a rectangle, then return the box as the picked feature map.on("dragboxend", function(e) { var mapInteractionModeStack = that.terria.mapInteractionModeStack; if ( defined(mapInteractionModeStack) && mapInteractionModeStack.length > 0 ) { if ( mapInteractionModeStack[mapInteractionModeStack.length - 1] .drawRectangle && defined(e.dragBoxBounds) ) { var b = e.dragBoxBounds; mapInteractionModeStack[ mapInteractionModeStack.length - 1 ].pickedFeatures = Rectangle.fromDegrees( b.getWest(), b.getSouth(), b.getEast(), b.getNorth() ); } } that._dragboxcompleted = true; }); map.on("click", function(e) { if (!that._dragboxcompleted && that.map.dragging.enabled()) { pickFeatures(that, e.latlng); } that._dragboxcompleted = false; }); this._selectedFeatureSubscription = knockout .getObservable(this.terria, "selectedFeature") .subscribe(function() { selectFeature(this); }, this); this._splitterPositionSubscription = knockout .getObservable(this.terria, "splitPosition") .subscribe(function() { this.updateAllItemsForSplitter(); }, this); this._showSplitterSubscription = knockout .getObservable(terria, "showSplitter") .subscribe(function() { this.updateAllItemsForSplitter(); }, this); map.on("layeradd", function(e) { that.updateAllItemsForSplitter(); }); map.on("move", function(e) { that.updateAllItemsForSplitter(); }); this._initProgressEvent(); selectFeature(this); }
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; /** * Gets the {@link LeafletDataSourceDisplay} used to render a {@link DataSource}. * @type {LeafletDataSourceDisplay} */ this.dataSourceDisplay = undefined; this._tweens = new TweenCollection(); this._tweensAreRunning = false; this._selectionIndicatorTween = undefined; this._selectionIndicatorIsAppearing = undefined; this._pickedFeatures = undefined; this._selectionIndicator = L.marker([0, 0], { icon: L.divIcon({ className: "", html: '<img src="' + selectionIndicatorUrl + '" width="50" height="50" alt="" />', iconSize: L.point(50, 50) }), zIndexOffset: 1, // We increment the z index so that the selection marker appears above the item. interactive: false, keyboard: false }); this._selectionIndicator.addTo(this.map); this._selectionIndicatorDomElement = this._selectionIndicator._icon.children[0]; this._dragboxcompleted = false; this._pauseMapInteractionCount = 0; this.scene.featureClicked.addEventListener( featurePicked.bind(undefined, this) ); var that = this; // if we receive dragboxend (see LeafletDragBox) and we are currently // accepting a rectangle, then return the box as the picked feature map.on("dragboxend", function(e) { var mapInteractionModeStack = that.terria.mapInteractionModeStack; if ( defined(mapInteractionModeStack) && mapInteractionModeStack.length > 0 ) { if ( mapInteractionModeStack[mapInteractionModeStack.length - 1] .drawRectangle && defined(e.dragBoxBounds) ) { var b = e.dragBoxBounds; mapInteractionModeStack[ mapInteractionModeStack.length - 1 ].pickedFeatures = Rectangle.fromDegrees( b.getWest(), b.getSouth(), b.getEast(), b.getNorth() ); } } that._dragboxcompleted = true; }); map.on("click", function(e) { if (!that._dragboxcompleted && that.map.dragging.enabled()) { pickFeatures(that, e.latlng); } that._dragboxcompleted = false; }); this._selectedFeatureSubscription = knockout .getObservable(this.terria, "selectedFeature") .subscribe(function() { selectFeature(this); }, this); this._splitterPositionSubscription = knockout .getObservable(this.terria, "splitPosition") .subscribe(function() { this.updateAllItemsForSplitter(); }, this); this._showSplitterSubscription = knockout .getObservable(terria, "showSplitter") .subscribe(function() { this.updateAllItemsForSplitter(); }, this); map.on("layeradd", function(e) { that.updateAllItemsForSplitter(); }); map.on("move", function(e) { that.updateAllItemsForSplitter(); }); this._initProgressEvent(); selectFeature(this); }
[ "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", "=", "new", "LeafletScene", "(", "map", ")", ";", "/**\n * Gets or sets whether this viewer _can_ show a splitter.\n * @type {Boolean}\n */", "this", ".", "canShowSplitter", "=", "true", ";", "/**\n * Gets the {@link LeafletDataSourceDisplay} used to render a {@link DataSource}.\n * @type {LeafletDataSourceDisplay}\n */", "this", ".", "dataSourceDisplay", "=", "undefined", ";", "this", ".", "_tweens", "=", "new", "TweenCollection", "(", ")", ";", "this", ".", "_tweensAreRunning", "=", "false", ";", "this", ".", "_selectionIndicatorTween", "=", "undefined", ";", "this", ".", "_selectionIndicatorIsAppearing", "=", "undefined", ";", "this", ".", "_pickedFeatures", "=", "undefined", ";", "this", ".", "_selectionIndicator", "=", "L", ".", "marker", "(", "[", "0", ",", "0", "]", ",", "{", "icon", ":", "L", ".", "divIcon", "(", "{", "className", ":", "\"\"", ",", "html", ":", "'<img src=\"'", "+", "selectionIndicatorUrl", "+", "'\" width=\"50\" height=\"50\" alt=\"\" />'", ",", "iconSize", ":", "L", ".", "point", "(", "50", ",", "50", ")", "}", ")", ",", "zIndexOffset", ":", "1", ",", "// We increment the z index so that the selection marker appears above the item.", "interactive", ":", "false", ",", "keyboard", ":", "false", "}", ")", ";", "this", ".", "_selectionIndicator", ".", "addTo", "(", "this", ".", "map", ")", ";", "this", ".", "_selectionIndicatorDomElement", "=", "this", ".", "_selectionIndicator", ".", "_icon", ".", "children", "[", "0", "]", ";", "this", ".", "_dragboxcompleted", "=", "false", ";", "this", ".", "_pauseMapInteractionCount", "=", "0", ";", "this", ".", "scene", ".", "featureClicked", ".", "addEventListener", "(", "featurePicked", ".", "bind", "(", "undefined", ",", "this", ")", ")", ";", "var", "that", "=", "this", ";", "// if we receive dragboxend (see LeafletDragBox) and we are currently", "// accepting a rectangle, then return the box as the picked feature", "map", ".", "on", "(", "\"dragboxend\"", ",", "function", "(", "e", ")", "{", "var", "mapInteractionModeStack", "=", "that", ".", "terria", ".", "mapInteractionModeStack", ";", "if", "(", "defined", "(", "mapInteractionModeStack", ")", "&&", "mapInteractionModeStack", ".", "length", ">", "0", ")", "{", "if", "(", "mapInteractionModeStack", "[", "mapInteractionModeStack", ".", "length", "-", "1", "]", ".", "drawRectangle", "&&", "defined", "(", "e", ".", "dragBoxBounds", ")", ")", "{", "var", "b", "=", "e", ".", "dragBoxBounds", ";", "mapInteractionModeStack", "[", "mapInteractionModeStack", ".", "length", "-", "1", "]", ".", "pickedFeatures", "=", "Rectangle", ".", "fromDegrees", "(", "b", ".", "getWest", "(", ")", ",", "b", ".", "getSouth", "(", ")", ",", "b", ".", "getEast", "(", ")", ",", "b", ".", "getNorth", "(", ")", ")", ";", "}", "}", "that", ".", "_dragboxcompleted", "=", "true", ";", "}", ")", ";", "map", ".", "on", "(", "\"click\"", ",", "function", "(", "e", ")", "{", "if", "(", "!", "that", ".", "_dragboxcompleted", "&&", "that", ".", "map", ".", "dragging", ".", "enabled", "(", ")", ")", "{", "pickFeatures", "(", "that", ",", "e", ".", "latlng", ")", ";", "}", "that", ".", "_dragboxcompleted", "=", "false", ";", "}", ")", ";", "this", ".", "_selectedFeatureSubscription", "=", "knockout", ".", "getObservable", "(", "this", ".", "terria", ",", "\"selectedFeature\"", ")", ".", "subscribe", "(", "function", "(", ")", "{", "selectFeature", "(", "this", ")", ";", "}", ",", "this", ")", ";", "this", ".", "_splitterPositionSubscription", "=", "knockout", ".", "getObservable", "(", "this", ".", "terria", ",", "\"splitPosition\"", ")", ".", "subscribe", "(", "function", "(", ")", "{", "this", ".", "updateAllItemsForSplitter", "(", ")", ";", "}", ",", "this", ")", ";", "this", ".", "_showSplitterSubscription", "=", "knockout", ".", "getObservable", "(", "terria", ",", "\"showSplitter\"", ")", ".", "subscribe", "(", "function", "(", ")", "{", "this", ".", "updateAllItemsForSplitter", "(", ")", ";", "}", ",", "this", ")", ";", "map", ".", "on", "(", "\"layeradd\"", ",", "function", "(", "e", ")", "{", "that", ".", "updateAllItemsForSplitter", "(", ")", ";", "}", ")", ";", "map", ".", "on", "(", "\"move\"", ",", "function", "(", "e", ")", "{", "that", ".", "updateAllItemsForSplitter", "(", ")", ";", "}", ")", ";", "this", ".", "_initProgressEvent", "(", ")", ";", "selectFeature", "(", "this", ")", ";", "}" ]
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", ".", "supportsReordering", ")", "{", "item", ".", "imageryLayer", ".", "setZIndex", "(", "currZIndex", ".", "reorderable", "++", ")", ";", "}", "else", "{", "item", ".", "imageryLayer", ".", "setZIndex", "(", "currZIndex", ".", "fixed", "++", ")", ";", "}", "}", "}" ]
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 ); updateSplitDirection(catalogItem); ImageryLayerCatalogItem.showLayer(catalogItem, catalogItem._nextLayer); }
javascript
function nextLayerFromIndex(index) { const imageryProvider = catalogItem.createImageryProvider( catalogItem.intervals.get(index).data ); imageryProvider.enablePickFeatures = false; catalogItem._nextLayer = ImageryLayerCatalogItem.enableLayer( catalogItem, imageryProvider, 0.0 ); updateSplitDirection(catalogItem); ImageryLayerCatalogItem.showLayer(catalogItem, catalogItem._nextLayer); }
[ "function", "nextLayerFromIndex", "(", "index", ")", "{", "const", "imageryProvider", "=", "catalogItem", ".", "createImageryProvider", "(", "catalogItem", ".", "intervals", ".", "get", "(", "index", ")", ".", "data", ")", ";", "imageryProvider", ".", "enablePickFeatures", "=", "false", ";", "catalogItem", ".", "_nextLayer", "=", "ImageryLayerCatalogItem", ".", "enableLayer", "(", "catalogItem", ",", "imageryProvider", ",", "0.0", ")", ";", "updateSplitDirection", "(", "catalogItem", ")", ";", "ImageryLayerCatalogItem", ".", "showLayer", "(", "catalogItem", ",", "catalogItem", ".", "_nextLayer", ")", ";", "}" ]
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, itemData, extras, parent ); if (item) { parent.add(item); } } return item; }
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, itemData, extras, parent ); if (item) { parent.add(item); } } return item; }
[ "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", ",", "itemData", ",", "extras", ",", "parent", ")", ";", "if", "(", "item", ")", "{", "parent", ".", "add", "(", "item", ")", ";", "}", "}", "return", "item", ";", "}" ]
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 parent group to add the item to once it's constructed - set this to rootCkanGroup for flat hierarchies. @returns {CatalogItem} The catalog item added, or undefined if no catalog item was added.
[ "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(subFeatureData) { return getEsriGeometry(subFeatureData, geometryType); }) }; } var geoJsonFeature = { type: "Feature", geometry: undefined, properties: featureData.attributes }; if (defined(spatialReference)) { geoJsonFeature.crs = esriSpatialReferenceToCrs(spatialReference); } if (geometryType === "esriGeometryPolygon") { // There are a bunch of differences between Esri polygons and GeoJSON polygons. // For GeoJSON, see https://tools.ietf.org/html/rfc7946#section-3.1.6. // For Esri, see http://resources.arcgis.com/en/help/arcgis-rest-api/#/Geometry_objects/02r3000000n1000000/ // In particular: // 1. Esri polygons can actually be multiple polygons by using multiple outer rings. GeoJSON polygons // can only have one outer ring and we need to use a MultiPolygon to represent multiple outer rings. // 2. In Esri which rings are outer rings and which are holes is determined by the winding order of the // rings. In GeoJSON, the first ring is the outer ring and subsequent rings are holes. // 3. In Esri polygons, clockwise rings are exterior, counter-clockwise are interior. In GeoJSON, the first // (exterior) ring is expected to be counter-clockwise, though lots of implementations probably don't // enforce this. The spec says, "For backwards compatibility, parsers SHOULD NOT reject // Polygons that do not follow the right-hand rule." // Group rings into outer rings and holes/ const outerRings = []; const holes = []; featureData.geometry.rings.forEach(function(ring) { if ( computeRingWindingOrder(ring.map(p => new Point(...p))) === WindingOrder.CLOCKWISE ) { outerRings.push(ring); } else { holes.push(ring); } // Reverse the coordinate order along the way due to #3 above. ring.reverse(); }); if (outerRings.length === 0 && holes.length > 0) { // Well, this is pretty weird. We have holes but not outer ring? // Most likely scenario is that someone messed up the winding order. // So let's treat all the holes as outer rings instead. holes.forEach(hole => { hole.reverse(); }); outerRings.push(...holes); holes.length = 0; } // If there's only one outer ring, we can use a `Polygon` and things are simple. if (outerRings.length === 1) { geoJsonFeature.geometry = { type: "Polygon", coordinates: [outerRings[0], ...holes] }; } else { // Multiple (or zero!) outer rings, so we need to use a multipolygon, and we need // to figure out which outer ring contains each hole. geoJsonFeature.geometry = { type: "MultiPolygon", coordinates: outerRings.map(ring => [ ring, ...findHolesInRing(ring, holes) ]) }; } } else if (geometryType === "esriGeometryPoint") { geoJsonFeature.geometry = { type: "Point", coordinates: [featureData.geometry.x, featureData.geometry.y] }; } else if (geometryType === "esriGeometryPolyline") { geoJsonFeature.geometry = { type: "MultiLineString", coordinates: featureData.geometry.paths }; } else { return undefined; } return geoJsonFeature; }
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(subFeatureData) { return getEsriGeometry(subFeatureData, geometryType); }) }; } var geoJsonFeature = { type: "Feature", geometry: undefined, properties: featureData.attributes }; if (defined(spatialReference)) { geoJsonFeature.crs = esriSpatialReferenceToCrs(spatialReference); } if (geometryType === "esriGeometryPolygon") { // There are a bunch of differences between Esri polygons and GeoJSON polygons. // For GeoJSON, see https://tools.ietf.org/html/rfc7946#section-3.1.6. // For Esri, see http://resources.arcgis.com/en/help/arcgis-rest-api/#/Geometry_objects/02r3000000n1000000/ // In particular: // 1. Esri polygons can actually be multiple polygons by using multiple outer rings. GeoJSON polygons // can only have one outer ring and we need to use a MultiPolygon to represent multiple outer rings. // 2. In Esri which rings are outer rings and which are holes is determined by the winding order of the // rings. In GeoJSON, the first ring is the outer ring and subsequent rings are holes. // 3. In Esri polygons, clockwise rings are exterior, counter-clockwise are interior. In GeoJSON, the first // (exterior) ring is expected to be counter-clockwise, though lots of implementations probably don't // enforce this. The spec says, "For backwards compatibility, parsers SHOULD NOT reject // Polygons that do not follow the right-hand rule." // Group rings into outer rings and holes/ const outerRings = []; const holes = []; featureData.geometry.rings.forEach(function(ring) { if ( computeRingWindingOrder(ring.map(p => new Point(...p))) === WindingOrder.CLOCKWISE ) { outerRings.push(ring); } else { holes.push(ring); } // Reverse the coordinate order along the way due to #3 above. ring.reverse(); }); if (outerRings.length === 0 && holes.length > 0) { // Well, this is pretty weird. We have holes but not outer ring? // Most likely scenario is that someone messed up the winding order. // So let's treat all the holes as outer rings instead. holes.forEach(hole => { hole.reverse(); }); outerRings.push(...holes); holes.length = 0; } // If there's only one outer ring, we can use a `Polygon` and things are simple. if (outerRings.length === 1) { geoJsonFeature.geometry = { type: "Polygon", coordinates: [outerRings[0], ...holes] }; } else { // Multiple (or zero!) outer rings, so we need to use a multipolygon, and we need // to figure out which outer ring contains each hole. geoJsonFeature.geometry = { type: "MultiPolygon", coordinates: outerRings.map(ring => [ ring, ...findHolesInRing(ring, holes) ]) }; } } else if (geometryType === "esriGeometryPoint") { geoJsonFeature.geometry = { type: "Point", coordinates: [featureData.geometry.x, featureData.geometry.y] }; } else if (geometryType === "esriGeometryPolyline") { geoJsonFeature.geometry = { type: "MultiLineString", coordinates: featureData.geometry.paths }; } else { return undefined; } return geoJsonFeature; }
[ "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", "(", "subFeatureData", ")", "{", "return", "getEsriGeometry", "(", "subFeatureData", ",", "geometryType", ")", ";", "}", ")", "}", ";", "}", "var", "geoJsonFeature", "=", "{", "type", ":", "\"Feature\"", ",", "geometry", ":", "undefined", ",", "properties", ":", "featureData", ".", "attributes", "}", ";", "if", "(", "defined", "(", "spatialReference", ")", ")", "{", "geoJsonFeature", ".", "crs", "=", "esriSpatialReferenceToCrs", "(", "spatialReference", ")", ";", "}", "if", "(", "geometryType", "===", "\"esriGeometryPolygon\"", ")", "{", "// There are a bunch of differences between Esri polygons and GeoJSON polygons.", "// For GeoJSON, see https://tools.ietf.org/html/rfc7946#section-3.1.6.", "// For Esri, see http://resources.arcgis.com/en/help/arcgis-rest-api/#/Geometry_objects/02r3000000n1000000/", "// In particular:", "// 1. Esri polygons can actually be multiple polygons by using multiple outer rings. GeoJSON polygons", "// can only have one outer ring and we need to use a MultiPolygon to represent multiple outer rings.", "// 2. In Esri which rings are outer rings and which are holes is determined by the winding order of the", "// rings. In GeoJSON, the first ring is the outer ring and subsequent rings are holes.", "// 3. In Esri polygons, clockwise rings are exterior, counter-clockwise are interior. In GeoJSON, the first", "// (exterior) ring is expected to be counter-clockwise, though lots of implementations probably don't", "// enforce this. The spec says, \"For backwards compatibility, parsers SHOULD NOT reject", "// Polygons that do not follow the right-hand rule.\"", "// Group rings into outer rings and holes/", "const", "outerRings", "=", "[", "]", ";", "const", "holes", "=", "[", "]", ";", "featureData", ".", "geometry", ".", "rings", ".", "forEach", "(", "function", "(", "ring", ")", "{", "if", "(", "computeRingWindingOrder", "(", "ring", ".", "map", "(", "p", "=>", "new", "Point", "(", "...", "p", ")", ")", ")", "===", "WindingOrder", ".", "CLOCKWISE", ")", "{", "outerRings", ".", "push", "(", "ring", ")", ";", "}", "else", "{", "holes", ".", "push", "(", "ring", ")", ";", "}", "// Reverse the coordinate order along the way due to #3 above.", "ring", ".", "reverse", "(", ")", ";", "}", ")", ";", "if", "(", "outerRings", ".", "length", "===", "0", "&&", "holes", ".", "length", ">", "0", ")", "{", "// Well, this is pretty weird. We have holes but not outer ring?", "// Most likely scenario is that someone messed up the winding order.", "// So let's treat all the holes as outer rings instead.", "holes", ".", "forEach", "(", "hole", "=>", "{", "hole", ".", "reverse", "(", ")", ";", "}", ")", ";", "outerRings", ".", "push", "(", "...", "holes", ")", ";", "holes", ".", "length", "=", "0", ";", "}", "// If there's only one outer ring, we can use a `Polygon` and things are simple.", "if", "(", "outerRings", ".", "length", "===", "1", ")", "{", "geoJsonFeature", ".", "geometry", "=", "{", "type", ":", "\"Polygon\"", ",", "coordinates", ":", "[", "outerRings", "[", "0", "]", ",", "...", "holes", "]", "}", ";", "}", "else", "{", "// Multiple (or zero!) outer rings, so we need to use a multipolygon, and we need", "// to figure out which outer ring contains each hole.", "geoJsonFeature", ".", "geometry", "=", "{", "type", ":", "\"MultiPolygon\"", ",", "coordinates", ":", "outerRings", ".", "map", "(", "ring", "=>", "[", "ring", ",", "...", "findHolesInRing", "(", "ring", ",", "holes", ")", "]", ")", "}", ";", "}", "}", "else", "if", "(", "geometryType", "===", "\"esriGeometryPoint\"", ")", "{", "geoJsonFeature", ".", "geometry", "=", "{", "type", ":", "\"Point\"", ",", "coordinates", ":", "[", "featureData", ".", "geometry", ".", "x", ",", "featureData", ".", "geometry", ".", "y", "]", "}", ";", "}", "else", "if", "(", "geometryType", "===", "\"esriGeometryPolyline\"", ")", "{", "geoJsonFeature", ".", "geometry", "=", "{", "type", ":", "\"MultiLineString\"", ",", "coordinates", ":", "featureData", ".", "geometry", ".", "paths", "}", ";", "}", "else", "{", "return", "undefined", ";", "}", "return", "geoJsonFeature", ";", "}" ]
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) { _resolveInputConflicts(element, tool, options, interactionTypes); // Iterate over specific interaction types and set active // This is used as a secondary check on active tools to find the active "parts" of the tool tool.supportedInteractionTypes.forEach(interactionType => { if ( interactionTypes === undefined || interactionTypes.includes(interactionType) ) { options[`is${interactionType}Active`] = true; } else { options[`is${interactionType}Active`] = false; } }); if ( globalConfiguration.state.showSVGCursors && tool.supportedInteractionTypes.includes('Mouse') ) { _setToolCursorIfPrimary(element, options, tool); } } // Resume normal behavior setToolModeForElement('active', null, element, toolName, options); }
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) { _resolveInputConflicts(element, tool, options, interactionTypes); // Iterate over specific interaction types and set active // This is used as a secondary check on active tools to find the active "parts" of the tool tool.supportedInteractionTypes.forEach(interactionType => { if ( interactionTypes === undefined || interactionTypes.includes(interactionType) ) { options[`is${interactionType}Active`] = true; } else { options[`is${interactionType}Active`] = false; } }); if ( globalConfiguration.state.showSVGCursors && tool.supportedInteractionTypes.includes('Mouse') ) { _setToolCursorIfPrimary(element, options, tool); } } // Resume normal behavior setToolModeForElement('active', null, element, toolName, options); }
[ "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", ")", "{", "_resolveInputConflicts", "(", "element", ",", "tool", ",", "options", ",", "interactionTypes", ")", ";", "// Iterate over specific interaction types and set active", "// This is used as a secondary check on active tools to find the active \"parts\" of the tool", "tool", ".", "supportedInteractionTypes", ".", "forEach", "(", "interactionType", "=>", "{", "if", "(", "interactionTypes", "===", "undefined", "||", "interactionTypes", ".", "includes", "(", "interactionType", ")", ")", "{", "options", "[", "`", "${", "interactionType", "}", "`", "]", "=", "true", ";", "}", "else", "{", "options", "[", "`", "${", "interactionType", "}", "`", "]", "=", "false", ";", "}", "}", ")", ";", "if", "(", "globalConfiguration", ".", "state", ".", "showSVGCursors", "&&", "tool", ".", "supportedInteractionTypes", ".", "includes", "(", "'Mouse'", ")", ")", "{", "_setToolCursorIfPrimary", "(", "element", ",", "options", ",", "tool", ")", ";", "}", "}", "// Resume normal behavior", "setToolModeForElement", "(", "'active'", ",", "null", ",", "element", ",", "toolName", ",", "options", ")", ";", "}" ]
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 tool to Active setToolActiveForElement(element, 'Length', { mouseButtonMask: 1 }, ['Mouse']) @example <caption>Setting a tool 'active' for all interaction types.</caption> // Sets length tool to Active setToolActiveForElement(element, 'Length', { mouseButtonMask: 1 }) @param {HTMLElement} element @param {string} toolName @param {(Object|string[]|number)} options @param {(string[])} interactionTypes @returns {undefined}
[ "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[interactionTypeFlag] === true ); if (activeToolWithActiveInteractionType) { logger.log( "Setting tool %s's %s to false", activeToolWithActiveInteractionType.name, interactionTypeFlag ); activeToolWithActiveInteractionType.options[interactionTypeFlag] = false; } }
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[interactionTypeFlag] === true ); if (activeToolWithActiveInteractionType) { logger.log( "Setting tool %s's %s to false", activeToolWithActiveInteractionType.name, interactionTypeFlag ); activeToolWithActiveInteractionType.options[interactionTypeFlag] = false; } }
[ "function", "_resolveGenericInputConflicts", "(", "interactionType", ",", "tool", ",", "element", ",", "options", ")", "{", "const", "interactionTypeFlag", "=", "`", "${", "interactionType", "}", "`", ";", "const", "activeToolWithActiveInteractionType", "=", "store", ".", "state", ".", "tools", ".", "find", "(", "t", "=>", "t", ".", "element", "===", "element", "&&", "t", ".", "mode", "===", "'active'", "&&", "t", ".", "options", "[", "interactionTypeFlag", "]", "===", "true", ")", ";", "if", "(", "activeToolWithActiveInteractionType", ")", "{", "logger", ".", "log", "(", "\"Setting tool %s's %s to false\"", ",", "activeToolWithActiveInteractionType", ".", "name", ",", "interactionTypeFlag", ")", ";", "activeToolWithActiveInteractionType", ".", "options", "[", "interactionTypeFlag", "]", "=", "false", ";", "}", "}" ]
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 currentPoints = { page: external.cornerstoneMath.point.pageToPoint(e), image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY), client: { x: e.clientX, y: e.clientY, }, }; currentPoints.canvas = external.cornerstone.pixelToCanvas( element, currentPoints.image ); // Calculate delta values in page and image coordinates const deltaPoints = { page: external.cornerstoneMath.point.subtract( currentPoints.page, lastPoints.page ), image: external.cornerstoneMath.point.subtract( currentPoints.image, lastPoints.image ), client: external.cornerstoneMath.point.subtract( currentPoints.client, lastPoints.client ), canvas: external.cornerstoneMath.point.subtract( currentPoints.canvas, lastPoints.canvas ), }; logger.log('mouseup: %o', getEventButtons(e)); const eventData = { event: e, buttons: getEventButtons(e), viewport: external.cornerstone.getViewport(element), image: enabledElement.image, element, startPoints, lastPoints, currentPoints, deltaPoints, type: eventType, }; triggerEvent(eventData.element, eventType, eventData); document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); element.addEventListener('mousemove', mouseMove); isClickEvent = true; }
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 currentPoints = { page: external.cornerstoneMath.point.pageToPoint(e), image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY), client: { x: e.clientX, y: e.clientY, }, }; currentPoints.canvas = external.cornerstone.pixelToCanvas( element, currentPoints.image ); // Calculate delta values in page and image coordinates const deltaPoints = { page: external.cornerstoneMath.point.subtract( currentPoints.page, lastPoints.page ), image: external.cornerstoneMath.point.subtract( currentPoints.image, lastPoints.image ), client: external.cornerstoneMath.point.subtract( currentPoints.client, lastPoints.client ), canvas: external.cornerstoneMath.point.subtract( currentPoints.canvas, lastPoints.canvas ), }; logger.log('mouseup: %o', getEventButtons(e)); const eventData = { event: e, buttons: getEventButtons(e), viewport: external.cornerstone.getViewport(element), image: enabledElement.image, element, startPoints, lastPoints, currentPoints, deltaPoints, type: eventType, }; triggerEvent(eventData.element, eventType, eventData); document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); element.addEventListener('mousemove', mouseMove); isClickEvent = true; }
[ "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", "currentPoints", "=", "{", "page", ":", "external", ".", "cornerstoneMath", ".", "point", ".", "pageToPoint", "(", "e", ")", ",", "image", ":", "external", ".", "cornerstone", ".", "pageToPixel", "(", "element", ",", "e", ".", "pageX", ",", "e", ".", "pageY", ")", ",", "client", ":", "{", "x", ":", "e", ".", "clientX", ",", "y", ":", "e", ".", "clientY", ",", "}", ",", "}", ";", "currentPoints", ".", "canvas", "=", "external", ".", "cornerstone", ".", "pixelToCanvas", "(", "element", ",", "currentPoints", ".", "image", ")", ";", "// Calculate delta values in page and image coordinates", "const", "deltaPoints", "=", "{", "page", ":", "external", ".", "cornerstoneMath", ".", "point", ".", "subtract", "(", "currentPoints", ".", "page", ",", "lastPoints", ".", "page", ")", ",", "image", ":", "external", ".", "cornerstoneMath", ".", "point", ".", "subtract", "(", "currentPoints", ".", "image", ",", "lastPoints", ".", "image", ")", ",", "client", ":", "external", ".", "cornerstoneMath", ".", "point", ".", "subtract", "(", "currentPoints", ".", "client", ",", "lastPoints", ".", "client", ")", ",", "canvas", ":", "external", ".", "cornerstoneMath", ".", "point", ".", "subtract", "(", "currentPoints", ".", "canvas", ",", "lastPoints", ".", "canvas", ")", ",", "}", ";", "logger", ".", "log", "(", "'mouseup: %o'", ",", "getEventButtons", "(", "e", ")", ")", ";", "const", "eventData", "=", "{", "event", ":", "e", ",", "buttons", ":", "getEventButtons", "(", "e", ")", ",", "viewport", ":", "external", ".", "cornerstone", ".", "getViewport", "(", "element", ")", ",", "image", ":", "enabledElement", ".", "image", ",", "element", ",", "startPoints", ",", "lastPoints", ",", "currentPoints", ",", "deltaPoints", ",", "type", ":", "eventType", ",", "}", ";", "triggerEvent", "(", "eventData", ".", "element", ",", "eventType", ",", "eventData", ")", ";", "document", ".", "removeEventListener", "(", "'mousemove'", ",", "onMouseMove", ")", ";", "document", ".", "removeEventListener", "(", "'mouseup'", ",", "onMouseUp", ")", ";", "element", ".", "addEventListener", "(", "'mousemove'", ",", "mouseMove", ")", ";", "isClickEvent", "=", "true", ";", "}" ]
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 not found", "stackPrefetch", ".", "indicesToRequest", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "}" ]
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.imageId]; }
javascript
function clearImageIdSpecificToolStateManager(element) { const enabledElement = external.cornerstone.getEnabledElement(element); if ( !enabledElement.image || toolState.hasOwnProperty(enabledElement.image.imageId) === false ) { return; } delete toolState[enabledElement.image.imageId]; }
[ "function", "clearImageIdSpecificToolStateManager", "(", "element", ")", "{", "const", "enabledElement", "=", "external", ".", "cornerstone", ".", "getEnabledElement", "(", "element", ")", ";", "if", "(", "!", "enabledElement", ".", "image", "||", "toolState", ".", "hasOwnProperty", "(", "enabledElement", ".", "image", ".", "imageId", ")", "===", "false", ")", "{", "return", ";", "}", "delete", "toolState", "[", "enabledElement", ".", "image", ".", "imageId", "]", ";", "}" ]
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", ".", "data", ".", "length", ")", "{", "return", ";", "}", "stopClipWithData", "(", "playClipToolData", ".", "data", "[", "0", "]", ")", ";", "}" ]
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.getColormap(state.colorMapId); const numberOfColors = colormap.getNumberOfColors(); // Remove enabledElement specific data. delete state.visibleSegmentations[enabledElementUID]; delete state.imageBitmapCache[enabledElementUID]; }
javascript
function removeEnabledElementCallback(enabledElement) { if (!external.cornerstone) { return; } const cornerstoneEnabledElement = external.cornerstone.getEnabledElement( enabledElement ); const enabledElementUID = cornerstoneEnabledElement.uuid; const colormap = external.cornerstone.colors.getColormap(state.colorMapId); const numberOfColors = colormap.getNumberOfColors(); // Remove enabledElement specific data. delete state.visibleSegmentations[enabledElementUID]; delete state.imageBitmapCache[enabledElementUID]; }
[ "function", "removeEnabledElementCallback", "(", "enabledElement", ")", "{", "if", "(", "!", "external", ".", "cornerstone", ")", "{", "return", ";", "}", "const", "cornerstoneEnabledElement", "=", "external", ".", "cornerstone", ".", "getEnabledElement", "(", "enabledElement", ")", ";", "const", "enabledElementUID", "=", "cornerstoneEnabledElement", ".", "uuid", ";", "const", "colormap", "=", "external", ".", "cornerstone", ".", "colors", ".", "getColormap", "(", "state", ".", "colorMapId", ")", ";", "const", "numberOfColors", "=", "colormap", ".", "getNumberOfColors", "(", ")", ";", "// Remove enabledElement specific data.", "delete", "state", ".", "visibleSegmentations", "[", "enabledElementUID", "]", ";", "delete", "state", ".", "imageBitmapCache", "[", "enabledElementUID", "]", ";", "}" ]
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", "(", "colorPairIndex", ")", ";", "}", "else", "{", "colorPairIndex", "=", "0", ";", "indexPair", ".", "push", "(", "colorPairIndex", ")", ";", "}", "return", "indexPair", ";", "}" ]
_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", ".", "filter", "(", "tool", "=>", "tool", ".", "element", "!==", "enabledElement", ")", ";", "}" ]
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 { logger.warn('unable to remove element'); } }
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 { logger.warn('unable to remove element'); } }
[ "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", "{", "logger", ".", "warn", "(", "'unable to remove element'", ")", ";", "}", "}" ]
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", "[", "key", "]", ".", "removeEnabledElementCallback", "===", "'function'", ")", "{", "modules", "[", "key", "]", ".", "removeEnabledElementCallback", "(", "enabledElement", ")", ";", "}", "}", ")", ";", "}" ]
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.pixelToCanvas(eventData.element, { x: eventData.image.width, y: 0, }); const canvasBottomRight = external.cornerstone.pixelToCanvas( eventData.element, { x: eventData.image.width, y: eventData.image.height, } ); const cornerstoneCanvasWidth = external.cornerstoneMath.point.distance( canvasTopLeft, canvasTopRight ); const cornerstoneCanvasHeight = external.cornerstoneMath.point.distance( canvasTopRight, canvasBottomRight ); const canvas = eventData.canvasContext.canvas; const viewport = eventData.viewport; context.imageSmoothingEnabled = false; context.globalAlpha = getLayerAlpha(alwaysVisible); transformCanvasContext(context, canvas, viewport); const canvasViewportTranslation = { x: viewport.translation.x * viewport.scale, y: viewport.translation.y * viewport.scale, }; context.drawImage( imageBitmap, canvas.width / 2 - cornerstoneCanvasWidth / 2 + canvasViewportTranslation.x, canvas.height / 2 - cornerstoneCanvasHeight / 2 + canvasViewportTranslation.y, cornerstoneCanvasWidth, cornerstoneCanvasHeight ); context.globalAlpha = 1.0; resetCanvasContextTransform(context); }
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.pixelToCanvas(eventData.element, { x: eventData.image.width, y: 0, }); const canvasBottomRight = external.cornerstone.pixelToCanvas( eventData.element, { x: eventData.image.width, y: eventData.image.height, } ); const cornerstoneCanvasWidth = external.cornerstoneMath.point.distance( canvasTopLeft, canvasTopRight ); const cornerstoneCanvasHeight = external.cornerstoneMath.point.distance( canvasTopRight, canvasBottomRight ); const canvas = eventData.canvasContext.canvas; const viewport = eventData.viewport; context.imageSmoothingEnabled = false; context.globalAlpha = getLayerAlpha(alwaysVisible); transformCanvasContext(context, canvas, viewport); const canvasViewportTranslation = { x: viewport.translation.x * viewport.scale, y: viewport.translation.y * viewport.scale, }; context.drawImage( imageBitmap, canvas.width / 2 - cornerstoneCanvasWidth / 2 + canvasViewportTranslation.x, canvas.height / 2 - cornerstoneCanvasHeight / 2 + canvasViewportTranslation.y, cornerstoneCanvasWidth, cornerstoneCanvasHeight ); context.globalAlpha = 1.0; resetCanvasContextTransform(context); }
[ "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", ".", "pixelToCanvas", "(", "eventData", ".", "element", ",", "{", "x", ":", "eventData", ".", "image", ".", "width", ",", "y", ":", "0", ",", "}", ")", ";", "const", "canvasBottomRight", "=", "external", ".", "cornerstone", ".", "pixelToCanvas", "(", "eventData", ".", "element", ",", "{", "x", ":", "eventData", ".", "image", ".", "width", ",", "y", ":", "eventData", ".", "image", ".", "height", ",", "}", ")", ";", "const", "cornerstoneCanvasWidth", "=", "external", ".", "cornerstoneMath", ".", "point", ".", "distance", "(", "canvasTopLeft", ",", "canvasTopRight", ")", ";", "const", "cornerstoneCanvasHeight", "=", "external", ".", "cornerstoneMath", ".", "point", ".", "distance", "(", "canvasTopRight", ",", "canvasBottomRight", ")", ";", "const", "canvas", "=", "eventData", ".", "canvasContext", ".", "canvas", ";", "const", "viewport", "=", "eventData", ".", "viewport", ";", "context", ".", "imageSmoothingEnabled", "=", "false", ";", "context", ".", "globalAlpha", "=", "getLayerAlpha", "(", "alwaysVisible", ")", ";", "transformCanvasContext", "(", "context", ",", "canvas", ",", "viewport", ")", ";", "const", "canvasViewportTranslation", "=", "{", "x", ":", "viewport", ".", "translation", ".", "x", "*", "viewport", ".", "scale", ",", "y", ":", "viewport", ".", "translation", ".", "y", "*", "viewport", ".", "scale", ",", "}", ";", "context", ".", "drawImage", "(", "imageBitmap", ",", "canvas", ".", "width", "/", "2", "-", "cornerstoneCanvasWidth", "/", "2", "+", "canvasViewportTranslation", ".", "x", ",", "canvas", ".", "height", "/", "2", "-", "cornerstoneCanvasHeight", "/", "2", "+", "canvasViewportTranslation", ".", "y", ",", "cornerstoneCanvasWidth", ",", "cornerstoneCanvasHeight", ")", ";", "context", ".", "globalAlpha", "=", "1.0", ";", "resetCanvasContextTransform", "(", "context", ")", ";", "}" ]
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.getToolColor(), /* --- Hover options --- showCursorOnHover: Shows a preview of the sculpting radius on hover. limitRadiusOutsideRegion: Limit max toolsize outside the subject ROI based on subject ROI area. hoverCursorFadeAlpha: Alpha to fade to when tool very distant from subject ROI. hoverCursorFadeDistance: Distance from ROI in which to fade the hoverCursor (in units of radii). */ showCursorOnHover: true, limitRadiusOutsideRegion: true, hoverCursorFadeAlpha: 0.5, hoverCursorFadeDistance: 1.2, }; }
javascript
function getDefaultFreehandSculpterMouseToolConfiguration() { return { mouseLocation: { handles: { start: { highlight: true, active: true, }, }, }, minSpacing: 1, currentTool: null, dragColor: toolColors.getActiveColor(), hoverColor: toolColors.getToolColor(), /* --- Hover options --- showCursorOnHover: Shows a preview of the sculpting radius on hover. limitRadiusOutsideRegion: Limit max toolsize outside the subject ROI based on subject ROI area. hoverCursorFadeAlpha: Alpha to fade to when tool very distant from subject ROI. hoverCursorFadeDistance: Distance from ROI in which to fade the hoverCursor (in units of radii). */ showCursorOnHover: true, limitRadiusOutsideRegion: true, hoverCursorFadeAlpha: 0.5, hoverCursorFadeDistance: 1.2, }; }
[ "function", "getDefaultFreehandSculpterMouseToolConfiguration", "(", ")", "{", "return", "{", "mouseLocation", ":", "{", "handles", ":", "{", "start", ":", "{", "highlight", ":", "true", ",", "active", ":", "true", ",", "}", ",", "}", ",", "}", ",", "minSpacing", ":", "1", ",", "currentTool", ":", "null", ",", "dragColor", ":", "toolColors", ".", "getActiveColor", "(", ")", ",", "hoverColor", ":", "toolColors", ".", "getToolColor", "(", ")", ",", "/* --- Hover options ---\n showCursorOnHover: Shows a preview of the sculpting radius on hover.\n limitRadiusOutsideRegion: Limit max toolsize outside the subject ROI based\n on subject ROI area.\n hoverCursorFadeAlpha: Alpha to fade to when tool very distant from\n subject ROI.\n hoverCursorFadeDistance: Distance from ROI in which to fade the hoverCursor\n (in units of radii).\n */", "showCursorOnHover", ":", "true", ",", "limitRadiusOutsideRegion", ":", "true", ",", "hoverCursorFadeAlpha", ":", "0.5", ",", "hoverCursorFadeDistance", ":", "1.2", ",", "}", ";", "}" ]
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 = svgCursor.getIconWithPointerSVG(); const mousePoint = svgCursor.mousePoint; const svgCursorUrl = window.URL.createObjectURL(cursorBlob); element.style.cursor = `url('${svgCursorUrl}') ${mousePoint}, auto`; state.svgCursorUrl = svgCursorUrl; }
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 = svgCursor.getIconWithPointerSVG(); const mousePoint = svgCursor.mousePoint; const svgCursorUrl = window.URL.createObjectURL(cursorBlob); element.style.cursor = `url('${svgCursorUrl}') ${mousePoint}, auto`; state.svgCursorUrl = svgCursorUrl; }
[ "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", "=", "svgCursor", ".", "getIconWithPointerSVG", "(", ")", ";", "const", "mousePoint", "=", "svgCursor", ".", "mousePoint", ";", "const", "svgCursorUrl", "=", "window", ".", "URL", ".", "createObjectURL", "(", "cursorBlob", ")", ";", "element", ".", "style", ".", "cursor", "=", "`", "${", "svgCursorUrl", "}", "${", "mousePoint", "}", "`", ";", "state", ".", "svgCursorUrl", "=", "svgCursorUrl", ";", "}" ]
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", ":", "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", ")", ")", ",", "}", ";", "}" ]
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", ")", ";", "}", "_addGlobalToolsToElement", "(", "enabledElement", ")", ";", "_repeatGlobalToolHistory", "(", "enabledElement", ")", ";", "}" ]
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", "[", "key", "]", ".", "enabledElementCallback", "===", "'function'", ")", "{", "modules", "[", "key", "]", ".", "enabledElementCallback", "(", "enabledElement", ")", ";", "}", "}", ")", ";", "}" ]
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, configuration); }); }
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, configuration); }); }
[ "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", ",", "configuration", ")", ";", "}", ")", ";", "}" ]
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: setToolDisabledForElement, }; store.state.globalToolChangeHistory.forEach(historyEvent => { const args = historyEvent.args.slice(0); args.unshift(enabledElement); setToolModeFns[historyEvent.mode].apply(null, args); }); }
javascript
function _repeatGlobalToolHistory(enabledElement) { if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) { return; } const setToolModeFns = { active: setToolActiveForElement, passive: setToolPassiveForElement, enabled: setToolEnabledForElement, disabled: setToolDisabledForElement, }; store.state.globalToolChangeHistory.forEach(historyEvent => { const args = historyEvent.args.slice(0); args.unshift(enabledElement); setToolModeFns[historyEvent.mode].apply(null, args); }); }
[ "function", "_repeatGlobalToolHistory", "(", "enabledElement", ")", "{", "if", "(", "!", "store", ".", "modules", ".", "globalConfiguration", ".", "state", ".", "globalToolSyncEnabled", ")", "{", "return", ";", "}", "const", "setToolModeFns", "=", "{", "active", ":", "setToolActiveForElement", ",", "passive", ":", "setToolPassiveForElement", ",", "enabled", ":", "setToolEnabledForElement", ",", "disabled", ":", "setToolDisabledForElement", ",", "}", ";", "store", ".", "state", ".", "globalToolChangeHistory", ".", "forEach", "(", "historyEvent", "=>", "{", "const", "args", "=", "historyEvent", ".", "args", ".", "slice", "(", "0", ")", ";", "args", ".", "unshift", "(", "enabledElement", ")", ";", "setToolModeFns", "[", "historyEvent", ".", "mode", "]", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ")", ";", "}" ]
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 targetIndex = targetElements.indexOf(targetElement); if (targetIndex === -1) { return; } const targetImageId = initialData.imageIds.targetElements[targetIndex]; const sourceIndex = sourceElements.indexOf(sourceElement); if (sourceIndex === -1) { return; } const sourceImageId = initialData.imageIds.sourceElements[sourceIndex]; let positionDifference; if (sourceImageId === targetImageId) { positionDifference = 0; } else if (initialData.distances[sourceImageId] !== undefined) { positionDifference = initialData.distances[sourceImageId][targetImageId]; } eventHandler( that, sourceElement, targetElement, eventData, positionDifference ); }); ignoreFiredEvents = false; }
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 targetIndex = targetElements.indexOf(targetElement); if (targetIndex === -1) { return; } const targetImageId = initialData.imageIds.targetElements[targetIndex]; const sourceIndex = sourceElements.indexOf(sourceElement); if (sourceIndex === -1) { return; } const sourceImageId = initialData.imageIds.sourceElements[sourceIndex]; let positionDifference; if (sourceImageId === targetImageId) { positionDifference = 0; } else if (initialData.distances[sourceImageId] !== undefined) { positionDifference = initialData.distances[sourceImageId][targetImageId]; } eventHandler( that, sourceElement, targetElement, eventData, positionDifference ); }); ignoreFiredEvents = false; }
[ "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", "targetIndex", "=", "targetElements", ".", "indexOf", "(", "targetElement", ")", ";", "if", "(", "targetIndex", "===", "-", "1", ")", "{", "return", ";", "}", "const", "targetImageId", "=", "initialData", ".", "imageIds", ".", "targetElements", "[", "targetIndex", "]", ";", "const", "sourceIndex", "=", "sourceElements", ".", "indexOf", "(", "sourceElement", ")", ";", "if", "(", "sourceIndex", "===", "-", "1", ")", "{", "return", ";", "}", "const", "sourceImageId", "=", "initialData", ".", "imageIds", ".", "sourceElements", "[", "sourceIndex", "]", ";", "let", "positionDifference", ";", "if", "(", "sourceImageId", "===", "targetImageId", ")", "{", "positionDifference", "=", "0", ";", "}", "else", "if", "(", "initialData", ".", "distances", "[", "sourceImageId", "]", "!==", "undefined", ")", "{", "positionDifference", "=", "initialData", ".", "distances", "[", "sourceImageId", "]", "[", "targetImageId", "]", ";", "}", "eventHandler", "(", "that", ",", "sourceElement", ",", "targetElement", ",", "eventData", ",", "positionDifference", ")", ";", "}", ")", ";", "ignoreFiredEvents", "=", "false", ";", "}" ]
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("opacity", 0); // For efficiency, filter nodes to keep only those large enough to see. var nodes = partition.nodes(json) .filter(function(d) { return (d.dx > 0.005); // 0.005 radians = 0.29 degrees }); var path = vis.data([json]).selectAll("path") .data(nodes) .enter().append("svg:path") .attr("display", function(d) { return d.depth ? null : "none"; }) .attr("d", arc) .attr("fill-rule", "evenodd") .style("fill", function(d) { return colors[d.depth]; }) .style("opacity", 1) .on("mouseover", mouseover); // Add the mouseleave handler to the bounding circle. d3.select("#container").on("mouseleave", mouseleave); // Get total size of the tree = value of root node from partition. totalSize = path.node().__data__.value; }
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("opacity", 0); // For efficiency, filter nodes to keep only those large enough to see. var nodes = partition.nodes(json) .filter(function(d) { return (d.dx > 0.005); // 0.005 radians = 0.29 degrees }); var path = vis.data([json]).selectAll("path") .data(nodes) .enter().append("svg:path") .attr("display", function(d) { return d.depth ? null : "none"; }) .attr("d", arc) .attr("fill-rule", "evenodd") .style("fill", function(d) { return colors[d.depth]; }) .style("opacity", 1) .on("mouseover", mouseover); // Add the mouseleave handler to the bounding circle. d3.select("#container").on("mouseleave", mouseleave); // Get total size of the tree = value of root node from partition. totalSize = path.node().__data__.value; }
[ "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", "(", "\"opacity\"", ",", "0", ")", ";", "// For efficiency, filter nodes to keep only those large enough to see.", "var", "nodes", "=", "partition", ".", "nodes", "(", "json", ")", ".", "filter", "(", "function", "(", "d", ")", "{", "return", "(", "d", ".", "dx", ">", "0.005", ")", ";", "// 0.005 radians = 0.29 degrees", "}", ")", ";", "var", "path", "=", "vis", ".", "data", "(", "[", "json", "]", ")", ".", "selectAll", "(", "\"path\"", ")", ".", "data", "(", "nodes", ")", ".", "enter", "(", ")", ".", "append", "(", "\"svg:path\"", ")", ".", "attr", "(", "\"display\"", ",", "function", "(", "d", ")", "{", "return", "d", ".", "depth", "?", "null", ":", "\"none\"", ";", "}", ")", ".", "attr", "(", "\"d\"", ",", "arc", ")", ".", "attr", "(", "\"fill-rule\"", ",", "\"evenodd\"", ")", ".", "style", "(", "\"fill\"", ",", "function", "(", "d", ")", "{", "return", "colors", "[", "d", ".", "depth", "]", ";", "}", ")", ".", "style", "(", "\"opacity\"", ",", "1", ")", ".", "on", "(", "\"mouseover\"", ",", "mouseover", ")", ";", "// Add the mouseleave handler to the bounding circle.", "d3", ".", "select", "(", "\"#container\"", ")", ".", "on", "(", "\"mouseleave\"", ",", "mouseleave", ")", ";", "// Get total size of the tree = value of root node from partition.", "totalSize", "=", "path", ".", "node", "(", ")", ".", "__data__", ".", "value", ";", "}" ]
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 sequenceArray = getAncestors(d); updateBreadcrumbs(sequenceArray, percentageString); // Fade all the segments. d3.selectAll("path") .style("opacity", 0.3); // Then highlight only those that are an ancestor of the current segment. vis.selectAll("path") .filter(function(node) { return (sequenceArray.indexOf(node) >= 0); }) .style("opacity", 1); }
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 sequenceArray = getAncestors(d); updateBreadcrumbs(sequenceArray, percentageString); // Fade all the segments. d3.selectAll("path") .style("opacity", 0.3); // Then highlight only those that are an ancestor of the current segment. vis.selectAll("path") .filter(function(node) { return (sequenceArray.indexOf(node) >= 0); }) .style("opacity", 1); }
[ "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", "sequenceArray", "=", "getAncestors", "(", "d", ")", ";", "updateBreadcrumbs", "(", "sequenceArray", ",", "percentageString", ")", ";", "// Fade all the segments.", "d3", ".", "selectAll", "(", "\"path\"", ")", ".", "style", "(", "\"opacity\"", ",", "0.3", ")", ";", "// Then highlight only those that are an ancestor of the current segment.", "vis", ".", "selectAll", "(", "\"path\"", ")", ".", "filter", "(", "function", "(", "node", ")", "{", "return", "(", "sequenceArray", ".", "indexOf", "(", "node", ")", ">=", "0", ")", ";", "}", ")", ".", "style", "(", "\"opacity\"", ",", "1", ")", ";", "}" ]
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") .transition() .duration(250) .style("opacity", 1) .each("end", function() { d3.select(this).on("mouseover", mouseover); }); d3.select("#explanation") .style("visibility", "hidden"); }
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") .transition() .duration(250) .style("opacity", 1) .each("end", function() { d3.select(this).on("mouseover", mouseover); }); d3.select("#explanation") .style("visibility", "hidden"); }
[ "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\"", ")", ".", "transition", "(", ")", ".", "duration", "(", "250", ")", ".", "style", "(", "\"opacity\"", ",", "1", ")", ".", "each", "(", "\"end\"", ",", "function", "(", ")", "{", "d3", ".", "select", "(", "this", ")", ".", "on", "(", "\"mouseover\"", ",", "mouseover", ")", ";", "}", ")", ";", "d3", ".", "select", "(", "\"#explanation\"", ")", ".", "style", "(", "\"visibility\"", ",", "\"hidden\"", ")", ";", "}" ]
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", ".", "parent", ";", "}", "return", "path", ";", "}" ]
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)); } return points.join(" "); }
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)); } return points.join(" "); }
[ "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", ")", ")", ";", "}", "return", "points", ".", "join", "(", "\" \"", ")", ";", "}" ]
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 entering = g.enter().append("svg:g"); entering.append("svg:polygon") .attr("points", breadcrumbPoints) .style("fill", function(d) { return colors[d.name]; }); entering.append("svg:text") .attr("x", (b.w + b.t) / 2) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .text(function(d) { return d.name; }); // Set position for entering and updating nodes. g.attr("transform", function(d, i) { return "translate(" + i * (b.w + b.s) + ", 0)"; }); // Remove exiting nodes. g.exit().remove(); // Now move and update the percentage at the end. d3.select("#trail").select("#endlabel") .attr("x", (nodeArray.length + 0.5) * (b.w + b.s)) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .text(percentageString); // Make the breadcrumb trail visible, if it's hidden. d3.select("#trail") .style("visibility", ""); }
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 entering = g.enter().append("svg:g"); entering.append("svg:polygon") .attr("points", breadcrumbPoints) .style("fill", function(d) { return colors[d.name]; }); entering.append("svg:text") .attr("x", (b.w + b.t) / 2) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .text(function(d) { return d.name; }); // Set position for entering and updating nodes. g.attr("transform", function(d, i) { return "translate(" + i * (b.w + b.s) + ", 0)"; }); // Remove exiting nodes. g.exit().remove(); // Now move and update the percentage at the end. d3.select("#trail").select("#endlabel") .attr("x", (nodeArray.length + 0.5) * (b.w + b.s)) .attr("y", b.h / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .text(percentageString); // Make the breadcrumb trail visible, if it's hidden. d3.select("#trail") .style("visibility", ""); }
[ "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", "entering", "=", "g", ".", "enter", "(", ")", ".", "append", "(", "\"svg:g\"", ")", ";", "entering", ".", "append", "(", "\"svg:polygon\"", ")", ".", "attr", "(", "\"points\"", ",", "breadcrumbPoints", ")", ".", "style", "(", "\"fill\"", ",", "function", "(", "d", ")", "{", "return", "colors", "[", "d", ".", "name", "]", ";", "}", ")", ";", "entering", ".", "append", "(", "\"svg:text\"", ")", ".", "attr", "(", "\"x\"", ",", "(", "b", ".", "w", "+", "b", ".", "t", ")", "/", "2", ")", ".", "attr", "(", "\"y\"", ",", "b", ".", "h", "/", "2", ")", ".", "attr", "(", "\"dy\"", ",", "\"0.35em\"", ")", ".", "attr", "(", "\"text-anchor\"", ",", "\"middle\"", ")", ".", "text", "(", "function", "(", "d", ")", "{", "return", "d", ".", "name", ";", "}", ")", ";", "// Set position for entering and updating nodes.", "g", ".", "attr", "(", "\"transform\"", ",", "function", "(", "d", ",", "i", ")", "{", "return", "\"translate(\"", "+", "i", "*", "(", "b", ".", "w", "+", "b", ".", "s", ")", "+", "\", 0)\"", ";", "}", ")", ";", "// Remove exiting nodes.", "g", ".", "exit", "(", ")", ".", "remove", "(", ")", ";", "// Now move and update the percentage at the end.", "d3", ".", "select", "(", "\"#trail\"", ")", ".", "select", "(", "\"#endlabel\"", ")", ".", "attr", "(", "\"x\"", ",", "(", "nodeArray", ".", "length", "+", "0.5", ")", "*", "(", "b", ".", "w", "+", "b", ".", "s", ")", ")", ".", "attr", "(", "\"y\"", ",", "b", ".", "h", "/", "2", ")", ".", "attr", "(", "\"dy\"", ",", "\"0.35em\"", ")", ".", "attr", "(", "\"text-anchor\"", ",", "\"middle\"", ")", ".", "text", "(", "percentageString", ")", ";", "// Make the breadcrumb trail visible, if it's hidden.", "d3", ".", "select", "(", "\"#trail\"", ")", ".", "style", "(", "\"visibility\"", ",", "\"\"", ")", ";", "}" ]
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; for (var j = 0; j < parts.length; j++) { var children = currentNode["children"]; var nodeName = parts[j]; var childNode; if (j + 1 < parts.length) { // Not yet at the end of the sequence; move down the tree. var foundChild = false; for (var k = 0; k < children.length; k++) { if (children[k]["name"] == nodeName) { childNode = children[k]; foundChild = true; break; } } // If we don't already have a child node for this branch, create it. if (!foundChild) { childNode = {"name": nodeName, "children": []}; children.push(childNode); } currentNode = childNode; } else { // Reached the end of the sequence; create a leaf node. childNode = {"name": nodeName, "size": size}; children.push(childNode); } } } return 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; for (var j = 0; j < parts.length; j++) { var children = currentNode["children"]; var nodeName = parts[j]; var childNode; if (j + 1 < parts.length) { // Not yet at the end of the sequence; move down the tree. var foundChild = false; for (var k = 0; k < children.length; k++) { if (children[k]["name"] == nodeName) { childNode = children[k]; foundChild = true; break; } } // If we don't already have a child node for this branch, create it. if (!foundChild) { childNode = {"name": nodeName, "children": []}; children.push(childNode); } currentNode = childNode; } else { // Reached the end of the sequence; create a leaf node. childNode = {"name": nodeName, "size": size}; children.push(childNode); } } } return root; }
[ "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", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "parts", ".", "length", ";", "j", "++", ")", "{", "var", "children", "=", "currentNode", "[", "\"children\"", "]", ";", "var", "nodeName", "=", "parts", "[", "j", "]", ";", "var", "childNode", ";", "if", "(", "j", "+", "1", "<", "parts", ".", "length", ")", "{", "// Not yet at the end of the sequence; move down the tree.", "var", "foundChild", "=", "false", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "children", ".", "length", ";", "k", "++", ")", "{", "if", "(", "children", "[", "k", "]", "[", "\"name\"", "]", "==", "nodeName", ")", "{", "childNode", "=", "children", "[", "k", "]", ";", "foundChild", "=", "true", ";", "break", ";", "}", "}", "// If we don't already have a child node for this branch, create it.", "if", "(", "!", "foundChild", ")", "{", "childNode", "=", "{", "\"name\"", ":", "nodeName", ",", "\"children\"", ":", "[", "]", "}", ";", "children", ".", "push", "(", "childNode", ")", ";", "}", "currentNode", "=", "childNode", ";", "}", "else", "{", "// Reached the end of the sequence; create a leaf node.", "childNode", "=", "{", "\"name\"", ":", "nodeName", ",", "\"size\"", ":", "size", "}", ";", "children", ".", "push", "(", "childNode", ")", ";", "}", "}", "}", "return", "root", ";", "}" ]
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", "leaf", "separated", "by", "hyphens", ".", "The", "second", "column", "is", "a", "count", "of", "how", "often", "that", "sequence", "occurred", "." ]
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 - %s %s does not exist", req.method, req.path); err = ono({ status: 404 }, "%s Not Found", resource.toString()); next(err); } else { // There' a default value, so use it instead of sending a 404 util.debug( "%s %s does not exist, but the response schema defines a fallback value. So, using the fallback value", req.method, req.path ); res.swagger.lastModified = new Date(); res.body = defaultValue; next(); } } else { res.swagger.lastModified = result.modifiedOn; // Set the response body (unless it's already been set by other middleware) res.body = res.body || result.data; next(); } }); }
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 - %s %s does not exist", req.method, req.path); err = ono({ status: 404 }, "%s Not Found", resource.toString()); next(err); } else { // There' a default value, so use it instead of sending a 404 util.debug( "%s %s does not exist, but the response schema defines a fallback value. So, using the fallback value", req.method, req.path ); res.swagger.lastModified = new Date(); res.body = defaultValue; next(); } } else { res.swagger.lastModified = result.modifiedOn; // Set the response body (unless it's already been set by other middleware) res.body = res.body || result.data; next(); } }); }
[ "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 - %s %s does not exist\"", ",", "req", ".", "method", ",", "req", ".", "path", ")", ";", "err", "=", "ono", "(", "{", "status", ":", "404", "}", ",", "\"%s Not Found\"", ",", "resource", ".", "toString", "(", ")", ")", ";", "next", "(", "err", ")", ";", "}", "else", "{", "// There' a default value, so use it instead of sending a 404", "util", ".", "debug", "(", "\"%s %s does not exist, but the response schema defines a fallback value. So, using the fallback value\"", ",", "req", ".", "method", ",", "req", ".", "path", ")", ";", "res", ".", "swagger", ".", "lastModified", "=", "new", "Date", "(", ")", ";", "res", ".", "body", "=", "defaultValue", ";", "next", "(", ")", ";", "}", "}", "else", "{", "res", ".", "swagger", ".", "lastModified", "=", "result", ".", "modifiedOn", ";", "// Set the response body (unless it's already been set by other middleware)", "res", ".", "body", "=", "res", ".", "body", "||", "result", ".", "data", ";", "next", "(", ")", ";", "}", "}", ")", ";", "}" ]
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.Middleware(router); if (swagger) { middleware.init(swagger, callback); } return middleware; }
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.Middleware(router); if (swagger) { middleware.init(swagger, callback); } return middleware; }
[ "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", ".", "Middleware", "(", "router", ")", ";", "if", "(", "swagger", ")", "{", "middleware", ".", "init", "(", "swagger", ",", "callback", ")", ";", "}", "return", "middleware", ";", "}" ]
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} [router] - An Express Application or Router that will be used to determine settings (such as case-sensitivity and strict routing) and to register path-parsing middleware. @param {function} [callback] - It will be called when the API has been parsed, validated, and dereferenced, or when an error occurs. @returns {Middleware} The {@link Middleware} object is returned immediately, but it isn't ready to handle requests until the callback function is called. The same {@link Middleware} object will be passed to the callback function.
[ "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", ".", "toString", "(", ")", ")", ";", "dataStore", ".", "save", "(", "resource", ",", "sendResponse", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", ")", ";", "}" ]
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()); dataStore.save(resource, sendResponse(req, res, next, dataStore)); } }); }
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()); dataStore.save(resource, sendResponse(req, res, next, dataStore)); } }); }
[ "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", "(", ")", ")", ";", "dataStore", ".", "save", "(", "resource", ",", "sendResponse", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", ")", ";", "}", "}", ")", ";", "}" ]
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(req, res, next, dataStore)(err, deletedResource || resource); }); }
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(req, res, next, dataStore)(err, deletedResource || resource); }); }
[ "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", "(", "req", ",", "res", ",", "next", ",", "dataStore", ")", "(", "err", ",", "deletedResource", "||", "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 new or modified 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 {function} [callback] * - It will be called when the API has been parsed, validated, and dereferenced, or when an error occurs. */ this.init = function (swagger, callback) { // the swagger variable should only ever be a string or a populated object. let invalidSwagger = _.isFunction(swagger) || _.isDate(swagger) || _.isEmpty(swagger); if (invalidSwagger) { throw new Error("Expected a Swagger file or object"); } // Need to retrieve the Swagger API and metadata from the Swagger .yaml or .json file. let parser = new SwaggerParser(); parser.dereference(swagger, (err, api) => { if (err) { util.warn(err); } context.error = err; context.api = api; context.parser = parser; context.emit("change"); if (_.isFunction(callback)) { callback(err, self, context.api, context.parser); } }); }; /** * Serves the Swagger API file(s) in JSON and YAML formats, * so they can be used with third-party front-end tools like Swagger UI and Swagger Editor. * * @param {express#Router} [router] * - Express routing options (e.g. `caseSensitive`, `strict`). * If an Express Application or Router is passed, then its routing settings will be used. * * @param {fileServer.defaultOptions} [options] * - Options for how the files are served (see {@link fileServer.defaultOptions}) * * @returns {function[]} */ this.files = function (router, options) { if (arguments.length === 1 && !util.isExpressRouter(router) && !util.isExpressRoutingOptions(router)) { // Shift arguments options = router; router = sharedRouter; } return fileServer(context, router, options); }; /** * Annotates the HTTP request (the `req` object) with Swagger metadata. * This middleware populates {@link Request#swagger}. * * @param {express#Router} [router] * - Express routing options (e.g. `caseSensitive`, `strict`). * If an Express Application or Router is passed, then its routing settings will be used. * * @returns {function[]} */ this.metadata = function (router) { return requestMetadata(context, router); }; /** * Handles CORS preflight requests and sets CORS headers for all requests * according the Swagger API definition. * * @returns {function[]} */ this.CORS = function () { return CORS(); }; /** * Parses the HTTP request into typed values. * This middleware populates {@link Request#params}, {@link Request#headers}, {@link Request#cookies}, * {@link Request#signedCookies}, {@link Request#query}, {@link Request#body}, and {@link Request#files}. * * @param {express#Router} [router] * - An Express Application or Router. If provided, this will be used to register path-param middleware * via {@link Router#param} (see http://expressjs.com/4x/api.html#router.param). * If not provided, then path parameters will always be parsed as strings. * * @param {requestParser.defaultOptions} [options] * - Options for each of the request-parsing middleware (see {@link requestParser.defaultOptions}) * * @returns {function[]} */ this.parseRequest = function (router, options) { if (arguments.length === 1 && !util.isExpressRouter(router) && !util.isExpressRoutingOptions(router)) { // Shift arguments options = router; router = sharedRouter; } return requestParser(options) .concat(paramParser()) .concat(pathParser(context, router)); }; /** * Validates the HTTP request against the Swagger API. * An error is sent downstream if the request is invalid for any reason. * * @returns {function[]} */ this.validateRequest = function () { return requestValidator(context); }; /** * Implements mock behavior for HTTP requests, based on the Swagger API. * * @param {express#Router} [router] * - Express routing options (e.g. `caseSensitive`, `strict`). * If an Express Application or Router is passed, then its routing settings will be used. * * @param {DataStore} [dataStore] * - The data store that will be used to persist REST resources. * If `router` is an Express Application, then you can set/get the data store * using `router.get("mock data store")`. * * @returns {function[]} */ this.mock = function (router, dataStore) { if (arguments.length === 1 && router instanceof DataStore) { // Shift arguments dataStore = router; router = undefined; } return mock(context, router, dataStore); }; }
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 new or modified 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 {function} [callback] * - It will be called when the API has been parsed, validated, and dereferenced, or when an error occurs. */ this.init = function (swagger, callback) { // the swagger variable should only ever be a string or a populated object. let invalidSwagger = _.isFunction(swagger) || _.isDate(swagger) || _.isEmpty(swagger); if (invalidSwagger) { throw new Error("Expected a Swagger file or object"); } // Need to retrieve the Swagger API and metadata from the Swagger .yaml or .json file. let parser = new SwaggerParser(); parser.dereference(swagger, (err, api) => { if (err) { util.warn(err); } context.error = err; context.api = api; context.parser = parser; context.emit("change"); if (_.isFunction(callback)) { callback(err, self, context.api, context.parser); } }); }; /** * Serves the Swagger API file(s) in JSON and YAML formats, * so they can be used with third-party front-end tools like Swagger UI and Swagger Editor. * * @param {express#Router} [router] * - Express routing options (e.g. `caseSensitive`, `strict`). * If an Express Application or Router is passed, then its routing settings will be used. * * @param {fileServer.defaultOptions} [options] * - Options for how the files are served (see {@link fileServer.defaultOptions}) * * @returns {function[]} */ this.files = function (router, options) { if (arguments.length === 1 && !util.isExpressRouter(router) && !util.isExpressRoutingOptions(router)) { // Shift arguments options = router; router = sharedRouter; } return fileServer(context, router, options); }; /** * Annotates the HTTP request (the `req` object) with Swagger metadata. * This middleware populates {@link Request#swagger}. * * @param {express#Router} [router] * - Express routing options (e.g. `caseSensitive`, `strict`). * If an Express Application or Router is passed, then its routing settings will be used. * * @returns {function[]} */ this.metadata = function (router) { return requestMetadata(context, router); }; /** * Handles CORS preflight requests and sets CORS headers for all requests * according the Swagger API definition. * * @returns {function[]} */ this.CORS = function () { return CORS(); }; /** * Parses the HTTP request into typed values. * This middleware populates {@link Request#params}, {@link Request#headers}, {@link Request#cookies}, * {@link Request#signedCookies}, {@link Request#query}, {@link Request#body}, and {@link Request#files}. * * @param {express#Router} [router] * - An Express Application or Router. If provided, this will be used to register path-param middleware * via {@link Router#param} (see http://expressjs.com/4x/api.html#router.param). * If not provided, then path parameters will always be parsed as strings. * * @param {requestParser.defaultOptions} [options] * - Options for each of the request-parsing middleware (see {@link requestParser.defaultOptions}) * * @returns {function[]} */ this.parseRequest = function (router, options) { if (arguments.length === 1 && !util.isExpressRouter(router) && !util.isExpressRoutingOptions(router)) { // Shift arguments options = router; router = sharedRouter; } return requestParser(options) .concat(paramParser()) .concat(pathParser(context, router)); }; /** * Validates the HTTP request against the Swagger API. * An error is sent downstream if the request is invalid for any reason. * * @returns {function[]} */ this.validateRequest = function () { return requestValidator(context); }; /** * Implements mock behavior for HTTP requests, based on the Swagger API. * * @param {express#Router} [router] * - Express routing options (e.g. `caseSensitive`, `strict`). * If an Express Application or Router is passed, then its routing settings will be used. * * @param {DataStore} [dataStore] * - The data store that will be used to persist REST resources. * If `router` is an Express Application, then you can set/get the data store * using `router.get("mock data store")`. * * @returns {function[]} */ this.mock = function (router, dataStore) { if (arguments.length === 1 && router instanceof DataStore) { // Shift arguments dataStore = router; router = undefined; } return mock(context, router, dataStore); }; }
[ "function", "Middleware", "(", "sharedRouter", ")", "{", "sharedRouter", "=", "util", ".", "isExpressRouter", "(", "sharedRouter", ")", "?", "sharedRouter", ":", "undefined", ";", "let", "self", "=", "this", ";", "let", "context", "=", "new", "MiddlewareContext", "(", "sharedRouter", ")", ";", "/**\n * Initializes the middleware with the given Swagger API.\n * This method can be called again to re-initialize with a new or modified API.\n *\n * @param {string|object} [swagger]\n * - The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format.\n * Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).\n *\n * @param {function} [callback]\n * - It will be called when the API has been parsed, validated, and dereferenced, or when an error occurs.\n */", "this", ".", "init", "=", "function", "(", "swagger", ",", "callback", ")", "{", "// the swagger variable should only ever be a string or a populated object.", "let", "invalidSwagger", "=", "_", ".", "isFunction", "(", "swagger", ")", "||", "_", ".", "isDate", "(", "swagger", ")", "||", "_", ".", "isEmpty", "(", "swagger", ")", ";", "if", "(", "invalidSwagger", ")", "{", "throw", "new", "Error", "(", "\"Expected a Swagger file or object\"", ")", ";", "}", "// Need to retrieve the Swagger API and metadata from the Swagger .yaml or .json file.", "let", "parser", "=", "new", "SwaggerParser", "(", ")", ";", "parser", ".", "dereference", "(", "swagger", ",", "(", "err", ",", "api", ")", "=>", "{", "if", "(", "err", ")", "{", "util", ".", "warn", "(", "err", ")", ";", "}", "context", ".", "error", "=", "err", ";", "context", ".", "api", "=", "api", ";", "context", ".", "parser", "=", "parser", ";", "context", ".", "emit", "(", "\"change\"", ")", ";", "if", "(", "_", ".", "isFunction", "(", "callback", ")", ")", "{", "callback", "(", "err", ",", "self", ",", "context", ".", "api", ",", "context", ".", "parser", ")", ";", "}", "}", ")", ";", "}", ";", "/**\n * Serves the Swagger API file(s) in JSON and YAML formats,\n * so they can be used with third-party front-end tools like Swagger UI and Swagger Editor.\n *\n * @param {express#Router} [router]\n * - Express routing options (e.g. `caseSensitive`, `strict`).\n * If an Express Application or Router is passed, then its routing settings will be used.\n *\n * @param {fileServer.defaultOptions} [options]\n * - Options for how the files are served (see {@link fileServer.defaultOptions})\n *\n * @returns {function[]}\n */", "this", ".", "files", "=", "function", "(", "router", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "!", "util", ".", "isExpressRouter", "(", "router", ")", "&&", "!", "util", ".", "isExpressRoutingOptions", "(", "router", ")", ")", "{", "// Shift arguments", "options", "=", "router", ";", "router", "=", "sharedRouter", ";", "}", "return", "fileServer", "(", "context", ",", "router", ",", "options", ")", ";", "}", ";", "/**\n * Annotates the HTTP request (the `req` object) with Swagger metadata.\n * This middleware populates {@link Request#swagger}.\n *\n * @param {express#Router} [router]\n * - Express routing options (e.g. `caseSensitive`, `strict`).\n * If an Express Application or Router is passed, then its routing settings will be used.\n *\n * @returns {function[]}\n */", "this", ".", "metadata", "=", "function", "(", "router", ")", "{", "return", "requestMetadata", "(", "context", ",", "router", ")", ";", "}", ";", "/**\n * Handles CORS preflight requests and sets CORS headers for all requests\n * according the Swagger API definition.\n *\n * @returns {function[]}\n */", "this", ".", "CORS", "=", "function", "(", ")", "{", "return", "CORS", "(", ")", ";", "}", ";", "/**\n * Parses the HTTP request into typed values.\n * This middleware populates {@link Request#params}, {@link Request#headers}, {@link Request#cookies},\n * {@link Request#signedCookies}, {@link Request#query}, {@link Request#body}, and {@link Request#files}.\n *\n * @param {express#Router} [router]\n * - An Express Application or Router. If provided, this will be used to register path-param middleware\n * via {@link Router#param} (see http://expressjs.com/4x/api.html#router.param).\n * If not provided, then path parameters will always be parsed as strings.\n *\n * @param {requestParser.defaultOptions} [options]\n * - Options for each of the request-parsing middleware (see {@link requestParser.defaultOptions})\n *\n * @returns {function[]}\n */", "this", ".", "parseRequest", "=", "function", "(", "router", ",", "options", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "!", "util", ".", "isExpressRouter", "(", "router", ")", "&&", "!", "util", ".", "isExpressRoutingOptions", "(", "router", ")", ")", "{", "// Shift arguments", "options", "=", "router", ";", "router", "=", "sharedRouter", ";", "}", "return", "requestParser", "(", "options", ")", ".", "concat", "(", "paramParser", "(", ")", ")", ".", "concat", "(", "pathParser", "(", "context", ",", "router", ")", ")", ";", "}", ";", "/**\n * Validates the HTTP request against the Swagger API.\n * An error is sent downstream if the request is invalid for any reason.\n *\n * @returns {function[]}\n */", "this", ".", "validateRequest", "=", "function", "(", ")", "{", "return", "requestValidator", "(", "context", ")", ";", "}", ";", "/**\n * Implements mock behavior for HTTP requests, based on the Swagger API.\n *\n * @param {express#Router} [router]\n * - Express routing options (e.g. `caseSensitive`, `strict`).\n * If an Express Application or Router is passed, then its routing settings will be used.\n *\n * @param {DataStore} [dataStore]\n * - The data store that will be used to persist REST resources.\n * If `router` is an Express Application, then you can set/get the data store\n * using `router.get(\"mock data store\")`.\n *\n * @returns {function[]}\n */", "this", ".", "mock", "=", "function", "(", "router", ",", "dataStore", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "router", "instanceof", "DataStore", ")", "{", "// Shift arguments", "dataStore", "=", "router", ";", "router", "=", "undefined", ";", "}", "return", "mock", "(", "context", ",", "router", ",", "dataStore", ")", ";", "}", ";", "}" ]
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#router.param). @constructor
[ "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; case 2: this.merge(name); this.collection = getCollectionFromPath(path); this.name = getNameFromPath(path); break; default: this.collection = normalizeCollection(path); this.name = normalizeName(name); this.merge(data); } this.createdOn = null; this.modifiedOn = null; }
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; case 2: this.merge(name); this.collection = getCollectionFromPath(path); this.name = getNameFromPath(path); break; default: this.collection = normalizeCollection(path); this.name = normalizeName(name); this.merge(data); } this.createdOn = null; this.modifiedOn = null; }
[ "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", ";", "case", "2", ":", "this", ".", "merge", "(", "name", ")", ";", "this", ".", "collection", "=", "getCollectionFromPath", "(", "path", ")", ";", "this", ".", "name", "=", "getNameFromPath", "(", "path", ")", ";", "break", ";", "default", ":", "this", ".", "collection", "=", "normalizeCollection", "(", "path", ")", ";", "this", ".", "name", "=", "normalizeName", "(", "name", ")", ";", "this", ".", "merge", "(", "data", ")", ";", "}", "this", ".", "createdOn", "=", "null", ";", "this", ".", "modifiedOn", "=", "null", ";", "}" ]
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 - Name: /seattle/ /restaurants/washington/seattle/joes-diner - Collection: /restaurants/washington/seattle - Name: /joes-diner / - Collection: (empty string) - Name: / @param {string} [path] - The full resource path (collection and name), or just the collection path @param {string} [name] - The resource name (if `path` is just the collection path) @param {*} [data] - The resource's data @constructor
[ "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", "(", "\"/\"", ")", ";", "if", "(", "lastSlash", "===", "-", "1", ")", "{", "return", "\"\"", ";", "}", "else", "{", "return", "normalizeCollection", "(", "path", ".", "substring", "(", "0", ",", "lastSlash", ")", ")", ";", "}", "}" ]
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", "(", "\"/\"", ")", ";", "if", "(", "lastSlash", "===", "-", "1", ")", "{", "return", "normalizeName", "(", "path", ")", ";", "}", "else", "{", "return", "normalizeName", "(", "path", ".", "substring", "(", "lastSlash", ")", ")", ";", "}", "}" ]
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 = "/" + collection; } // Remove a trailing slash if (_.endsWith(collection, "/")) { collection = collection.substring(0, collection.length - 1); } return collection; }
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 = "/" + collection; } // Remove a trailing slash if (_.endsWith(collection, "/")) { collection = collection.substring(0, collection.length - 1); } return collection; }
[ "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", "=", "\"/\"", "+", "collection", ";", "}", "// Remove a trailing slash", "if", "(", "_", ".", "endsWith", "(", "collection", ",", "\"/\"", ")", ")", "{", "collection", "=", "collection", ".", "substring", "(", "0", ",", "collection", ".", "length", "-", "1", ")", ";", "}", "return", "collection", ";", "}" ]
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 (_.includes(name.substring(1, name.length - 1), "/")) { throw ono("Resource names cannot contain slashes"); } return name; }
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 (_.includes(name.substring(1, name.length - 1), "/")) { throw ono("Resource names cannot contain slashes"); } return name; }
[ "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", "(", "_", ".", "includes", "(", "name", ".", "substring", "(", "1", ",", "name", ".", "length", "-", "1", ")", ",", "\"/\"", ")", ")", "{", "throw", "ono", "(", "\"Resource names cannot contain slashes\"", ")", ";", "}", "return", "name", ";", "}" ]
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(); resource.createdOn = new Date(now); resource.modifiedOn = new Date(now); // Does the resource already exist? let existing = _.find(existingResources, resource.filter(dataStore.__router)); if (existing) { // Merge the new data into the existing resource util.debug("%s already exists. Merging new data with existing data.", resource.toString()); existing.merge(resource); // Update the calling code's reference to the resource _.extend(resource, existing); } else { existingResources.push(resource); } }); // Save the changes dataStore.__saveDataStore(collectionName, existingResources, (err) => { callback(err, resources); }); }); }
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(); resource.createdOn = new Date(now); resource.modifiedOn = new Date(now); // Does the resource already exist? let existing = _.find(existingResources, resource.filter(dataStore.__router)); if (existing) { // Merge the new data into the existing resource util.debug("%s already exists. Merging new data with existing data.", resource.toString()); existing.merge(resource); // Update the calling code's reference to the resource _.extend(resource, existing); } else { existingResources.push(resource); } }); // Save the changes dataStore.__saveDataStore(collectionName, existingResources, (err) => { callback(err, resources); }); }); }
[ "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", "(", ")", ";", "resource", ".", "createdOn", "=", "new", "Date", "(", "now", ")", ";", "resource", ".", "modifiedOn", "=", "new", "Date", "(", "now", ")", ";", "// Does the resource already exist?", "let", "existing", "=", "_", ".", "find", "(", "existingResources", ",", "resource", ".", "filter", "(", "dataStore", ".", "__router", ")", ")", ";", "if", "(", "existing", ")", "{", "// Merge the new data into the existing resource", "util", ".", "debug", "(", "\"%s already exists. Merging new data with existing data.\"", ",", "resource", ".", "toString", "(", ")", ")", ";", "existing", ".", "merge", "(", "resource", ")", ";", "// Update the calling code's reference to the resource", "_", ".", "extend", "(", "resource", ",", "existing", ")", ";", "}", "else", "{", "existingResources", ".", "push", "(", "resource", ")", ";", "}", "}", ")", ";", "// Save the changes", "dataStore", ".", "__saveDataStore", "(", "collectionName", ",", "existingResources", ",", "(", "err", ")", "=>", "{", "callback", "(", "err", ",", "resources", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
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[]} resources - The Resources to be saved @param {function} callback - Callback function
[ "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.forEach((resource) => { let removed = _.remove(existingResources, resource.filter(dataStore.__router)); removedResources = removedResources.concat(removed); }); if (removedResources.length > 0) { // Save the changes dataStore.__saveDataStore(collectionName, existingResources, (err) => { if (err) { callback(err); } else { callback(null, removedResources); } }); } else { callback(null, []); } }); }
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.forEach((resource) => { let removed = _.remove(existingResources, resource.filter(dataStore.__router)); removedResources = removedResources.concat(removed); }); if (removedResources.length > 0) { // Save the changes dataStore.__saveDataStore(collectionName, existingResources, (err) => { if (err) { callback(err); } else { callback(null, removedResources); } }); } else { callback(null, []); } }); }
[ "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", ".", "forEach", "(", "(", "resource", ")", "=>", "{", "let", "removed", "=", "_", ".", "remove", "(", "existingResources", ",", "resource", ".", "filter", "(", "dataStore", ".", "__router", ")", ")", ";", "removedResources", "=", "removedResources", ".", "concat", "(", "removed", ")", ";", "}", ")", ";", "if", "(", "removedResources", ".", "length", ">", "0", ")", "{", "// Save the changes", "dataStore", ".", "__saveDataStore", "(", "collectionName", ",", "existingResources", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "removedResources", ")", ";", "}", "}", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "[", "]", ")", ";", "}", "}", ")", ";", "}" ]
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 - Callback function
[ "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 collection name let collectionName = collection.valueOf(dataStore.__router, true); // Open the data store dataStore.__openDataStore(collectionName, (err, resources) => { callback(err, collection, resources); }); }
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 collection name let collectionName = collection.valueOf(dataStore.__router, true); // Open the data store dataStore.__openDataStore(collectionName, (err, resources) => { callback(err, collection, resources); }); }
[ "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 collection name", "let", "collectionName", "=", "collection", ".", "valueOf", "(", "dataStore", ".", "__router", ",", "true", ")", ";", "// Open the data store", "dataStore", ".", "__openDataStore", "(", "collectionName", ",", "(", "err", ",", "resources", ")", "=>", "{", "callback", "(", "err", ",", "collection", ",", "resources", ")", ";", "}", ")", ";", "}" ]
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(' Parsing the "%s" query parameter', param.name); req.query[param.name] = parseParameter(param, req.query[param.name], param); break; case "header": // NOTE: req.headers properties are always lower-cased util.debug(' Parsing the "%s" header parameter', param.name); req.headers[param.name.toLowerCase()] = parseParameter(param, req.header(param.name), param); break; } }); } next(); }
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(' Parsing the "%s" query parameter', param.name); req.query[param.name] = parseParameter(param, req.query[param.name], param); break; case "header": // NOTE: req.headers properties are always lower-cased util.debug(' Parsing the "%s" header parameter', param.name); req.headers[param.name.toLowerCase()] = parseParameter(param, req.header(param.name), param); break; } }); } next(); }
[ "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", "(", "' Parsing the \"%s\" query parameter'", ",", "param", ".", "name", ")", ";", "req", ".", "query", "[", "param", ".", "name", "]", "=", "parseParameter", "(", "param", ",", "req", ".", "query", "[", "param", ".", "name", "]", ",", "param", ")", ";", "break", ";", "case", "\"header\"", ":", "// NOTE: req.headers properties are always lower-cased", "util", ".", "debug", "(", "' Parsing the \"%s\" header parameter'", ",", "param", ".", "name", ")", ";", "req", ".", "headers", "[", "param", ".", "name", ".", "toLowerCase", "(", ")", "]", "=", "parseParameter", "(", "param", ",", "req", ".", "header", "(", "param", ".", "name", ")", ",", "param", ")", ";", "break", ";", "}", "}", ")", ";", "}", "next", "(", ")", ";", "}" ]
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] = parseParameter(param, req.files[param.name], param); } else { // Parse the body parameter req.body[param.name] = parseParameter(param, req.body[param.name], param); } } }); next(); }
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] = parseParameter(param, req.files[param.name], param); } else { // Parse the body parameter req.body[param.name] = parseParameter(param, req.body[param.name], param); } } }); next(); }
[ "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", "]", "=", "parseParameter", "(", "param", ",", "req", ".", "files", "[", "param", ".", "name", "]", ",", "param", ")", ";", "}", "else", "{", "// Parse the body parameter", "req", ".", "body", "[", "param", ".", "name", "]", "=", "parseParameter", "(", "param", ",", "req", ".", "body", "[", "param", ".", "name", "]", ",", "param", ")", ";", "}", "}", "}", ")", ";", "next", "(", ")", ";", "}" ]
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 && param.schema.type === "string")) { // Convert {} to "" req.body = ""; } else { // Convert {} to undefined req.body = undefined; } } // Parse the body req.body = parseParameter(param, req.body, param.schema); // There can only be one "body" parameter, so skip the rest return true; } }); // If there are no body/formData parameters, then reset `req.body` to undefined if (params.length > 0) { let hasBody = params.some((param) => { return param.in === "body" || param.in === "formData"; }); if (!hasBody) { req.body = undefined; } } next(); }
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 && param.schema.type === "string")) { // Convert {} to "" req.body = ""; } else { // Convert {} to undefined req.body = undefined; } } // Parse the body req.body = parseParameter(param, req.body, param.schema); // There can only be one "body" parameter, so skip the rest return true; } }); // If there are no body/formData parameters, then reset `req.body` to undefined if (params.length > 0) { let hasBody = params.some((param) => { return param.in === "body" || param.in === "formData"; }); if (!hasBody) { req.body = undefined; } } next(); }
[ "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", "&&", "param", ".", "schema", ".", "type", "===", "\"string\"", ")", ")", "{", "// Convert {} to \"\"", "req", ".", "body", "=", "\"\"", ";", "}", "else", "{", "// Convert {} to undefined", "req", ".", "body", "=", "undefined", ";", "}", "}", "// Parse the body", "req", ".", "body", "=", "parseParameter", "(", "param", ",", "req", ".", "body", ",", "param", ".", "schema", ")", ";", "// There can only be one \"body\" parameter, so skip the rest", "return", "true", ";", "}", "}", ")", ";", "// If there are no body/formData parameters, then reset `req.body` to undefined", "if", "(", "params", ".", "length", ">", "0", ")", "{", "let", "hasBody", "=", "params", ".", "some", "(", "(", "param", ")", "=>", "{", "return", "param", ".", "in", "===", "\"body\"", "||", "param", ".", "in", "===", "\"formData\"", ";", "}", ")", ";", "if", "(", "!", "hasBody", ")", "{", "req", ".", "body", "=", "undefined", ";", "}", "}", "next", "(", ")", ";", "}" ]
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 the Content-Length header. It has it's own HTTP error code. errCode = 411; // (Length Required) } // noinspection ExceptionCaughtLocallyJS throw ono({ status: errCode }, 'Missing required %s parameter "%s"', param.in, param.name); } else if (schema.default === undefined) { // The parameter is optional, and there's no default value return undefined; } } // Special case for the Content-Length header. It has it's own HTTP error code (411 Length Required) if (value === "" && param.in === "header" && param.name.toLowerCase() === "content-length") { throw ono({ status: 411 }, 'Missing required header parameter "%s"', param.name); } try { return new JsonSchema(schema).parse(value); } catch (e) { throw ono(e, { status: e.status }, 'The "%s" %s parameter is invalid (%j)', param.name, param.in, value === undefined ? param.default : value); } }
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 the Content-Length header. It has it's own HTTP error code. errCode = 411; // (Length Required) } // noinspection ExceptionCaughtLocallyJS throw ono({ status: errCode }, 'Missing required %s parameter "%s"', param.in, param.name); } else if (schema.default === undefined) { // The parameter is optional, and there's no default value return undefined; } } // Special case for the Content-Length header. It has it's own HTTP error code (411 Length Required) if (value === "" && param.in === "header" && param.name.toLowerCase() === "content-length") { throw ono({ status: 411 }, 'Missing required header parameter "%s"', param.name); } try { return new JsonSchema(schema).parse(value); } catch (e) { throw ono(e, { status: e.status }, 'The "%s" %s parameter is invalid (%j)', param.name, param.in, value === undefined ? param.default : value); } }
[ "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 the Content-Length header. It has it's own HTTP error code.", "errCode", "=", "411", ";", "// (Length Required)", "}", "// noinspection ExceptionCaughtLocallyJS", "throw", "ono", "(", "{", "status", ":", "errCode", "}", ",", "'Missing required %s parameter \"%s\"'", ",", "param", ".", "in", ",", "param", ".", "name", ")", ";", "}", "else", "if", "(", "schema", ".", "default", "===", "undefined", ")", "{", "// The parameter is optional, and there's no default value", "return", "undefined", ";", "}", "}", "// Special case for the Content-Length header. It has it's own HTTP error code (411 Length Required)", "if", "(", "value", "===", "\"\"", "&&", "param", ".", "in", "===", "\"header\"", "&&", "param", ".", "name", ".", "toLowerCase", "(", ")", "===", "\"content-length\"", ")", "{", "throw", "ono", "(", "{", "status", ":", "411", "}", ",", "'Missing required header parameter \"%s\"'", ",", "param", ".", "name", ")", ";", "}", "try", "{", "return", "new", "JsonSchema", "(", "schema", ")", ".", "parse", "(", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "ono", "(", "e", ",", "{", "status", ":", "e", ".", "status", "}", ",", "'The \"%s\" %s parameter is invalid (%j)'", ",", "param", ".", "name", ",", "param", ".", "in", ",", "value", "===", "undefined", "?", "param", ".", "default", ":", "value", ")", ";", "}", "}" ]
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 parsed value
[ "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", "(", ")", ";", "return", "path", ".", "normalize", "(", "path", ".", "join", "(", "baseDir", ",", "dir", ")", ")", ";", "}" ]
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", "(", "\"/\"", ")", "+", "1", ")", "+", "\".json\"", ";", "fileName", "=", "fileName", ".", "toLowerCase", "(", ")", ";", "return", "path", ".", "join", "(", "directory", ",", "fileName", ")", ";", "}" ]
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 (context.error) { context.error.status = 500; throw context.error; } next(); } }
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 (context.error) { context.error.status = 500; throw context.error; } next(); } }
[ "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 {@link Middleware#init} again with a valid Swagger API will clear the error.\n */", "function", "http500", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "context", ".", "error", ")", "{", "context", ".", "error", ".", "status", "=", "500", ";", "throw", "context", ".", "error", ";", "}", "next", "(", ")", ";", "}", "}" ]
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.lastModified = new Date(); // Use the default/example value, if there is one if (res.swagger.schema) { resources = res.swagger.schema.default || res.swagger.schema.example || []; } } else { // Determine the max "modifiedOn" date of the remaining items res.swagger.lastModified = _.maxBy(resources, "modifiedOn").modifiedOn; // Extract the "data" of each Resource resources = _.map(resources, "data"); } // Set the response body (unless it's already been set by other middleware) res.body = res.body || resources; } next(err); }); }
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.lastModified = new Date(); // Use the default/example value, if there is one if (res.swagger.schema) { resources = res.swagger.schema.default || res.swagger.schema.example || []; } } else { // Determine the max "modifiedOn" date of the remaining items res.swagger.lastModified = _.maxBy(resources, "modifiedOn").modifiedOn; // Extract the "data" of each Resource resources = _.map(resources, "data"); } // Set the response body (unless it's already been set by other middleware) res.body = res.body || resources; } next(err); }); }
[ "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", ".", "lastModified", "=", "new", "Date", "(", ")", ";", "// Use the default/example value, if there is one", "if", "(", "res", ".", "swagger", ".", "schema", ")", "{", "resources", "=", "res", ".", "swagger", ".", "schema", ".", "default", "||", "res", ".", "swagger", ".", "schema", ".", "example", "||", "[", "]", ";", "}", "}", "else", "{", "// Determine the max \"modifiedOn\" date of the remaining items", "res", ".", "swagger", ".", "lastModified", "=", "_", ".", "maxBy", "(", "resources", ",", "\"modifiedOn\"", ")", ".", "modifiedOn", ";", "// Extract the \"data\" of each Resource", "resources", "=", "_", ".", "map", "(", "resources", ",", "\"data\"", ")", ";", "}", "// Set the response body (unless it's already been set by other middleware)", "res", ".", "body", "=", "res", ".", "body", "||", "resources", ";", "}", "next", "(", "err", ")", ";", "}", ")", ";", "}" ]
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 not defined in the Swagger API are ignored. @param {Request} req @param {Response} res @param {function} next @param {DataStore} dataStore
[ "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 === 0) { sendResponse(null, []); } else if (resourcesToDelete.length === resources.length) { // Delete the whole collection dataStore.deleteCollection(req.path, sendResponse); } else { // Only delete the matching resources dataStore.delete(resourcesToDelete, sendResponse); } } }); // Responds with the deleted resources 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 (err || res.body) { next(err); } else if (!res.swagger.isCollection) { // Response body is a single value, so only return the first item in the collection res.body = _.first(resources); next(); } else { // Response body is the resource that was created/update/deleted res.body = resources; next(); } } }
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 === 0) { sendResponse(null, []); } else if (resourcesToDelete.length === resources.length) { // Delete the whole collection dataStore.deleteCollection(req.path, sendResponse); } else { // Only delete the matching resources dataStore.delete(resourcesToDelete, sendResponse); } } }); // Responds with the deleted resources 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 (err || res.body) { next(err); } else if (!res.swagger.isCollection) { // Response body is a single value, so only return the first item in the collection res.body = _.first(resources); next(); } else { // Response body is the resource that was created/update/deleted res.body = resources; next(); } } }
[ "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", "===", "0", ")", "{", "sendResponse", "(", "null", ",", "[", "]", ")", ";", "}", "else", "if", "(", "resourcesToDelete", ".", "length", "===", "resources", ".", "length", ")", "{", "// Delete the whole collection", "dataStore", ".", "deleteCollection", "(", "req", ".", "path", ",", "sendResponse", ")", ";", "}", "else", "{", "// Only delete the matching resources", "dataStore", ".", "delete", "(", "resourcesToDelete", ",", "sendResponse", ")", ";", "}", "}", "}", ")", ";", "// Responds with the deleted resources", "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", "(", "err", "||", "res", ".", "body", ")", "{", "next", "(", "err", ")", ";", "}", "else", "if", "(", "!", "res", ".", "swagger", ".", "isCollection", ")", "{", "// Response body is a single value, so only return the first item in the collection", "res", ".", "body", "=", "_", ".", "first", "(", "resources", ")", ";", "next", "(", ")", ";", "}", "else", "{", "// Response body is the resource that was created/update/deleted", "res", ".", "body", "=", "resources", ";", "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 Swagger API are ignored. @param {Request} req @param {Response} res @param {function} next @param {DataStore} dataStore
[ "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 (err || res.body) { next(err); } else if (!res.swagger.isCollection) { // Response body is a single value, so only return the first item in the collection res.body = _.first(resources); next(); } else { // Response body is the resource that was created/update/deleted res.body = resources; next(); } }
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 (err || res.body) { next(err); } else if (!res.swagger.isCollection) { // Response body is a single value, so only return the first item in the collection res.body = _.first(resources); next(); } else { // Response body is the resource that was created/update/deleted res.body = resources; next(); } }
[ "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", "(", "err", "||", "res", ".", "body", ")", "{", "next", "(", "err", ")", ";", "}", "else", "if", "(", "!", "res", ".", "swagger", ".", "isCollection", ")", "{", "// Response body is a single value, so only return the first item in the collection", "res", ".", "body", "=", "_", ".", "first", "(", "resources", ")", ";", "next", "(", ")", ";", "}", "else", "{", "// Response body is the resource that was created/update/deleted", "res", ".", "body", "=", "resources", ";", "next", "(", ")", ";", "}", "}" ]
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", "++", ")", "{", "obj", "=", "obj", "[", "propName", "[", "i", "]", "]", "=", "obj", "[", "propName", "[", "i", "]", "]", "||", "{", "}", ";", "}", "obj", "[", "propName", "[", "propName", ".", "length", "-", "1", "]", "]", "=", "propValue", ";", "}" ]
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)) { req.swagger.api = context.api; } } next(); }
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)) { req.swagger.api = context.api; } } next(); }
[ "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", ")", ")", "{", "req", ".", "swagger", ".", "api", "=", "context", ".", "api", ";", "}", "}", "next", "(", ")", ";", "}" ]
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 = util.normalizePath(swaggerPath, router); if (swaggerPathNormalized === relPathNormalized) { // We found an exact match (i.e. a path with no parameters) req.swagger.path = req.swagger.api.paths[swaggerPath]; req.swagger.pathName = swaggerPath; return true; } else if (req.swagger.path === null && pathMatches(relPathNormalized, swaggerPathNormalized)) { // We found a possible match, but keep searching in case we find an exact match req.swagger.path = req.swagger.api.paths[swaggerPath]; req.swagger.pathName = swaggerPath; } }); if (req.swagger.path) { util.debug("%s %s matches Swagger path %s", req.method, req.path, req.swagger.pathName); } else { util.warn('WARNING! Unable to find a Swagger path that matches "%s"', req.path); } } next(); }
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 = util.normalizePath(swaggerPath, router); if (swaggerPathNormalized === relPathNormalized) { // We found an exact match (i.e. a path with no parameters) req.swagger.path = req.swagger.api.paths[swaggerPath]; req.swagger.pathName = swaggerPath; return true; } else if (req.swagger.path === null && pathMatches(relPathNormalized, swaggerPathNormalized)) { // We found a possible match, but keep searching in case we find an exact match req.swagger.path = req.swagger.api.paths[swaggerPath]; req.swagger.pathName = swaggerPath; } }); if (req.swagger.path) { util.debug("%s %s matches Swagger path %s", req.method, req.path, req.swagger.pathName); } else { util.warn('WARNING! Unable to find a Swagger path that matches "%s"', req.path); } } next(); }
[ "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", "=", "util", ".", "normalizePath", "(", "swaggerPath", ",", "router", ")", ";", "if", "(", "swaggerPathNormalized", "===", "relPathNormalized", ")", "{", "// We found an exact match (i.e. a path with no parameters)", "req", ".", "swagger", ".", "path", "=", "req", ".", "swagger", ".", "api", ".", "paths", "[", "swaggerPath", "]", ";", "req", ".", "swagger", ".", "pathName", "=", "swaggerPath", ";", "return", "true", ";", "}", "else", "if", "(", "req", ".", "swagger", ".", "path", "===", "null", "&&", "pathMatches", "(", "relPathNormalized", ",", "swaggerPathNormalized", ")", ")", "{", "// We found a possible match, but keep searching in case we find an exact match", "req", ".", "swagger", ".", "path", "=", "req", ".", "swagger", ".", "api", ".", "paths", "[", "swaggerPath", "]", ";", "req", ".", "swagger", ".", "pathName", "=", "swaggerPath", ";", "}", "}", ")", ";", "if", "(", "req", ".", "swagger", ".", "path", ")", "{", "util", ".", "debug", "(", "\"%s %s matches Swagger path %s\"", ",", "req", ".", "method", ",", "req", ".", "path", ",", "req", ".", "swagger", ".", "pathName", ")", ";", "}", "else", "{", "util", ".", "warn", "(", "'WARNING! Unable to find a Swagger path that matches \"%s\"'", ",", "req", ".", "path", ")", ";", "}", "}", "next", "(", ")", ";", "}" ]
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/blob/master/versions/2.0.md#swagger-object) * @type {SwaggerObject|null} */ api: null, /** * The Swagger path name, as it appears in the Swagger API. * (e.g. "/users/{username}/orders/{orderId}") * @type {string} */ pathName: "", /** * The Path object from the Swagger API. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject) * @type {object|null} */ path: null, /** * The Operation object from the Swagger API. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject) * @type {object|null} */ operation: null, /** * The Parameter objects that apply to this request. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameter-object-) * @type {object[]} */ params: [], /** * The Security Requirement objects that apply to this request. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityRequirementObject) * @type {object[]} */ security: [] }; next(); }
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/blob/master/versions/2.0.md#swagger-object) * @type {SwaggerObject|null} */ api: null, /** * The Swagger path name, as it appears in the Swagger API. * (e.g. "/users/{username}/orders/{orderId}") * @type {string} */ pathName: "", /** * The Path object from the Swagger API. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject) * @type {object|null} */ path: null, /** * The Operation object from the Swagger API. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject) * @type {object|null} */ operation: null, /** * The Parameter objects that apply to this request. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameter-object-) * @type {object[]} */ params: [], /** * The Security Requirement objects that apply to this request. * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityRequirementObject) * @type {object[]} */ security: [] }; next(); }
[ "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 * The complete Swagger API object.\n * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object)\n * @type {SwaggerObject|null}\n */", "api", ":", "null", ",", "/**\n * The Swagger path name, as it appears in the Swagger API.\n * (e.g. \"/users/{username}/orders/{orderId}\")\n * @type {string}\n */", "pathName", ":", "\"\"", ",", "/**\n * The Path object from the Swagger API.\n * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject)\n * @type {object|null}\n */", "path", ":", "null", ",", "/**\n * The Operation object from the Swagger API.\n * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject)\n * @type {object|null}\n */", "operation", ":", "null", ",", "/**\n * The Parameter objects that apply to this request.\n * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameter-object-)\n * @type {object[]}\n */", "params", ":", "[", "]", ",", "/**\n * The Security Requirement objects that apply to this request.\n * (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityRequirementObject)\n * @type {object[]}\n */", "security", ":", "[", "]", "}", ";", "next", "(", ")", ";", "}" ]
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.method.toUpperCase(), req.path); } } next(); }
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.method.toUpperCase(), req.path); } } next(); }
[ "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", ".", "method", ".", "toUpperCase", "(", ")", ",", "req", ".", "path", ")", ";", "}", "}", "next", "(", ")", ";", "}" ]
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", ")", ";", "next", "(", ")", ";", "}" ]
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 security requirements for the API req.swagger.security = req.swagger.api.security || []; } next(); }
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 security requirements for the API req.swagger.security = req.swagger.api.security || []; } next(); }
[ "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 security requirements for the API", "req", ".", "swagger", ".", "security", "=", "req", ".", "swagger", ".", "api", ".", "security", "||", "[", "]", ";", "}", "next", "(", ")", ";", "}" ]
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", ".", "swagger", ".", "api", ".", "basePath", ".", "length", ")", ";", "}", "}" ]
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 + "$"); return pathRegExp.test(path); }
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 + "$"); return pathRegExp.test(path); }
[ "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", "+", "\"$\"", ")", ";", "return", "pathRegExp", ".", "test", "(", "path", ")", ";", "}" ]
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 value from the Swagger API res.set(header, responseHeaders[header]); } else { // Set the header to a sensible default switch (header) { case accessControl.allowOrigin: // By default, allow the origin host. Fallback to wild-card. res.set(header, req.get("Origin") || "*"); break; case accessControl.allowMethods: if (req.swagger && req.swagger.path) { // Return the allowed methods for this Swagger path res.set(header, util.getAllowedMethods(req.swagger.path)); } else { // By default, allow all of the requested methods. Fallback to ALL methods. res.set(header, req.get("Access-Control-Request-Method") || swaggerMethods.join(", ").toUpperCase()); } break; case accessControl.allowHeaders: // By default, allow all of the requested headers res.set(header, req.get("Access-Control-Request-Headers") || ""); break; case accessControl.allowCredentials: // By default, allow credentials res.set(header, true); break; case accessControl.maxAge: // By default, access-control expires immediately. res.set(header, 0); break; } } }); if (res.get(accessControl.allowOrigin) === "*") { // If Access-Control-Allow-Origin is wild-carded, then Access-Control-Allow-Credentials must be false res.set("Access-Control-Allow-Credentials", "false"); } else { // If Access-Control-Allow-Origin is set (not wild-carded), then "Vary: Origin" must be set res.vary("Origin"); } next(); }
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 value from the Swagger API res.set(header, responseHeaders[header]); } else { // Set the header to a sensible default switch (header) { case accessControl.allowOrigin: // By default, allow the origin host. Fallback to wild-card. res.set(header, req.get("Origin") || "*"); break; case accessControl.allowMethods: if (req.swagger && req.swagger.path) { // Return the allowed methods for this Swagger path res.set(header, util.getAllowedMethods(req.swagger.path)); } else { // By default, allow all of the requested methods. Fallback to ALL methods. res.set(header, req.get("Access-Control-Request-Method") || swaggerMethods.join(", ").toUpperCase()); } break; case accessControl.allowHeaders: // By default, allow all of the requested headers res.set(header, req.get("Access-Control-Request-Headers") || ""); break; case accessControl.allowCredentials: // By default, allow credentials res.set(header, true); break; case accessControl.maxAge: // By default, access-control expires immediately. res.set(header, 0); break; } } }); if (res.get(accessControl.allowOrigin) === "*") { // If Access-Control-Allow-Origin is wild-carded, then Access-Control-Allow-Credentials must be false res.set("Access-Control-Allow-Credentials", "false"); } else { // If Access-Control-Allow-Origin is set (not wild-carded), then "Vary: Origin" must be set res.vary("Origin"); } next(); }
[ "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 value from the Swagger API", "res", ".", "set", "(", "header", ",", "responseHeaders", "[", "header", "]", ")", ";", "}", "else", "{", "// Set the header to a sensible default", "switch", "(", "header", ")", "{", "case", "accessControl", ".", "allowOrigin", ":", "// By default, allow the origin host. Fallback to wild-card.", "res", ".", "set", "(", "header", ",", "req", ".", "get", "(", "\"Origin\"", ")", "||", "\"*\"", ")", ";", "break", ";", "case", "accessControl", ".", "allowMethods", ":", "if", "(", "req", ".", "swagger", "&&", "req", ".", "swagger", ".", "path", ")", "{", "// Return the allowed methods for this Swagger path", "res", ".", "set", "(", "header", ",", "util", ".", "getAllowedMethods", "(", "req", ".", "swagger", ".", "path", ")", ")", ";", "}", "else", "{", "// By default, allow all of the requested methods. Fallback to ALL methods.", "res", ".", "set", "(", "header", ",", "req", ".", "get", "(", "\"Access-Control-Request-Method\"", ")", "||", "swaggerMethods", ".", "join", "(", "\", \"", ")", ".", "toUpperCase", "(", ")", ")", ";", "}", "break", ";", "case", "accessControl", ".", "allowHeaders", ":", "// By default, allow all of the requested headers", "res", ".", "set", "(", "header", ",", "req", ".", "get", "(", "\"Access-Control-Request-Headers\"", ")", "||", "\"\"", ")", ";", "break", ";", "case", "accessControl", ".", "allowCredentials", ":", "// By default, allow credentials", "res", ".", "set", "(", "header", ",", "true", ")", ";", "break", ";", "case", "accessControl", ".", "maxAge", ":", "// By default, access-control expires immediately.", "res", ".", "set", "(", "header", ",", "0", ")", ";", "break", ";", "}", "}", "}", ")", ";", "if", "(", "res", ".", "get", "(", "accessControl", ".", "allowOrigin", ")", "===", "\"*\"", ")", "{", "// If Access-Control-Allow-Origin is wild-carded, then Access-Control-Allow-Credentials must be false", "res", ".", "set", "(", "\"Access-Control-Allow-Credentials\"", ",", "\"false\"", ")", ";", "}", "else", "{", "// If Access-Control-Allow-Origin is set (not wild-carded), then \"Vary: Origin\" must be set", "res", ".", "vary", "(", "\"Origin\"", ")", ";", "}", "next", "(", ")", ";", "}" ]
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", ".", "path", ")", ";", "res", ".", "send", "(", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
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.operation); } if (req.swagger.path) { // Regardless of whether this is a preflight request, append the OPTIONS response headers headers = headers.concat(getOperationResponseHeaders(req.swagger.path.options)); } // Add the headers to the `corsHeaders` object. First one wins. headers.forEach((header) => { if (corsHeaders[header.name] === undefined) { corsHeaders[header.name] = header.value; } }); } return corsHeaders; }
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.operation); } if (req.swagger.path) { // Regardless of whether this is a preflight request, append the OPTIONS response headers headers = headers.concat(getOperationResponseHeaders(req.swagger.path.options)); } // Add the headers to the `corsHeaders` object. First one wins. headers.forEach((header) => { if (corsHeaders[header.name] === undefined) { corsHeaders[header.name] = header.value; } }); } return corsHeaders; }
[ "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", ".", "operation", ")", ";", "}", "if", "(", "req", ".", "swagger", ".", "path", ")", "{", "// Regardless of whether this is a preflight request, append the OPTIONS response headers", "headers", "=", "headers", ".", "concat", "(", "getOperationResponseHeaders", "(", "req", ".", "swagger", ".", "path", ".", "options", ")", ")", ";", "}", "// Add the headers to the `corsHeaders` object. First one wins.", "headers", ".", "forEach", "(", "(", "header", ")", "=>", "{", "if", "(", "corsHeaders", "[", "header", ".", "name", "]", "===", "undefined", ")", "{", "corsHeaders", "[", "header", ".", "name", "]", "=", "header", ".", "value", ";", "}", "}", ")", ";", "}", "return", "corsHeaders", ";", "}" ]
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", "wins", "." ]
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", "&&", "dataTypes", ".", "indexOf", "(", "schema", ".", "type", ")", "===", "-", "1", ")", "{", "throw", "ono", "(", "{", "status", ":", "500", "}", ",", "\"Invalid JSON schema type: %s\"", ",", "schema", ".", "type", ")", ";", "}", "this", ".", "schema", "=", "schema", ";", "}" ]
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 = schema.default; } else if (schema.example !== undefined) { value = schema.example; } } // Special case for Buffers if (value && value.type === "Buffer" && _.isArray(value.data)) { value = new Buffer(value.data); } // It's not empty, so return the existing value return value; }
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 = schema.default; } else if (schema.example !== undefined) { value = schema.example; } } // Special case for Buffers if (value && value.type === "Buffer" && _.isArray(value.data)) { value = new Buffer(value.data); } // It's not empty, so return the existing value return value; }
[ "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", "=", "schema", ".", "default", ";", "}", "else", "if", "(", "schema", ".", "example", "!==", "undefined", ")", "{", "value", "=", "schema", ".", "example", ";", "}", "}", "// Special case for Buffers", "if", "(", "value", "&&", "value", ".", "type", "===", "\"Buffer\"", "&&", "_", ".", "isArray", "(", "value", ".", "data", ")", ")", "{", "value", "=", "new", "Buffer", "(", "value", ".", "data", ")", ";", "}", "// It's not empty, so return the existing value", "return", "value", ";", "}" ]
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", ")", ")", "{", "router", ".", "param", "(", "param", ",", "pathParamMiddleware", ")", ";", "}", "}", ")", ";", "}" ]
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); // Add each operation parameter _.each(path, (operation) => { _.each(operation.parameters, addParam); }); }); } return _.uniq(params); }
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); // Add each operation parameter _.each(path, (operation) => { _.each(operation.parameters, addParam); }); }); } return _.uniq(params); }
[ "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", ")", ";", "// Add each operation parameter", "_", ".", "each", "(", "path", ",", "(", "operation", ")", "=>", "{", "_", ".", "each", "(", "operation", ".", "parameters", ",", "addParam", ")", ";", "}", ")", ";", "}", ")", ";", "}", "return", "_", ".", "uniq", "(", "params", ")", ";", "}" ]
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", ";", "}", "return", "params", "&&", "params", "[", "paramName", "]", "&&", "(", "params", "[", "paramName", "]", ".", "indexOf", "(", "pathParamMiddleware", ")", ">=", "0", ")", ";", "}" ]
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 === configPath) { if (context.api) { util.debug("%s %s => Sending the Swagger API as JSON", req.method, req.path); res.json(context.api); } else { util.warn("WARNING! The Swagger API is empty. Sending an HTTP 500 response to %s %s", req.method, req.path); res.status(500).json({}); } return; } } next(); }
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 === configPath) { if (context.api) { util.debug("%s %s => Sending the Swagger API as JSON", req.method, req.path); res.json(context.api); } else { util.warn("WARNING! The Swagger API is empty. Sending an HTTP 500 response to %s %s", req.method, req.path); res.status(500).json({}); } return; } } next(); }
[ "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", "===", "configPath", ")", "{", "if", "(", "context", ".", "api", ")", "{", "util", ".", "debug", "(", "\"%s %s => Sending the Swagger API as JSON\"", ",", "req", ".", "method", ",", "req", ".", "path", ")", ";", "res", ".", "json", "(", "context", ".", "api", ")", ";", "}", "else", "{", "util", ".", "warn", "(", "\"WARNING! The Swagger API is empty. Sending an HTTP 500 response to %s %s\"", ",", "req", ".", "method", ",", "req", ".", "path", ")", ";", "res", ".", "status", "(", "500", ")", ".", "json", "(", "{", "}", ")", ";", "}", "return", ";", "}", "}", "next", "(", ")", ";", "}" ]
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", ";", "}", "else", "{", "return", "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] || editCollection[req.method]; } else { mock = queryResource[req.method] || editResource[req.method]; } // Get the current DataStore (this can be changed at any time by third-party code) let db = util.isExpressApp(router) ? router.get("mock data store") || dataStore : dataStore; db.__router = router; // Run the mock util.debug("Running the %s mock", mock.name); mock(req, res, next, db); } else { next(); } }
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] || editCollection[req.method]; } else { mock = queryResource[req.method] || editResource[req.method]; } // Get the current DataStore (this can be changed at any time by third-party code) let db = util.isExpressApp(router) ? router.get("mock data store") || dataStore : dataStore; db.__router = router; // Run the mock util.debug("Running the %s mock", mock.name); mock(req, res, next, db); } else { next(); } }
[ "function", "mockImplementation", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "res", ".", "swagger", ")", "{", "// Determine the semantics of this request\r", "let", "request", "=", "new", "SemanticRequest", "(", "req", ")", ";", "// Determine which mock to run\r", "let", "mock", ";", "if", "(", "request", ".", "isCollection", ")", "{", "mock", "=", "queryCollection", "[", "req", ".", "method", "]", "||", "editCollection", "[", "req", ".", "method", "]", ";", "}", "else", "{", "mock", "=", "queryResource", "[", "req", ".", "method", "]", "||", "editResource", "[", "req", ".", "method", "]", ";", "}", "// Get the current DataStore (this can be changed at any time by third-party code)\r", "let", "db", "=", "util", ".", "isExpressApp", "(", "router", ")", "?", "router", ".", "get", "(", "\"mock data store\"", ")", "||", "dataStore", ":", "dataStore", ";", "db", ".", "__router", "=", "router", ";", "// Run the mock\r", "util", ".", "debug", "(", "\"Running the %s mock\"", ",", "mock", ".", "name", ")", ";", "mock", "(", "req", ",", "res", ",", "next", ",", "db", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
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. // If a default value is specified in the Swagger API, then use it; otherwise generate a value. if (res.get(name) !== undefined) { util.debug(" %s: %s (already set)", name, res.get(name)); } else if (header.default !== undefined) { res.set(name, header.default); util.debug(" %s: %s (default)", name, header.default); } else { switch (name.toLowerCase()) { case "location": res.location(req.baseUrl + (res.swagger.location || req.path)); break; case "last-modified": res.set(name, util.rfc1123(res.swagger.lastModified)); break; case "content-disposition": res.set(name, 'attachment; filename="' + path.basename(res.swagger.location || req.path) + '"'); break; case "set-cookie": // Generate a random "swagger" cookie, or re-use it if it already exists if (req.cookies.swagger === undefined) { res.cookie("swagger", _.uniqueId("random") + _.random(99999999999.9999)); } else { res.cookie("swagger", req.cookies.swagger); } break; default: // Generate a sample value from the schema let sample = new JsonSchema(header).sample(); if (_.isDate(sample)) { res.set(name, util.rfc1123(sample)); } else { res.set(name, _(sample).toString()); } } util.debug(" %s: %s", name, res.get(name)); } }); } } next(); }
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. // If a default value is specified in the Swagger API, then use it; otherwise generate a value. if (res.get(name) !== undefined) { util.debug(" %s: %s (already set)", name, res.get(name)); } else if (header.default !== undefined) { res.set(name, header.default); util.debug(" %s: %s (default)", name, header.default); } else { switch (name.toLowerCase()) { case "location": res.location(req.baseUrl + (res.swagger.location || req.path)); break; case "last-modified": res.set(name, util.rfc1123(res.swagger.lastModified)); break; case "content-disposition": res.set(name, 'attachment; filename="' + path.basename(res.swagger.location || req.path) + '"'); break; case "set-cookie": // Generate a random "swagger" cookie, or re-use it if it already exists if (req.cookies.swagger === undefined) { res.cookie("swagger", _.uniqueId("random") + _.random(99999999999.9999)); } else { res.cookie("swagger", req.cookies.swagger); } break; default: // Generate a sample value from the schema let sample = new JsonSchema(header).sample(); if (_.isDate(sample)) { res.set(name, util.rfc1123(sample)); } else { res.set(name, _(sample).toString()); } } util.debug(" %s: %s", name, res.get(name)); } }); } } next(); }
[ "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.\r", "// If a default value is specified in the Swagger API, then use it; otherwise generate a value.\r", "if", "(", "res", ".", "get", "(", "name", ")", "!==", "undefined", ")", "{", "util", ".", "debug", "(", "\" %s: %s (already set)\"", ",", "name", ",", "res", ".", "get", "(", "name", ")", ")", ";", "}", "else", "if", "(", "header", ".", "default", "!==", "undefined", ")", "{", "res", ".", "set", "(", "name", ",", "header", ".", "default", ")", ";", "util", ".", "debug", "(", "\" %s: %s (default)\"", ",", "name", ",", "header", ".", "default", ")", ";", "}", "else", "{", "switch", "(", "name", ".", "toLowerCase", "(", ")", ")", "{", "case", "\"location\"", ":", "res", ".", "location", "(", "req", ".", "baseUrl", "+", "(", "res", ".", "swagger", ".", "location", "||", "req", ".", "path", ")", ")", ";", "break", ";", "case", "\"last-modified\"", ":", "res", ".", "set", "(", "name", ",", "util", ".", "rfc1123", "(", "res", ".", "swagger", ".", "lastModified", ")", ")", ";", "break", ";", "case", "\"content-disposition\"", ":", "res", ".", "set", "(", "name", ",", "'attachment; filename=\"'", "+", "path", ".", "basename", "(", "res", ".", "swagger", ".", "location", "||", "req", ".", "path", ")", "+", "'\"'", ")", ";", "break", ";", "case", "\"set-cookie\"", ":", "// Generate a random \"swagger\" cookie, or re-use it if it already exists\r", "if", "(", "req", ".", "cookies", ".", "swagger", "===", "undefined", ")", "{", "res", ".", "cookie", "(", "\"swagger\"", ",", "_", ".", "uniqueId", "(", "\"random\"", ")", "+", "_", ".", "random", "(", "99999999999.9999", ")", ")", ";", "}", "else", "{", "res", ".", "cookie", "(", "\"swagger\"", ",", "req", ".", "cookies", ".", "swagger", ")", ";", "}", "break", ";", "default", ":", "// Generate a sample value from the schema\r", "let", "sample", "=", "new", "JsonSchema", "(", "header", ")", ".", "sample", "(", ")", ";", "if", "(", "_", ".", "isDate", "(", "sample", ")", ")", "{", "res", ".", "set", "(", "name", ",", "util", ".", "rfc1123", "(", "sample", ")", ")", ";", "}", "else", "{", "res", ".", "set", "(", "name", ",", "_", "(", "sample", ")", ".", "toString", "(", ")", ")", ";", "}", "}", "util", ".", "debug", "(", "\" %s: %s\"", ",", "name", ",", "res", ".", "get", "(", "name", ")", ")", ";", "}", "}", ")", ";", "}", "}", "next", "(", ")", ";", "}" ]
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 { // Serialize the response body according to the response schema let schema = new JsonSchema(res.swagger.schema); let serialized = schema.serialize(res.swagger.wrap(res.body)); switch (res.swagger.schema.type) { case "object": case "array": case undefined: sendObject(req, res, next, serialized); break; case "file": sendFile(req, res, next, serialized); break; default: sendText(req, res, next, serialized); } } } else { next(); } }
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 { // Serialize the response body according to the response schema let schema = new JsonSchema(res.swagger.schema); let serialized = schema.serialize(res.swagger.wrap(res.body)); switch (res.swagger.schema.type) { case "object": case "array": case undefined: sendObject(req, res, next, serialized); break; case "file": sendFile(req, res, next, serialized); break; default: sendText(req, res, next, serialized); } } } else { next(); } }
[ "function", "mockResponseBody", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "res", ".", "swagger", ")", "{", "if", "(", "res", ".", "swagger", ".", "isEmpty", ")", "{", "// There is no response schema, so send an empty response\r", "util", ".", "debug", "(", "\"%s %s does not have a response schema. Sending an empty response\"", ",", "req", ".", "method", ",", "req", ".", "path", ")", ";", "res", ".", "send", "(", ")", ";", "}", "else", "{", "// Serialize the response body according to the response schema\r", "let", "schema", "=", "new", "JsonSchema", "(", "res", ".", "swagger", ".", "schema", ")", ";", "let", "serialized", "=", "schema", ".", "serialize", "(", "res", ".", "swagger", ".", "wrap", "(", "res", ".", "body", ")", ")", ";", "switch", "(", "res", ".", "swagger", ".", "schema", ".", "type", ")", "{", "case", "\"object\"", ":", "case", "\"array\"", ":", "case", "undefined", ":", "sendObject", "(", "req", ",", "res", ",", "next", ",", "serialized", ")", ";", "break", ";", "case", "\"file\"", ":", "sendFile", "(", "req", ",", "res", ",", "next", ",", "serialized", ")", ";", "break", ";", "default", ":", "sendText", "(", "req", ",", "res", ",", "next", ",", "serialized", ")", ";", "}", "}", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
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(_(data).toString()); }
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(_(data).toString()); }
[ "function", "sendText", "(", "req", ",", "res", ",", "next", ",", "data", ")", "{", "setContentType", "(", "req", ",", "res", ",", "[", "\"text\"", ",", "\"html\"", ",", "\"text/*\"", ",", "\"application/*\"", "]", ",", "// allow these types\r", "[", "\"json\"", ",", "\"*/json\"", ",", "\"+json\"", ",", "\"application/octet-stream\"", "]", ")", ";", "// don't allow these types\r", "util", ".", "debug", "(", "\"Serializing the response as a string\"", ")", ";", "res", ".", "send", "(", "_", "(", "data", ")", ".", "toString", "(", ")", ")", ";", "}" ]
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 "produces" MIME types are specified in the Swagger API, so defaulting to %s', supported[0]); res.type(supported[0]); } else { // Find the first MIME type that we support let match = _.find(produces, (mimeType) => { return typeIs.is(mimeType, supported) && (!excluded || !typeIs.is(mimeType, excluded)); }); if (match) { util.debug("Using %s MIME type, which is allowed by the Swagger API", match); res.type(match); } else { util.warn( 'WARNING! %s %s produces the MIME types that are not supported (%s). Using "%s" instead', req.method, req.path, produces.join(", "), supported[0] ); res.type(supported[0]); } } }
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 "produces" MIME types are specified in the Swagger API, so defaulting to %s', supported[0]); res.type(supported[0]); } else { // Find the first MIME type that we support let match = _.find(produces, (mimeType) => { return typeIs.is(mimeType, supported) && (!excluded || !typeIs.is(mimeType, excluded)); }); if (match) { util.debug("Using %s MIME type, which is allowed by the Swagger API", match); res.type(match); } else { util.warn( 'WARNING! %s %s produces the MIME types that are not supported (%s). Using "%s" instead', req.method, req.path, produces.join(", "), supported[0] ); res.type(supported[0]); } } }
[ "function", "setContentType", "(", "req", ",", "res", ",", "supported", ",", "excluded", ")", "{", "// Get the MIME types that this operation produces\r", "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\r", "util", ".", "debug", "(", "'No \"produces\" MIME types are specified in the Swagger API, so defaulting to %s'", ",", "supported", "[", "0", "]", ")", ";", "res", ".", "type", "(", "supported", "[", "0", "]", ")", ";", "}", "else", "{", "// Find the first MIME type that we support\r", "let", "match", "=", "_", ".", "find", "(", "produces", ",", "(", "mimeType", ")", "=>", "{", "return", "typeIs", ".", "is", "(", "mimeType", ",", "supported", ")", "&&", "(", "!", "excluded", "||", "!", "typeIs", ".", "is", "(", "mimeType", ",", "excluded", ")", ")", ";", "}", ")", ";", "if", "(", "match", ")", "{", "util", ".", "debug", "(", "\"Using %s MIME type, which is allowed by the Swagger API\"", ",", "match", ")", ";", "res", ".", "type", "(", "match", ")", ";", "}", "else", "{", "util", ".", "warn", "(", "'WARNING! %s %s produces the MIME types that are not supported (%s). Using \"%s\" instead'", ",", "req", ".", "method", ",", "req", ".", "path", ",", "produces", ".", "join", "(", "\", \"", ")", ",", "supported", "[", "0", "]", ")", ";", "res", ".", "type", "(", "supported", "[", "0", "]", ")", ";", "}", "}", "}" ]
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 types to exclude from the supported list
[ "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", ")", ";", "}", "return", "isCollection", ";", "}" ]
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 {Request} req @returns {boolean}
[ "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", "." ]
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) { return response.isCollection; } } } }
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) { return response.isCollection; } } } }
[ "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", ")", "{", "return", "response", ".", "isCollection", ";", "}", "}", "}", "}" ]
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", "(", "\"{\"", ")", ";", "return", "(", "lastParam", ">", "lastSlash", ")", ";", "}" ]
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 following paths are all considered to be collection requests, because their final path segment is NOT a parameter: - /users - /products/{productId}/reviews - /{country}/{state}/{city}/neighborhoods/streets @param {Request} req @returns {boolean}
[ "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 empty response should be sent. * @type {boolean} */ this.isEmpty = !response.schema; /** * Indicates whether the response should be a single resource, or a collection. * @type {boolean} */ this.isCollection = false; /** * Indicates whether the response schema is a wrapper around the actual resource data. * It's common for RESTful APIs to include a response wrapper with additional metadata, * and one of the properties of the wrapper is the actual resource data. * @type {boolean} */ this.isWrapped = false; /** * If the response is wrapped, then this is the name of the wrapper property that * contains the actual resource data. * @type {string} */ this.wrapperProperty = ""; /** * The date/time that the response data was last modified. * This is used to set the Last-Modified HTTP header (if defined in the Swagger API) * * Each mock implementation sets this to the appropriate value. * * @type {Date} */ this.lastModified = null; /** * The location (URL) of the REST resource. * This is used to set the Location HTTP header (if defined in the Swagger API) * * Some mocks implementations set this value. If left blank, then the Location header * will be set to the current path. * * @type {string} */ this.location = ""; if (!this.isEmpty) { this.setWrapperInfo(response, path); } }
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 empty response should be sent. * @type {boolean} */ this.isEmpty = !response.schema; /** * Indicates whether the response should be a single resource, or a collection. * @type {boolean} */ this.isCollection = false; /** * Indicates whether the response schema is a wrapper around the actual resource data. * It's common for RESTful APIs to include a response wrapper with additional metadata, * and one of the properties of the wrapper is the actual resource data. * @type {boolean} */ this.isWrapped = false; /** * If the response is wrapped, then this is the name of the wrapper property that * contains the actual resource data. * @type {string} */ this.wrapperProperty = ""; /** * The date/time that the response data was last modified. * This is used to set the Last-Modified HTTP header (if defined in the Swagger API) * * Each mock implementation sets this to the appropriate value. * * @type {Date} */ this.lastModified = null; /** * The location (URL) of the REST resource. * This is used to set the Location HTTP header (if defined in the Swagger API) * * Some mocks implementations set this value. If left blank, then the Location header * will be set to the current path. * * @type {string} */ this.location = ""; if (!this.isEmpty) { this.setWrapperInfo(response, path); } }
[ "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\n * @type {object|null}\n */", "this", ".", "headers", "=", "response", ".", "headers", "||", "null", ";", "/**\n * If true, then an empty response should be sent.\n * @type {boolean}\n */", "this", ".", "isEmpty", "=", "!", "response", ".", "schema", ";", "/**\n * Indicates whether the response should be a single resource, or a collection.\n * @type {boolean}\n */", "this", ".", "isCollection", "=", "false", ";", "/**\n * Indicates whether the response schema is a wrapper around the actual resource data.\n * It's common for RESTful APIs to include a response wrapper with additional metadata,\n * and one of the properties of the wrapper is the actual resource data.\n * @type {boolean}\n */", "this", ".", "isWrapped", "=", "false", ";", "/**\n * If the response is wrapped, then this is the name of the wrapper property that\n * contains the actual resource data.\n * @type {string}\n */", "this", ".", "wrapperProperty", "=", "\"\"", ";", "/**\n * The date/time that the response data was last modified.\n * This is used to set the Last-Modified HTTP header (if defined in the Swagger API)\n *\n * Each mock implementation sets this to the appropriate value.\n *\n * @type {Date}\n */", "this", ".", "lastModified", "=", "null", ";", "/**\n * The location (URL) of the REST resource.\n * This is used to set the Location HTTP header (if defined in the Swagger API)\n *\n * Some mocks implementations set this value. If left blank, then the Location header\n * will be set to the current path.\n *\n * @type {string}\n */", "this", ".", "location", "=", "\"\"", ";", "if", "(", "!", "this", ".", "isEmpty", ")", "{", "this", ".", "setWrapperInfo", "(", "response", ",", "path", ")", ";", "}", "}" ]
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