1414
1515// eslint-disable-next-line node/no-deprecated-api
1616import * as domain from 'domain' ;
17+
18+ import * as Debug from 'debug' ;
19+ import { get , isEmpty } from 'lodash' ;
20+
1721import { Request , Response , RequestHandler } from 'express' ;
1822import { sendCrashResponse } from './logger' ;
1923import { sendResponse } from './invoker' ;
@@ -27,9 +31,14 @@ import {
2731 CloudEventFunctionWithCallback ,
2832 HandlerFunction ,
2933} from './functions' ;
30- import { CloudEvent } from './functions' ;
34+ import { CloudEvent , OpenFunction } from './functions' ;
3135import { SignatureType } from './types' ;
3236
37+ import { OpenFunctionContext } from './openfunction/function_context' ;
38+ import { OpenFunctionRuntime } from './openfunction/function_runtime' ;
39+
40+ const debug = Debug ( 'common:wrapper' ) ;
41+
3342/**
3443 * The handler function used to signal completion of event functions.
3544 */
@@ -122,6 +131,37 @@ const wrapHttpFunction = (execute: HttpFunction): RequestHandler => {
122131 } ;
123132} ;
124133
134+ const wrapHttpAsyncFunction = (
135+ userFunction : OpenFunction ,
136+ context : OpenFunctionContext
137+ ) : RequestHandler => {
138+ const ctx = OpenFunctionRuntime . ProxyContext ( context ) ;
139+ const httpHandler = ( req : Request , res : Response ) => {
140+ const callback = getOnDoneCallback ( res ) ;
141+
142+ Promise . resolve ( )
143+ . then ( ( ) => userFunction ( ctx , req . body ) )
144+ . then ( result => {
145+ debug ( 'ℹ️ User function returned: %j' , result ) ;
146+
147+ const data = get ( result , 'body' ) ;
148+ const code = get ( result , 'code' , 200 ) ;
149+ const headers = get ( result , 'headers' ) ;
150+
151+ ! isEmpty ( headers ) && res . set ( headers ) ;
152+
153+ if ( data !== undefined ) {
154+ res . status ( code ) . send ( data ) ;
155+ } else {
156+ res . status ( code ) . end ( ) ;
157+ }
158+ } )
159+ . catch ( err => callback ( err , undefined ) ) ;
160+ } ;
161+
162+ return wrapHttpFunction ( httpHandler ) ;
163+ } ;
164+
125165/**
126166 * Wraps an async CloudEvent function in an express RequestHandler.
127167 * @param userFunction User's function.
@@ -202,10 +242,16 @@ const wrapEventFunctionWithCallback = (
202242 */
203243export const wrapUserFunction = < T = unknown > (
204244 userFunction : HandlerFunction < T > ,
205- signatureType : SignatureType
245+ signatureType : SignatureType ,
246+ context ?: object
206247) : RequestHandler => {
207248 switch ( signatureType ) {
208249 case 'http' :
250+ if ( ! isEmpty ( ( context as OpenFunctionContext ) ?. outputs ) )
251+ return wrapHttpAsyncFunction (
252+ userFunction as OpenFunction ,
253+ context as OpenFunctionContext
254+ ) ;
209255 return wrapHttpFunction ( userFunction as HttpFunction ) ;
210256 case 'event' :
211257 // Callback style if user function has more than 2 arguments.
0 commit comments