Skip to content

Commit

Permalink
fix: use cdk annotations for logs and errors
Browse files Browse the repository at this point in the history
  • Loading branch information
adriencaccia committed Jan 30, 2023
1 parent a75e347 commit f471cce
Showing 1 changed file with 17 additions and 18 deletions.
35 changes: 17 additions & 18 deletions src/NodeJsFunctionBundleAnalyzerAspect.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { IAspect } from 'aws-cdk-lib';
import { Annotations, IAspect } from 'aws-cdk-lib';
import { CfnFunction } from 'aws-cdk-lib/aws-lambda';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { IConstruct } from 'constructs';
import { Metadata, TemplateType, visualizer } from 'esbuild-visualizer';
import { promises as fs } from 'fs';
import { existsSync, promises as fs } from 'fs';
import open from 'open';
import { tmpdir } from 'os';
import { dirname, join } from 'path';
Expand Down Expand Up @@ -43,36 +43,35 @@ class NodeJsFunctionBundleAnalyzerAspect implements IAspect {
}
const template = node.node.tryGetContext('template') as TemplateType | undefined;

if (template !== undefined && !['sunburst', 'treemap', 'network'].includes(template)) {
throw new Error(
`🤯 Analyze failed: template ${template} is not supported. Should be one of 'sunburst', 'treemap', 'network'`,
);
}

if (isNodejsFunction(node, this.customFunctionConstructName)) {
if (!node.toString().includes(functionToAnalyze)) {
return;
}

console.log(`\n⏳ Analyzing function ${functionToAnalyze}`);
if (template !== undefined && !['sunburst', 'treemap', 'network'].includes(template)) {
Annotations.of(node).addError(
`🤯 Analyze failed: template ${template} is not supported. Should be one of 'sunburst', 'treemap', 'network'`,
);

return;
}

Annotations.of(node).addInfo('⏳ Analyzing function');

const assetPath = (node.node.defaultChild as CfnFunction).cfnOptions.metadata?.[
'aws:asset:path'
] as string;
const metafilePath = join('cdk.out', assetPath, 'index.meta.json');

let textContent: string;
try {
textContent = await fs.readFile(metafilePath, {
encoding: 'utf-8',
});
} catch (e) {
console.error(
`\n🤯 Analyze failed: metafile ${metafilePath} not found. Did you set metafile: true in the bundling options of the ${functionToAnalyze} NodejsFunction construct?\n`,
const metafileExists = existsSync(metafilePath);
if (!metafileExists) {
Annotations.of(node).addError(
`🤯 Analyze failed: metafile ${metafilePath} not found. Make sure metafile: true is specified in the bundling options?`,
);

throw new Error('Analyze failed');
return;
}
const textContent = await fs.readFile(metafilePath, { encoding: 'utf-8' });

const jsonContent = JSON.parse(textContent) as Metadata;

Expand Down

0 comments on commit f471cce

Please sign in to comment.