Skip to content

Commit

Permalink
fix(cdk): pack lambdas with folder structure
Browse files Browse the repository at this point in the history
  • Loading branch information
coderbyheart committed Oct 25, 2023
1 parent 63bb91e commit de38404
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
6 changes: 3 additions & 3 deletions cdk/backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const packagesInLayer: string[] = [
]
const pack = async (
id: string,
handler = `${id}.handler`,
handlerFunction = 'handler',
): Promise<PackedLambda> => {
try {
await mkdir(path.join(process.cwd(), 'dist', 'lambdas'), {
Expand All @@ -24,13 +24,13 @@ const pack = async (
// Directory exists
}
const zipFile = path.join(process.cwd(), 'dist', 'lambdas', `${id}.zip`)
await packLambda({
const { handler } = await packLambda({
sourceFile: path.join(process.cwd(), 'lambda', `${id}.ts`),
zipFile,
})
return {
lambdaZipFile: zipFile,
handler,
handler: handler.replace('.js', `.${handlerFunction}`),
}
}

Expand Down
31 changes: 20 additions & 11 deletions cdk/packLambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@ import * as yazl from 'yazl'
import { commonParent } from './commonParent.js'
import { findDependencies } from './findDependencies.js'

const removeCommonAncestor =
(parentDir: string) =>
(file: string): string => {
const p = parse(file)
const jsFileName = [
p.dir.replace(parentDir.slice(0, parentDir.length - 1), ''),
`${p.name}.js`,
]
.join('/')
// Replace leading slash
.replace(/^\//, '')

return jsFileName
}

/**
* In the bundle we only include code that's not in the layer.
*/
Expand All @@ -18,12 +33,12 @@ export const packLambda = async ({
zipFile: string
debug?: (label: string, info: string) => void
progress?: (label: string, info: string) => void
}): Promise<void> => {
}): Promise<{ handler: string }> => {
const lambdaFiles = [sourceFile, ...findDependencies(sourceFile)]

const zipfile = new yazl.ZipFile()

const parentDir = commonParent(lambdaFiles)
const stripCommon = removeCommonAncestor(commonParent(lambdaFiles))

for (const file of lambdaFiles) {
const compiled = (
Expand All @@ -34,15 +49,7 @@ export const packLambda = async ({
})
).code
debug?.(`compiled`, compiled)
const p = parse(file)
const jsFileName = [
p.dir.replace(parentDir.slice(0, parentDir.length - 1), ''),
`${p.name}.js`,
]
.join('/')
// Replace leading slash
.replace(/^\//, '')

const jsFileName = stripCommon(file)
zipfile.addBuffer(Buffer.from(compiled, 'utf-8'), jsFileName)
progress?.(`added`, jsFileName)
}
Expand All @@ -66,4 +73,6 @@ export const packLambda = async ({
zipfile.end()
})
progress?.(`written`, zipFile)

return { handler: stripCommon(sourceFile) }
}

0 comments on commit de38404

Please sign in to comment.