This repository was archived by the owner on Sep 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
Fix async and callback combo handling #166
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,7 +7,7 @@ const path = require("path"); | |
const getPort = require("get-port"); | ||
const chokidar = require("chokidar"); | ||
const jwtDecode = require("jwt-decode"); | ||
// const chalk = require("chalk"); | ||
const chalk = require("chalk"); | ||
const { | ||
NETLIFYDEVLOG, | ||
// NETLIFYDEVWARN, | ||
|
@@ -27,60 +27,10 @@ function handleErr(err, response) { | |
console.log(`${NETLIFYDEVERR} Error during invocation: `, err); // eslint-disable-line no-console | ||
} | ||
|
||
function createCallback(response) { | ||
return function(err, lambdaResponse) { | ||
if (err) { | ||
return handleErr(err, response); | ||
} | ||
if (!Number(lambdaResponse.statusCode)) { | ||
console.log( | ||
`${NETLIFYDEVERR} Your function response must have a numerical statusCode. You gave: $`, | ||
lambdaResponse.statusCode | ||
); | ||
return handleErr("Incorrect function response statusCode", response); | ||
} | ||
if (typeof lambdaResponse.body !== "string") { | ||
console.log( | ||
`${NETLIFYDEVERR} Your function response must have a string body. You gave:`, | ||
lambdaResponse.body | ||
); | ||
return handleErr("Incorrect function response body", response); | ||
} | ||
|
||
response.statusCode = lambdaResponse.statusCode; | ||
// eslint-disable-line guard-for-in | ||
for (const key in lambdaResponse.headers) { | ||
response.setHeader(key, lambdaResponse.headers[key]); | ||
} | ||
response.write( | ||
lambdaResponse.isBase64Encoded | ||
? Buffer.from(lambdaResponse.body, "base64") | ||
: lambdaResponse.body | ||
); | ||
response.end(); | ||
}; | ||
} | ||
|
||
function promiseCallback(promise, callback) { | ||
if (!promise) return; | ||
if (typeof promise.then !== "function") return; | ||
if (typeof callback !== "function") return; | ||
|
||
promise.then( | ||
function(data) { | ||
callback(null, data); | ||
}, | ||
function(err) { | ||
callback(err, null); | ||
} | ||
); | ||
} | ||
|
||
// function getHandlerPath(functionPath) { | ||
// if (functionPath.match(/\.js$/)) { | ||
// return functionPath; | ||
// } | ||
|
||
// return path.join(functionPath, `${path.basename(functionPath)}.js`); | ||
// } | ||
|
||
|
@@ -130,7 +80,12 @@ function createHandler(dir) { | |
|
||
Object.keys(functions).forEach(name => { | ||
const fn = functions[name]; | ||
const clearCache = () => { | ||
const clearCache = action => () => { | ||
console.log( | ||
`${NETLIFYDEVLOG} function ${chalk.yellow( | ||
name | ||
)} ${action}, reloading...` | ||
); // eslint-disable-line no-console | ||
const before = module.paths; | ||
module.paths = [fn.moduleDir]; | ||
delete require.cache[require.resolve(fn.functionPath)]; | ||
|
@@ -144,9 +99,9 @@ function createHandler(dir) { | |
ignored: /node_modules/ | ||
}); | ||
fn.watcher | ||
.on("add", clearCache) | ||
.on("change", clearCache) | ||
.on("unlink", clearCache); | ||
.on("add", clearCache("added")) | ||
.on("change", clearCache("modified")) | ||
.on("unlink", clearCache("deleted")); | ||
}); | ||
|
||
return function(request, response) { | ||
|
@@ -167,6 +122,11 @@ function createHandler(dir) { | |
try { | ||
module.paths = [moduleDir]; | ||
handler = require(functionPath); | ||
if (typeof handler.handler !== "function") { | ||
throw new Error( | ||
`function ${functionPath} must export a function named handler` | ||
); | ||
} | ||
module.paths = before; | ||
} catch (error) { | ||
module.paths = before; | ||
|
@@ -180,7 +140,7 @@ function createHandler(dir) { | |
if (body instanceof Buffer) { | ||
isBase64Encoded = true; | ||
body = body.toString("base64"); | ||
} else if(typeof(body) === "string") { | ||
} else if (typeof body === "string") { | ||
// body is already processed as string | ||
} else { | ||
body = ""; | ||
|
@@ -195,24 +155,96 @@ function createHandler(dir) { | |
isBase64Encoded: isBase64Encoded | ||
}; | ||
|
||
let callbackWasCalled = false; | ||
const callback = createCallback(response); | ||
const promise = handler.handler( | ||
lambdaRequest, | ||
{ clientContext: buildClientContext(request.headers) || {} }, | ||
callback | ||
); | ||
promiseCallback(promise, callback); | ||
/** guard against using BOTH async and callback */ | ||
if (callbackWasCalled && promise && typeof promise.then === "function") { | ||
throw new Error( | ||
"Error: your function seems to be using both a callback and returning a promise (aka async function). This is invalid, pick one. (Hint: async!)" | ||
); | ||
} else { | ||
// it is definitely an async function with no callback called, good. | ||
promiseCallback(promise, callback); | ||
} | ||
|
||
/** need to keep createCallback in scope so we can know if cb was called AND handler is async */ | ||
function createCallback(response) { | ||
return function(err, lambdaResponse) { | ||
callbackWasCalled = true; | ||
if (err) { | ||
return handleErr(err, response); | ||
} | ||
if (lambdaResponse === undefined) { | ||
return handleErr( | ||
"lambda response was undefined. check your function code again.", | ||
response | ||
); | ||
} | ||
if (!Number(lambdaResponse.statusCode)) { | ||
console.log( | ||
`${NETLIFYDEVERR} Your function response must have a numerical statusCode. You gave: $`, | ||
lambdaResponse.statusCode | ||
); | ||
return handleErr("Incorrect function response statusCode", response); | ||
} | ||
if (typeof lambdaResponse.body !== "string") { | ||
console.log( | ||
`${NETLIFYDEVERR} Your function response must have a string body. You gave:`, | ||
lambdaResponse.body | ||
); | ||
return handleErr("Incorrect function response body", response); | ||
} | ||
|
||
response.statusCode = lambdaResponse.statusCode; | ||
// eslint-disable-line guard-for-in | ||
for (const key in lambdaResponse.headers) { | ||
response.setHeader(key, lambdaResponse.headers[key]); | ||
} | ||
response.write( | ||
lambdaResponse.isBase64Encoded | ||
? Buffer.from(lambdaResponse.body, "base64") | ||
: lambdaResponse.body | ||
); | ||
response.end(); | ||
}; | ||
} | ||
}; | ||
} | ||
|
||
function promiseCallback(promise, callback) { | ||
if (!promise) return; // means no handler was written | ||
if (typeof promise.then !== "function") return; | ||
if (typeof callback !== "function") return; | ||
|
||
promise.then( | ||
function(data) { | ||
console.log("hellooo"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👋 |
||
callback(null, data); | ||
}, | ||
function(err) { | ||
callback(err, null); | ||
} | ||
); | ||
} | ||
|
||
async function serveFunctions(settings) { | ||
const app = express(); | ||
const dir = settings.functionsDir; | ||
const port = await getPort({ | ||
port: assignLoudly(settings.port, defaultPort) | ||
}); | ||
|
||
app.use(bodyParser.text({ limit: "6mb", type: ["text/*", "application/json", "multipart/form-data"] })); | ||
app.use( | ||
bodyParser.text({ | ||
limit: "6mb", | ||
type: ["text/*", "application/json", "multipart/form-data"] | ||
}) | ||
); | ||
app.use(bodyParser.raw({ limit: "6mb", type: "*/*" })); | ||
app.use( | ||
expressLogging(console, { | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
😍