Use arrow functions for callbacks

This commit is contained in:
MICHAEL JACKSON 2017-11-08 10:14:46 -08:00
parent a8ab0b7dab
commit b614f8646d
14 changed files with 71 additions and 78 deletions

View File

@ -22,10 +22,10 @@ function get(path, headers) {
function getJSON(path, headers) {
return get(path, headers)
.then(function(res) {
.then(res => {
return res.json()
})
.then(function(data) {
.then(data => {
if (!data.success) {
console.error(`CloudflareAPI.getJSON failed at ${path}`)
console.error(data)
@ -38,11 +38,11 @@ function getJSON(path, headers) {
function getZones(domains) {
return Promise.all(
(Array.isArray(domains) ? domains : [domains]).map(function(domain) {
(Array.isArray(domains) ? domains : [domains]).map(domain => {
return getJSON(`/zones?name=${domain}`)
})
).then(function(results) {
return results.reduce(function(memo, zones) {
).then(results => {
return results.reduce((memo, zones) => {
return memo.concat(zones)
})
})
@ -64,14 +64,14 @@ function reduceResults(target, values) {
function getZoneAnalyticsDashboard(zones, since, until) {
return Promise.all(
(Array.isArray(zones) ? zones : [zones]).map(function(zone) {
(Array.isArray(zones) ? zones : [zones]).map(zone => {
return getJSON(
`/zones/${
zone.id
}/analytics/dashboard?since=${since.toISOString()}&until=${until.toISOString()}`
)
})
).then(function(results) {
).then(results => {
return results.reduce(reduceResults)
})
}
@ -82,10 +82,10 @@ function getJSONStream(path, headers) {
})
return get(path, acceptGzipHeaders)
.then(function(res) {
.then(res => {
return res.body.pipe(gunzip())
})
.then(function(stream) {
.then(stream => {
return stream.pipe(ndjson.parse())
})
}

View File

@ -4,7 +4,7 @@ const db = require('./RedisClient')
const PackageBlacklist = require('./PackageBlacklist').blacklist
function prunePackages(packagesMap) {
PackageBlacklist.forEach(function(packageName) {
PackageBlacklist.forEach(packageName => {
delete packagesMap[packageName]
})
@ -26,15 +26,16 @@ function createMinuteKey(date) {
function createScoresMap(array) {
const map = {}
for (let i = 0; i < array.length; i += 2)
for (let i = 0; i < array.length; i += 2) {
map[array[i]] = parseInt(array[i + 1], 10)
}
return map
}
function getScoresMap(key, n = 100) {
return new Promise(function(resolve, reject) {
db.zrevrange(key, 0, n, 'withscores', function(error, value) {
return new Promise((resolve, reject) => {
db.zrevrange(key, 0, n, 'withscores', (error, value) => {
if (error) {
reject(error)
} else {
@ -67,7 +68,7 @@ function addDailyMetricsToTimeseries(timeseries) {
getPackageRequests(since),
getPackageBandwidth(since),
getProtocolRequests(since)
]).then(function(results) {
]).then(results => {
timeseries.requests.package = results[0]
timeseries.bandwidth.package = results[1]
timeseries.requests.protocol = results[2]
@ -76,8 +77,8 @@ function addDailyMetricsToTimeseries(timeseries) {
}
function sumMaps(maps) {
return maps.reduce(function(memo, map) {
Object.keys(map).forEach(function(key) {
return maps.reduce((memo, map) => {
Object.keys(map).forEach(key => {
memo[key] = (memo[key] || 0) + map[key]
})
@ -87,23 +88,19 @@ function sumMaps(maps) {
function addDailyMetrics(result) {
return Promise.all(result.timeseries.map(addDailyMetricsToTimeseries)).then(
function() {
() => {
result.totals.requests.package = sumMaps(
result.timeseries.map(function(timeseries) {
result.timeseries.map(timeseries => {
return timeseries.requests.package
})
)
result.totals.bandwidth.package = sumMaps(
result.timeseries.map(function(timeseries) {
return timeseries.bandwidth.package
})
result.timeseries.map(timeseries => timeseries.bandwidth.package)
)
result.totals.requests.protocol = sumMaps(
result.timeseries.map(function(timeseries) {
return timeseries.requests.protocol
})
result.timeseries.map(timeseries => timeseries.requests.protocol)
)
return result
@ -143,15 +140,13 @@ function extractPublicInfo(data) {
const DomainNames = ['unpkg.com', 'npmcdn.com']
function fetchStats(since, until) {
return cf.getZones(DomainNames).then(function(zones) {
return cf
.getZoneAnalyticsDashboard(zones, since, until)
.then(function(dashboard) {
return {
timeseries: dashboard.timeseries.map(extractPublicInfo),
totals: extractPublicInfo(dashboard.totals)
}
})
return cf.getZones(DomainNames).then(zones => {
return cf.getZoneAnalyticsDashboard(zones, since, until).then(dashboard => {
return {
timeseries: dashboard.timeseries.map(extractPublicInfo),
totals: extractPublicInfo(dashboard.totals)
}
})
})
}
@ -164,7 +159,7 @@ function getStats(since, until, callback) {
if (until - since > oneDay) promise = promise.then(addDailyMetrics)
promise.then(function(value) {
promise.then(value => {
callback(null, value)
}, callback)
}

View File

@ -3,14 +3,14 @@ const createServer = require('./createServer')
describe('The server app', function() {
let app
beforeEach(function() {
beforeEach(() => {
app = createServer()
})
it('rejects invalid package names', function(done) {
request(app)
.get('/_invalid/index.js')
.then(function(res) {
.then(res => {
expect(res.statusCode).toBe(403)
done()
})
@ -19,7 +19,7 @@ describe('The server app', function() {
it('redirects invalid query params', function(done) {
request(app)
.get('/react?main=index&invalid')
.then(function(res) {
.then(res => {
expect(res.statusCode).toBe(302)
expect(res.headers.location).toBe('/react?main=index')
done()
@ -29,7 +29,7 @@ describe('The server app', function() {
it('redirects /_meta to ?meta', function(done) {
request(app)
.get('/_meta/react?main=index')
.then(function(res) {
.then(res => {
expect(res.statusCode).toBe(302)
expect(res.headers.location).toBe('/react?main=index&meta')
done()

View File

@ -37,7 +37,7 @@ const oneMinute = oneSecond * 60
const oneHour = oneMinute * 60
function computeCounters(stream) {
return new Promise(function(resolve, reject) {
return new Promise((resolve, reject) => {
const counters = {}
const expireat = {}
@ -113,11 +113,11 @@ function computeCounters(stream) {
}
function processLogs(stream) {
return computeCounters(stream).then(function({ counters, expireat }) {
Object.keys(counters).forEach(function(key) {
return computeCounters(stream).then(({ counters, expireat }) => {
Object.keys(counters).forEach(key => {
const values = counters[key]
Object.keys(values).forEach(function(member) {
Object.keys(values).forEach(member => {
db.zincrby(key, values[member], member)
})
@ -127,7 +127,7 @@ function processLogs(stream) {
}
function ingestLogs(zone, startSeconds, endSeconds) {
return new Promise(function(resolve) {
return new Promise(resolve => {
console.log(
'info: Started ingesting logs for %s from %s to %s',
zone.name,
@ -138,7 +138,7 @@ function ingestLogs(zone, startSeconds, endSeconds) {
const startFetchTime = Date.now()
resolve(
cf.getLogs(zone.id, startSeconds, endSeconds).then(function(stream) {
cf.getLogs(zone.id, startSeconds, endSeconds).then(stream => {
const endFetchTime = Date.now()
console.log(
@ -150,7 +150,7 @@ function ingestLogs(zone, startSeconds, endSeconds) {
const startProcessTime = Date.now()
return processLogs(stream).then(function() {
return processLogs(stream).then(() => {
const endProcessTime = Date.now()
console.log(
@ -226,8 +226,8 @@ function startZone(zone) {
takeATurn()
}
Promise.all(DomainNames.map(cf.getZones)).then(function(results) {
const zones = results.reduce(function(memo, zones) {
Promise.all(DomainNames.map(cf.getZones)).then(results => {
const zones = results.reduce((memo, zones) => {
return memo.concat(zones)
})

View File

@ -20,7 +20,7 @@ const FindExtensions = ['', '.js', '.json']
* depending on which one is available, similar to require('lib/file').
*/
function findFile(base, useIndex, callback) {
FindExtensions.reduceRight(function(next, ext) {
FindExtensions.reduceRight((next, ext) => {
const file = base + ext
return function() {

View File

@ -19,7 +19,7 @@ function queryIsKnown(query) {
function sanitizeQuery(query) {
const saneQuery = {}
Object.keys(query).forEach(function(param) {
Object.keys(query).forEach(param => {
if (isKnownQueryParam(param)) saneQuery[param] = query[param]
})

View File

@ -13,7 +13,7 @@ function createMutex(doWork) {
]
doWork(payload, function(error, value) {
mutex[key].forEach(function(callback) {
mutex[key].forEach(callback => {
callback(error, value)
})
})

View File

@ -1,7 +1,7 @@
function createSearch(query) {
const params = []
Object.keys(query).forEach(function(param) {
Object.keys(query).forEach(param => {
if (query[param] === '') {
params.push(param) // Omit the trailing "=" from param=
} else {

View File

@ -8,7 +8,7 @@ const IndexPage = require('../components/IndexPage')
const e = React.createElement
function getEntries(dir) {
return new Promise(function(resolve, reject) {
return new Promise((resolve, reject) => {
fs.readdir(dir, function(error, files) {
if (error) {
reject(error)
@ -16,8 +16,8 @@ function getEntries(dir) {
resolve(
Promise.all(
files.map(file => getFileStats(path.join(dir, file)))
).then(function(statsArray) {
return statsArray.map(function(stats, index) {
).then(statsArray => {
return statsArray.map((stats, index) => {
return { file: files[index], stats }
})
})

View File

@ -6,26 +6,24 @@ const getFileStats = require('./getFileStats')
const getFileType = require('./getFileType')
function getEntries(dir, file, maximumDepth) {
return new Promise(function(resolve, reject) {
return new Promise((resolve, reject) => {
fs.readdir(path.join(dir, file), function(error, files) {
if (error) {
reject(error)
} else {
resolve(
Promise.all(
files.map(function(f) {
return getFileStats(path.join(dir, file, f))
})
).then(function(statsArray) {
files.map(f => getFileStats(path.join(dir, file, f)))
).then(statsArray => {
return Promise.all(
statsArray.map(function(stats, index) {
return getMetadataRecursive(
statsArray.map((stats, index) =>
getMetadataRecursive(
dir,
path.join(file, files[index]),
stats,
maximumDepth - 1
)
})
)
)
})
)
@ -39,7 +37,7 @@ function formatTime(time) {
}
function getIntegrity(file) {
return new Promise(function(resolve, reject) {
return new Promise((resolve, reject) => {
fs.readFile(file, function(error, data) {
if (error) {
reject(error)
@ -60,7 +58,7 @@ function getMetadataRecursive(dir, file, stats, maximumDepth) {
}
if (stats.isFile()) {
return getIntegrity(path.join(dir, file)).then(function(integrity) {
return getIntegrity(path.join(dir, file)).then(integrity => {
metadata.integrity = integrity
return metadata
})
@ -69,7 +67,7 @@ function getMetadataRecursive(dir, file, stats, maximumDepth) {
if (!stats.isDirectory() || maximumDepth === 0)
return Promise.resolve(metadata)
return getEntries(dir, file, maximumDepth).then(function(files) {
return getEntries(dir, file, maximumDepth).then(files => {
metadata.files = files
return metadata
})

View File

@ -26,7 +26,7 @@ function ignoreSymlinks(file, headers) {
}
function extractResponse(response, outputDir) {
return new Promise(function(resolve, reject) {
return new Promise((resolve, reject) => {
const extract = tar.extract(outputDir, {
readable: true, // All dirs/files should be readable.
map: stripNamePrefix,
@ -44,12 +44,12 @@ function extractResponse(response, outputDir) {
function fetchAndExtract(tarballURL, outputDir) {
console.log(`info: Fetching ${tarballURL} and extracting to ${outputDir}`)
return fetch(tarballURL).then(function(response) {
return fetch(tarballURL).then(response => {
return extractResponse(response, outputDir)
})
}
const fetchMutex = createMutex(function(payload, callback) {
const fetchMutex = createMutex((payload, callback) => {
const { tarballURL, outputDir } = payload
fs.access(outputDir, function(error) {
@ -61,7 +61,7 @@ const fetchMutex = createMutex(function(payload, callback) {
if (error) {
callback(error)
} else {
fetchAndExtract(tarballURL, outputDir).then(function() {
fetchAndExtract(tarballURL, outputDir).then(() => {
callback()
}, callback)
}

View File

@ -22,7 +22,7 @@ function fetchPackageInfo(packageName) {
headers: {
Accept: 'application/json'
}
}).then(function(res) {
}).then(res => {
return res.status === 404 ? null : res.json()
})
}
@ -31,7 +31,7 @@ const PackageNotFound = 'PackageNotFound'
// This mutex prevents multiple concurrent requests to
// the registry for the same package info.
const fetchMutex = createMutex(function(packageName, callback) {
const fetchMutex = createMutex((packageName, callback) => {
fetchPackageInfo(packageName).then(
function(value) {
if (value == null) {

View File

@ -5,7 +5,7 @@ function getAssetPaths(packageName, version) {
const entries = assetPathsIndex[packageName]
if (entries) {
const matchingEntry = entries.find(function(entry) {
const matchingEntry = entries.find(entry => {
const range = entry[0]
if (range == null || semver.satisfies(version, range)) return entry

View File

@ -2,15 +2,15 @@ const searchIndex = require('./searchIndex')
const getAssetPaths = require('./getAssetPaths')
function enhanceHit(hit) {
return new Promise(function(resolve, reject) {
return new Promise((resolve, reject) => {
const assetPaths = getAssetPaths(hit.name, hit.version)
if (assetPaths) {
// TODO: Double check the package metadata to ensure the files
// haven't moved from the paths in the index?
hit.assets = assetPaths.map(function(path) {
return `https://unpkg.com/${hit.name}@${hit.version}${path}`
})
hit.assets = assetPaths.map(
path => `https://unpkg.com/${hit.name}@${hit.version}${path}`
)
resolve(hit)
} else {
@ -30,7 +30,7 @@ function concat(string) {
}
function search(query, page) {
return new Promise(function(resolve, reject) {
return new Promise((resolve, reject) => {
const hitsPerPage = 10
const params = {
@ -61,7 +61,7 @@ function search(query, page) {
reject(error)
} else {
resolve(
Promise.all(value.hits.map(enhanceHit)).then(function(hits) {
Promise.all(value.hits.map(enhanceHit)).then(hits => {
const totalHits = value.nbHits
const totalPages = value.nbPages