-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
source.ts
104 lines (93 loc) · 2.7 KB
/
source.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import * as iam from '@aws-cdk/aws-iam';
import * as s3 from '@aws-cdk/aws-s3';
import * as s3_assets from '@aws-cdk/aws-s3-assets';
// keep this import separate from other imports to reduce chance for merge conflicts with v2-main
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct } from '@aws-cdk/core';
export interface SourceConfig {
/**
* The source bucket to deploy from.
*/
readonly bucket: s3.IBucket;
/**
* An S3 object key in the source bucket that points to a zip file.
*/
readonly zipObjectKey: string;
}
/**
* Bind context for ISources
*/
export interface DeploymentSourceContext {
/**
* The role for the handler
*/
readonly handlerRole: iam.IRole;
}
/**
* Represents a source for bucket deployments.
*/
export interface ISource {
/**
* Binds the source to a bucket deployment.
* @param scope The construct tree context.
*/
bind(scope: Construct, context?: DeploymentSourceContext): SourceConfig;
}
/**
* Specifies bucket deployment source.
*
* Usage:
*
* Source.bucket(bucket, key)
* Source.asset('/local/path/to/directory')
* Source.asset('/local/path/to/a/file.zip')
*
*/
export class Source {
/**
* Uses a .zip file stored in an S3 bucket as the source for the destination bucket contents.
* @param bucket The S3 Bucket
* @param zipObjectKey The S3 object key of the zip file with contents
*/
public static bucket(bucket: s3.IBucket, zipObjectKey: string): ISource {
return {
bind: (_: Construct, context?: DeploymentSourceContext) => {
if (!context) {
throw new Error('To use a Source.bucket(), context must be provided');
}
bucket.grantRead(context.handlerRole);
return { bucket, zipObjectKey };
},
};
}
/**
* Uses a local asset as the deployment source.
* @param path The path to a local .zip file or a directory
*/
public static asset(path: string, options?: s3_assets.AssetOptions): ISource {
return {
bind(scope: Construct, context?: DeploymentSourceContext): SourceConfig {
if (!context) {
throw new Error('To use a Source.asset(), context must be provided');
}
let id = 1;
while (scope.node.tryFindChild(`Asset${id}`)) {
id++;
}
const asset = new s3_assets.Asset(scope, `Asset${id}`, {
path,
...options,
});
if (!asset.isZipArchive) {
throw new Error('Asset path must be either a .zip file or a directory');
}
asset.grantRead(context.handlerRole);
return {
bucket: asset.bucket,
zipObjectKey: asset.s3ObjectKey,
};
},
};
}
private constructor() { }
}