Skip to content

Commit

Permalink
Minor refactor: expose custom promisify function from legacy request …
Browse files Browse the repository at this point in the history
…handler

Cherry-picked from #3410; should simplify reworking it.
  • Loading branch information
paulmelnikow committed Jul 5, 2019
1 parent 5d06503 commit a2d3ab4
Showing 1 changed file with 23 additions and 18 deletions.
41 changes: 23 additions & 18 deletions core/base-service/legacy-request-handler.js
Expand Up @@ -63,6 +63,27 @@ function flattenQueryParams(queryParams) {
return Array.from(union).sort()
}

// Wrapper around `cachingRequest` that returns a promise rather than needing
// to pass a callback.
function promisify(cachingRequest) {
return (uri, options) =>
new Promise((resolve, reject) => {
cachingRequest(uri, options, (err, res, buffer) => {
if (err) {
if (err instanceof ShieldsRuntimeError) {
reject(err)
} else {
// Wrap the error in an Inaccessible so it can be identified
// by the BaseService handler.
reject(new Inaccessible({ underlyingError: err }))
}
} else {
resolve({ res, buffer })
}
})
})
}

// handlerOptions can contain:
// - handler: The service's request handler function
// - queryParams: An array of the field names of any custom query parameters
Expand Down Expand Up @@ -231,24 +252,7 @@ function handleRequest(cacheHeaderConfig, handlerOptions) {
})
}

// Wrapper around `cachingRequest` that returns a promise rather than
// needing to pass a callback.
cachingRequest.asPromise = (uri, options) =>
new Promise((resolve, reject) => {
cachingRequest(uri, options, (err, res, buffer) => {
if (err) {
if (err instanceof ShieldsRuntimeError) {
reject(err)
} else {
// Wrap the error in an Inaccessible so it can be identified
// by the BaseService handler.
reject(new Inaccessible({ underlyingError: err }))
}
} else {
resolve({ res, buffer })
}
})
})
cachingRequest.asPromise = promisify(cachingRequest)

vendorDomain.run(() => {
const result = handlerOptions.handler(
Expand Down Expand Up @@ -304,6 +308,7 @@ function clearRequestCache() {

module.exports = {
handleRequest,
promisify,
clearRequestCache,
// Expose for testing.
_requestCache: requestCache,
Expand Down

0 comments on commit a2d3ab4

Please sign in to comment.