1- import { Callback } from 'aws-lambda' ;
1+ import { Callback , Context } from 'aws-lambda' ;
22import Router from './Router' ;
33import { RequestEvent , HandlerContext } from './request-response-types' ;
4- import { StringUnknownMap } from './utils/common-types' ;
4+ import { StringUnknownMap , Writable } from './utils/common-types' ;
55import { Request , Response } from '.' ;
6+ import _ from 'underscore' ;
67
78export default class Application extends Router {
89
@@ -85,8 +86,8 @@ export default class Application extends Router {
8586 * @param context The context provided to the Lambda handler
8687 * @param cb The callback provided to the Lambda handler
8788 */
88- public run ( evt : RequestEvent , context : HandlerContext , cb : Callback ) : void {
89- const req = new Request ( this , evt , context ) ,
89+ public run ( evt : RequestEvent , context : Context , cb : Callback ) : void {
90+ const req = new Request ( this , evt , this . _createHandlerContext ( context ) ) ,
9091 resp = new Response ( this , req , cb ) ;
9192
9293 this . handle ( undefined , req , resp , ( err : unknown ) : void => {
@@ -99,4 +100,29 @@ export default class Application extends Router {
99100 } ) ;
100101 }
101102
103+ private _createHandlerContext ( context : Context ) : HandlerContext {
104+ // keys should exist on both `HandlerContext` and `Context`
105+ const keys : ( keyof HandlerContext & keyof Context ) [ ] = [
106+ 'functionName' , 'functionVersion' , 'invokedFunctionArn' , 'memoryLimitInMB' ,
107+ 'awsRequestId' , 'logGroupName' , 'logStreamName' , 'identity' , 'clientContext' ,
108+ 'getRemainingTimeInMillis' ,
109+ ] ;
110+
111+ let handlerContext : Writable < HandlerContext > ;
112+
113+ handlerContext = _ . reduce ( keys , ( memo , key ) => {
114+ let contextValue = context [ key ] ;
115+
116+ if ( typeof contextValue === 'object' && contextValue ) {
117+ // Freeze sub-objects
118+ memo [ key ] = Object . freeze ( _ . extend ( { } , contextValue ) ) ;
119+ } else if ( typeof contextValue !== 'undefined' ) {
120+ memo [ key ] = contextValue ;
121+ }
122+ return memo ;
123+ } , { } as Writable < HandlerContext > ) ;
124+
125+ return Object . freeze ( handlerContext ) ;
126+ }
127+
102128}
0 commit comments