Skip to content

Commit

Permalink
fix: minimize execution-time require()s
Browse files Browse the repository at this point in the history
  • Loading branch information
mvayngrib committed Nov 30, 2017
1 parent eff9686 commit 5346bf2
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 15 deletions.
17 changes: 10 additions & 7 deletions lib/lambda-utils.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion lib/lambda/mqtt/onmessage.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 11 additions & 7 deletions src/lambda-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
unitToMillis
} from './constants'

import serverlessYml = require('./cli/serverless-yml')
import PRICING = require('./lambda-pricing')

const defaultConcurrency = 1
Expand Down Expand Up @@ -277,18 +278,21 @@ export default class Utils {
})
}

private requireLambdaByName = (shortName:string) => {
const { functions } = serverlessYml
const handlerExportPath = functions[shortName].handler
const lastDotIdx = handlerExportPath.lastIndexOf('.')
const handlerPath = path.join('..', handlerExportPath.slice(0, lastDotIdx))
const handleExportName = handlerExportPath.slice(lastDotIdx + 1)
return require(handlerPath)[handleExportName]
}

private invokeLocal = async (params:AWS.Lambda.InvocationRequest)
:Promise<AWS.Lambda.InvocationResponse> => {
const { FunctionName, InvocationType, Payload } = params
this.logger.debug(`invoking ${params.FunctionName} inside ${this.env.FUNCTION_NAME}`)
const shortName = this.getShortName(FunctionName)
const yml = require('./cli/serverless-yml')
const { functions } = yml
const handlerExportPath = functions[shortName].handler
const lastDotIdx = handlerExportPath.lastIndexOf('.')
const handlerPath = path.join('..', handlerExportPath.slice(0, lastDotIdx))
const handleExportName = handlerExportPath.slice(lastDotIdx + 1)
const handler = require(handlerPath)[handleExportName]
const handler = this.requireLambdaByName(shortName)
const event = typeof Payload === 'string' ? JSON.parse(Payload) : {}
// not ideal as the called function may have different environment vars
const context = createLambdaContext(FunctionName)
Expand Down
5 changes: 5 additions & 0 deletions src/lambda/mqtt/onmessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const {
wrap,
user,
env,
lambdaUtils,
stringUtils,
utils,
constants
Expand All @@ -14,6 +15,10 @@ const { prettify } = stringUtils
const { SEQ } = constants
const { timestamp } = utils

if (env.INVOKE_BOT_LAMBDAS_DIRECTLY) {
lambdaUtils.requireLambdaByName(env.BOT_ONMESSAGE)
}

exports.handler = wrap(function* (event, context) {
// the user sent us a message
debug('[START]', timestamp())
Expand Down

0 comments on commit 5346bf2

Please sign in to comment.