-
Notifications
You must be signed in to change notification settings - Fork 820
/
file-asset.ts
57 lines (49 loc) · 1.84 KB
/
file-asset.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import * as cdk from '@aws-cdk/core';
import * as crypto from 'crypto';
import { TransformerStackSythesizer } from './stack-synthesizer';
import { Construct, FileAssetPackaging, Stack } from '@aws-cdk/core';
export interface TemplateProps {
readonly fileContent: string;
readonly fileName: string;
}
export class FileAsset extends cdk.Construct implements cdk.IAsset {
public readonly assetHash: string;
public readonly httpUrl: string;
public readonly s3BucketName: string;
public readonly s3ObjectKey: string;
public readonly s3Url: string;
constructor(scope: cdk.Construct, id: string, props: TemplateProps) {
super(scope, id);
const rootStack = findRootStack(scope);
const sythesizer = rootStack.synthesizer;
if (sythesizer instanceof TransformerStackSythesizer) {
sythesizer.setMappingTemplates(props.fileName, props.fileContent);
this.assetHash = crypto
.createHash('sha256')
.update(props.fileContent)
.digest('hex');
const asset = sythesizer.addFileAsset({
fileName: props.fileName,
packaging: FileAssetPackaging.FILE,
sourceHash: this.assetHash,
});
this.httpUrl = asset.httpUrl;
this.s3BucketName = asset.bucketName;
this.s3ObjectKey = asset.objectKey;
this.s3Url = asset.s3ObjectUrl
} else {
// TODO: handle a generic synthesizer by creating a asset in output path
throw new Error('Template asset can be used only with TransformerStackSynthesizer');
}
}
}
function findRootStack(scope: Construct): Stack {
if (!scope) {
throw new Error('Nested stacks cannot be defined as a root construct');
}
const rootStack = scope.node.scopes.find(p => Stack.isStack(p));
if (!rootStack) {
throw new Error('Nested stacks must be defined within scope of another non-nested stack');
}
return rootStack as Stack;
}