@@ -21,13 +21,22 @@ import {getUserFunction} from './loader';
21
21
import { ErrorHandler } from './invoker' ;
22
22
import { getServer } from './server' ;
23
23
import { parseOptions , helpText , OptionsError } from './options' ;
24
+ import {
25
+ HttpFunction ,
26
+ EventFunction ,
27
+ CloudEventFunction ,
28
+ HandlerFunction ,
29
+ } from './functions' ;
24
30
import { loggingHandlerAddExecutionContext } from './logger' ;
25
31
26
32
/**
27
33
* Main entrypoint for the functions framework that loads the user's function
28
34
* and starts the HTTP server.
35
+ * @param code - A function to be executed.
29
36
*/
30
- export const main = async ( ) => {
37
+ export const main = async (
38
+ code ?: HttpFunction | EventFunction | CloudEventFunction ,
39
+ ) => {
31
40
try {
32
41
const options = parseOptions ( ) ;
33
42
@@ -40,11 +49,21 @@ export const main = async () => {
40
49
loggingHandlerAddExecutionContext ( ) ;
41
50
}
42
51
43
- const loadedFunction = await getUserFunction (
44
- options . sourceLocation ,
45
- options . target ,
46
- options . signatureType ,
47
- ) ;
52
+ let loadedFunction ;
53
+ // If a function is provided directly, use it.
54
+ if ( code ) {
55
+ loadedFunction = {
56
+ userFunction : code ,
57
+ signatureType : options . signatureType || 'http' ,
58
+ } ;
59
+ } else {
60
+ // Otherwise, load the function from file.
61
+ loadedFunction = await getUserFunction (
62
+ options . sourceLocation ,
63
+ options . target ,
64
+ options . signatureType ,
65
+ ) ;
66
+ }
48
67
if ( ! loadedFunction ) {
49
68
console . error ( 'Could not load the function, shutting down.' ) ;
50
69
// eslint-disable-next-line no-process-exit
@@ -55,7 +74,7 @@ export const main = async () => {
55
74
// It is possible to overwrite the configured signature type in code so we
56
75
// reset it here based on what we loaded.
57
76
options . signatureType = signatureType ;
58
- const server = getServer ( userFunction ! , options ) ;
77
+ const server = getServer ( userFunction as HandlerFunction , options ) ;
59
78
const errorHandler = new ErrorHandler ( server ) ;
60
79
server
61
80
. listen ( options . port , ( ) => {
@@ -79,4 +98,7 @@ export const main = async () => {
79
98
} ;
80
99
81
100
// Call the main method to load the user code and start the http server.
82
- void main ( ) ;
101
+ // Only call main if the module is not being required.
102
+ if ( require . main === module ) {
103
+ void main ( ) ;
104
+ }
0 commit comments