-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
function.ts
84 lines (74 loc) · 2.43 KB
/
function.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
import * as fs from 'fs';
import * as path from 'path';
import { Function, FunctionOptions, Runtime, RuntimeFamily } from 'aws-cdk-lib/aws-lambda';
import { Stack } from 'aws-cdk-lib/core';
import { Construct } from 'constructs';
import { Bundling } from './bundling';
import { BundlingOptions } from './types';
/**
* Properties for a PythonFunction
*/
export interface PythonFunctionProps extends FunctionOptions {
/**
* Path to the source of the function or the location for dependencies.
*/
readonly entry: string;
/**
* The runtime environment. Only runtimes of the Python family are
* supported.
*/
readonly runtime: Runtime;
/**
* The path (relative to entry) to the index file containing the exported handler.
*
* @default index.py
*/
readonly index?: string;
/**
* The name of the exported handler in the index file.
*
* @default handler
*/
readonly handler?: string;
/**
* Bundling options to use for this function. Use this to specify custom bundling options like
* the bundling Docker image, asset hash type, custom hash, architecture, etc.
*
* @default - Use the default bundling Docker image, with x86_64 architecture.
*/
readonly bundling?: BundlingOptions;
}
/**
* A Python Lambda function
*/
export class PythonFunction extends Function {
constructor(scope: Construct, id: string, props: PythonFunctionProps) {
const { index = 'index.py', handler = 'handler', runtime } = props;
if (props.index && !/\.py$/.test(props.index)) {
throw new Error('Only Python (.py) index files are supported.');
}
// Entry
const entry = path.resolve(props.entry);
const resolvedIndex = path.resolve(entry, index);
if (!fs.existsSync(resolvedIndex)) {
throw new Error(`Cannot find index file at ${resolvedIndex}`);
}
const resolvedHandler =`${index.slice(0, -3)}.${handler}`.replace(/\//g, '.');
if (props.runtime && props.runtime.family !== RuntimeFamily.PYTHON) {
throw new Error('Only `PYTHON` runtimes are supported.');
}
super(scope, id, {
...props,
runtime,
code: Bundling.bundle({
entry,
runtime,
skip: !Stack.of(scope).bundlingRequired,
// define architecture based on the target architecture of the function, possibly overriden in bundling options
architecture: props.architecture,
...props.bundling,
}),
handler: resolvedHandler,
});
}
}