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

View File

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

View File

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

View File

@ -37,7 +37,7 @@ const oneMinute = oneSecond * 60
const oneHour = oneMinute * 60 const oneHour = oneMinute * 60
function computeCounters(stream) { function computeCounters(stream) {
return new Promise(function(resolve, reject) { return new Promise((resolve, reject) => {
const counters = {} const counters = {}
const expireat = {} const expireat = {}
@ -113,11 +113,11 @@ function computeCounters(stream) {
} }
function processLogs(stream) { function processLogs(stream) {
return computeCounters(stream).then(function({ counters, expireat }) { return computeCounters(stream).then(({ counters, expireat }) => {
Object.keys(counters).forEach(function(key) { Object.keys(counters).forEach(key => {
const values = counters[key] const values = counters[key]
Object.keys(values).forEach(function(member) { Object.keys(values).forEach(member => {
db.zincrby(key, values[member], member) db.zincrby(key, values[member], member)
}) })
@ -127,7 +127,7 @@ function processLogs(stream) {
} }
function ingestLogs(zone, startSeconds, endSeconds) { function ingestLogs(zone, startSeconds, endSeconds) {
return new Promise(function(resolve) { return new Promise(resolve => {
console.log( console.log(
'info: Started ingesting logs for %s from %s to %s', 'info: Started ingesting logs for %s from %s to %s',
zone.name, zone.name,
@ -138,7 +138,7 @@ function ingestLogs(zone, startSeconds, endSeconds) {
const startFetchTime = Date.now() const startFetchTime = Date.now()
resolve( resolve(
cf.getLogs(zone.id, startSeconds, endSeconds).then(function(stream) { cf.getLogs(zone.id, startSeconds, endSeconds).then(stream => {
const endFetchTime = Date.now() const endFetchTime = Date.now()
console.log( console.log(
@ -150,7 +150,7 @@ function ingestLogs(zone, startSeconds, endSeconds) {
const startProcessTime = Date.now() const startProcessTime = Date.now()
return processLogs(stream).then(function() { return processLogs(stream).then(() => {
const endProcessTime = Date.now() const endProcessTime = Date.now()
console.log( console.log(
@ -226,8 +226,8 @@ function startZone(zone) {
takeATurn() takeATurn()
} }
Promise.all(DomainNames.map(cf.getZones)).then(function(results) { Promise.all(DomainNames.map(cf.getZones)).then(results => {
const zones = results.reduce(function(memo, zones) { const zones = results.reduce((memo, zones) => {
return memo.concat(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'). * depending on which one is available, similar to require('lib/file').
*/ */
function findFile(base, useIndex, callback) { function findFile(base, useIndex, callback) {
FindExtensions.reduceRight(function(next, ext) { FindExtensions.reduceRight((next, ext) => {
const file = base + ext const file = base + ext
return function() { return function() {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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