diff --git a/.gitignore b/.gitignore index 78e819ce..ca9c29d0 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,6 @@ doc/api/ # Further artifacts *.exe *.zip -bootstrap \ No newline at end of file +bootstrap + +.idea \ No newline at end of file diff --git a/.analysis_option.yaml b/analysis_options.yaml similarity index 100% rename from .analysis_option.yaml rename to analysis_options.yaml diff --git a/example/lib/main.dart b/example/lib/main.dart index bb26dafb..02d0b25c 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,17 +1,17 @@ import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; +import 'package:aws_lambda_dart_runtime/runtime/context.dart'; void main() async { /// This demo's handling an API Gateway request. - final Handler helloApiGateway = (context, event) async { - final response = {"message": "hello ${context.requestId}"}; + final helloApiGateway = (Context context, AwsApiGatewayEvent event) async { + final response = {'message': 'hello ${context.requestId}'}; - /// it returns an encoded response to the gateway - return InvocationResult( - context.requestId, AwsApiGatewayResponse.fromJson(response)); + /// it returns an response to the gateway + return AwsApiGatewayResponse.fromJson(response); }; /// The Runtime is a singleton. You can define the handlers as you wish. Runtime() - ..registerHandler("hello.apigateway", helloApiGateway) + ..registerHandler('hello.apigateway', helloApiGateway) ..invoke(); } diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 1baa7e49..b19f9a3d 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -1,11 +1,11 @@ name: example environment: - sdk: ">=2.6.0 <3.0.0" + sdk: ">=2.12.0 <3.0.0" dependencies: aws_lambda_dart_runtime: - git: https://github.com/awslabs/aws-lambda-dart-runtime.git + path: .. dev_dependencies: build_runner: diff --git a/lib/client/client.dart b/lib/client/client.dart index b8f7b509..f8ac809f 100644 --- a/lib/client/client.dart +++ b/lib/client/client.dart @@ -2,6 +2,8 @@ import 'dart:io'; import 'dart:async'; import 'dart:convert'; +import 'package:http/http.dart' as http; + /// Next invocation data wraps the data from the /// invocation endpoint of the Lambda Runtime Interface. class NextInvocation { @@ -20,43 +22,41 @@ class NextInvocation { final String requestId; /// Deadline milliseconds is the setting for ultimate cancelation of the invocation. - final String deadlineMs; + final String? deadlineMs; /// Invoked function ARN is the identifier of the function. - final String invokedFunctionArn; + final String? invokedFunctionArn; /// Tracing id is the identifier for tracing like X-Ray. - final String traceId; + final String? traceId; /// Client context is the context that is provided to the function. - final String clientContext; + final String? clientContext; /// Cognito identity is the identity that maybe is used for authorizing the request. - final String cognitoIdentity; + final String? cognitoIdentity; /// Digesting a [HttpClientResponse] into a [NextInvocation]. - static Future fromResponse( - HttpClientResponse response) async { - return NextInvocation( - response: json - .decode((await response.transform(Utf8Decoder()).toList()).first), - requestId: response.headers.value(runtimeRequestId), - deadlineMs: response.headers.value(runtimeDeadlineMs), - invokedFunctionArn: response.headers.value(runtimeInvokedFunctionArn), - traceId: response.headers.value(runtimeTraceId), - clientContext: response.headers.value(runtimeClientContext), - cognitoIdentity: response.headers.value(runtimeCognitoIdentity)); - } - - const NextInvocation( - {this.requestId, - this.deadlineMs, - this.traceId, - this.clientContext, - this.cognitoIdentity, - this.invokedFunctionArn, - this.response}) - : assert(requestId != null); + static Future fromResponse(http.Response response) async => + NextInvocation( + response: (json.decode(utf8.decode(response.bodyBytes)) as Map) + .cast(), + requestId: response.headers[runtimeRequestId]!, + deadlineMs: response.headers[runtimeDeadlineMs], + invokedFunctionArn: response.headers[runtimeInvokedFunctionArn], + traceId: response.headers[runtimeTraceId], + clientContext: response.headers[runtimeClientContext], + cognitoIdentity: response.headers[runtimeCognitoIdentity]); + + const NextInvocation({ + required this.requestId, + this.deadlineMs, + this.traceId, + this.clientContext, + this.cognitoIdentity, + this.invokedFunctionArn, + required this.response, + }); } /// Invocation result is the result that the invoked handler @@ -71,9 +71,7 @@ class InvocationResult { /// any json-encodable data type. final dynamic body; - const InvocationResult(this.requestId, this.body) - : assert(requestId != null), - assert(body != null); + const InvocationResult(this.requestId, this.body) : assert(body != null); } /// Invocation error occurs when there has been an @@ -92,8 +90,7 @@ class InvocationError { /// representation for the Runtime Interface. Map toJson() => { 'errorMessage': error.toString(), - 'errorType': "InvocationError", - 'stackTrace': this.stackTrace.toString() + 'errorType': 'InvocationError', }; const InvocationError(this.error, this.stackTrace); @@ -103,7 +100,7 @@ class InvocationError { /// It is implemented as a singleton whereby [Client.instance] /// always returns the already instantiated client. class Client { - HttpClient _client; + late http.Client _client; static final Client _singleton = Client._internal(); @@ -112,53 +109,45 @@ class Client { } Client._internal() { - _client = HttpClient(); + _client = http.Client(); } static const runtimeApiVersion = '2018-06-01'; - static final runtimeApi = Platform.environment["AWS_LAMBDA_RUNTIME_API"]; - /// Get the next inovation from the AWS Lambda Runtime Interface (see https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html). + static String? get runtimeApi => + Platform.environment['AWS_LAMBDA_RUNTIME_API']; + + static String? get handlerName => Platform.environment['_HANDLER']; + + /// Get the next invocation from the AWS Lambda Runtime Interface (see https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html). Future getNextInvocation() async { - final request = await _client.getUrl(Uri.parse( - 'http://${runtimeApi}/${runtimeApiVersion}/runtime/invocation/next')); - final response = await request.close(); + final response = await _client.get(Uri.parse( + 'http://$runtimeApi/$runtimeApiVersion/runtime/invocation/next')); return NextInvocation.fromResponse(response); } /// Post the invocation response to the AWS Lambda Runtime Interface. - Future postInvocationResponse( - InvocationResult result) async { - final request = await _client.postUrl( + Future postInvocationResponse( + String? requestId, dynamic payload) async { + return await _client.post( Uri.parse( - 'http://${runtimeApi}/${runtimeApiVersion}/runtime/invocation/${result.requestId}/response', + 'http://$runtimeApi/$runtimeApiVersion/runtime/invocation/$requestId/response', ), + body: jsonEncode(payload), ); - request.add( - utf8.encode( - json.encode(result.body), - ), - ); - - return await request.close(); } /// Post an invocation error to the AWS Lambda Runtime Interface. /// It takes in an [InvocationError] and the [requestId]. The [requestId] /// is used to map the error to the execution. - Future postInvocationError( + Future postInvocationError( String requestId, InvocationError err) async { - final request = await _client.postUrl( + return await _client.post( Uri.parse( - 'http://${runtimeApi}/${runtimeApiVersion}/runtime/invocation/$requestId/error', + 'http://$runtimeApi/$runtimeApiVersion/runtime/invocation/$requestId/error', ), + body: jsonEncode(err), + headers: {'Content-type': 'application/json'}, ); - request.add( - utf8.encode( - json.encode(err) - ) - ); - - return await request.close(); } } diff --git a/lib/events/alb_event.dart b/lib/events/alb_event.dart index 05a4f963..b0d0cd0d 100644 --- a/lib/events/alb_event.dart +++ b/lib/events/alb_event.dart @@ -1,5 +1,6 @@ import 'dart:io'; +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'alb_event.g.dart'; @@ -7,50 +8,51 @@ part 'alb_event.g.dart'; /// Event send by an Application Load Balancer to the /// invocation to the Lambda. @JsonSerializable() -class AwsALBEvent { +class AwsALBEvent extends Event { /// Request context in which this request is executed. /// For the ELB this is the ARN of the target group. @JsonKey() - final AwsALBEventContext context; + final AwsALBEventContext? context; /// HTTP method that is used to trigger the invocation of the Lambda. @JsonKey() - final String httpMethod; + final String? httpMethod; /// The URI that is accessed to trigger the invocation of the Lambda. @JsonKey() - final String path; + final String? path; /// HTTP headers that are send with the request to the load balancer. @JsonKey() - final Map headers; + final Map? headers; /// The query parameters for the request to the load balancer. @JsonKey() - final Map queryStringParameters; + final Map? queryStringParameters; /// Body of the request. This can be data that is send with the POST /// to the request. @JsonKey() - final String body; + final String? body; /// Singals that the request is Base64 encoded. @JsonKey() - final bool isBase64Encoded; + final bool? isBase64Encoded; factory AwsALBEvent.fromJson(Map json) => _$AwsALBEventFromJson(json); Map toJson() => _$AwsALBEventToJson(this); - const AwsALBEvent( - {this.context, - this.httpMethod, - this.path, - this.headers, - this.queryStringParameters, - this.body, - this.isBase64Encoded}); + const AwsALBEvent({ + this.context, + this.httpMethod, + this.path, + this.headers, + this.queryStringParameters, + this.body, + this.isBase64Encoded, + }); } /// Response for a request from an Application Load Balancer. @@ -58,20 +60,20 @@ class AwsALBEvent { /// They should reflect the informationen needed here. class AwsALBResponse { /// The body of the HTTP Response send from the API Gateway to the client. - String body; + String? body; /// Indicates if the [body] is Base64 encoded or not. By default is `false`. - bool isBase64Encoded; + bool? isBase64Encoded; /// HTTP status code of the response of the API Gateway to the client. /// The default status code is `200 OK`. - int statusCode; + int? statusCode; /// Description of the send HTTP status code. - String statusDescription; + String? statusDescription; /// The HTTP headers that should be send with the response to the client. - Map headers; + Map? headers; /// Returns the JSON representation of the response. This is called by /// the JSON encoder to produce the response. @@ -85,10 +87,10 @@ class AwsALBResponse { factory AwsALBResponse.fromString( String body, { - bool isBase64Encoded, - int statusCode, - String statusDescription, - Map headers, + bool? isBase64Encoded, + int? statusCode, + String? statusDescription, + Map? headers, }) { return AwsALBResponse( body: body, @@ -100,13 +102,18 @@ class AwsALBResponse { /// The Response that should be returned to the Application Load Balancer. /// It is constructed with some default values for the optional parameters. - AwsALBResponse( - {body, headers, isBase64Encoded, statusCode, statusDescription}) { + AwsALBResponse({ + String? body, + Map? headers, + bool? isBase64Encoded, + int? statusCode, + String? statusDescription, + }) { this.body = body ?? ''; this.isBase64Encoded = isBase64Encoded ?? false; - this.headers = headers ?? {"Content-Type": "text/html; charset=utf-8"}; + this.headers = headers ?? {'Content-Type': 'text/html; charset=utf-8'}; this.statusCode = statusCode ?? HttpStatus.ok; - this.statusDescription = statusDescription ?? "200 OK"; + this.statusDescription = statusDescription ?? '200 OK'; } } diff --git a/lib/events/alb_event.g.dart b/lib/events/alb_event.g.dart index f6c69f9f..66010b53 100644 --- a/lib/events/alb_event.g.dart +++ b/lib/events/alb_event.g.dart @@ -11,13 +11,13 @@ AwsALBEvent _$AwsALBEventFromJson(Map json) { context: json['context'] == null ? null : AwsALBEventContext.fromJson(json['context'] as Map), - httpMethod: json['httpMethod'] as String, - path: json['path'] as String, - headers: json['headers'] as Map, + httpMethod: json['httpMethod'] as String?, + path: json['path'] as String?, + headers: json['headers'] as Map?, queryStringParameters: - json['queryStringParameters'] as Map, - body: json['body'] as String, - isBase64Encoded: json['isBase64Encoded'] as bool, + json['queryStringParameters'] as Map?, + body: json['body'] as String?, + isBase64Encoded: json['isBase64Encoded'] as bool?, ); } diff --git a/lib/events/alexa_event.dart b/lib/events/alexa_event.dart index 5bf63110..c0198e63 100644 --- a/lib/events/alexa_event.dart +++ b/lib/events/alexa_event.dart @@ -1,3 +1,4 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'alexa_event.g.dart'; @@ -7,15 +8,15 @@ part 'alexa_event.g.dart'; class AwsAlexaEventHeader { /// Version of the send payload. @JsonKey() - final String payloadVersion; + final String? payloadVersion; /// Namespace of the event. @JsonKey() - final String namespace; + final String? namespace; /// Name of the event @JsonKey() - final String name; + final String? name; factory AwsAlexaEventHeader.fromJson(Map json) => _$AwsAlexaEventHeaderFromJson(json); @@ -28,14 +29,14 @@ class AwsAlexaEventHeader { /// Event send by an Application Load Balancer to the /// invocation to the Lambda. @JsonSerializable() -class AwsAlexaEvent { +class AwsAlexaEvent extends Event { /// Meta information about the event. @JsonKey() - final AwsAlexaEventHeader header; + final AwsAlexaEventHeader? header; /// Payload of the event send by Alexa. @JsonKey() - final Map payload; + final Map? payload; factory AwsAlexaEvent.fromJson(Map json) => _$AwsAlexaEventFromJson(json); diff --git a/lib/events/alexa_event.g.dart b/lib/events/alexa_event.g.dart index e94b6c6f..163961b4 100644 --- a/lib/events/alexa_event.g.dart +++ b/lib/events/alexa_event.g.dart @@ -8,9 +8,9 @@ part of 'alexa_event.dart'; AwsAlexaEventHeader _$AwsAlexaEventHeaderFromJson(Map json) { return AwsAlexaEventHeader( - namespace: json['namespace'] as String, - payloadVersion: json['payloadVersion'] as String, - name: json['name'] as String, + namespace: json['namespace'] as String?, + payloadVersion: json['payloadVersion'] as String?, + name: json['name'] as String?, ); } @@ -27,7 +27,7 @@ AwsAlexaEvent _$AwsAlexaEventFromJson(Map json) { header: json['header'] == null ? null : AwsAlexaEventHeader.fromJson(json['header'] as Map), - payload: json['payload'] as Map, + payload: json['payload'] as Map?, ); } diff --git a/lib/events/apigateway_event.dart b/lib/events/apigateway_event.dart index 83845f2b..c79baacb 100644 --- a/lib/events/apigateway_event.dart +++ b/lib/events/apigateway_event.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'dart:convert'; +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'apigateway_event.g.dart'; @@ -11,36 +12,41 @@ part 'apigateway_event.g.dart'; /// Furthermore it indicates if the [body] is Base64 encoded or not. class AwsApiGatewayResponse { /// The body of the HTTP Response send from the API Gateway to the client. - String body; + String? body; /// Indicates if the [body] is Base64 encoded or not. By default is `false`. - bool isBase64Encoded; + bool? isBase64Encoded; // HTTP Status Code of the response of the API Gateway to the client. - int statusCode; + int? statusCode; /// The HTTP headers that should be send with the response to the client. - Map headers; + Map? headers; /// Returns the JSON representation of the response. This is called by /// the JSON encoder to produce the response. Map toJson() => { - 'body': body, + if (body != null) 'body': body, 'isBase64Encoded': isBase64Encoded, 'statusCode': statusCode, - 'headers': headers + if (headers != null) 'headers': headers }; /// The factory creates a new [AwsApiGatewayResponse] from JSON. /// It optionally accepts the Base64 encoded flag and a HTTP Status Code /// for the response. - factory AwsApiGatewayResponse.fromJson(Map body, - {bool isBase64Encoded, int statusCode, Map headers}) { + factory AwsApiGatewayResponse.fromJson( + Map body, { + bool isBase64Encoded = false, + int statusCode = HttpStatus.ok, + Map? headers, + }) { return AwsApiGatewayResponse( - body: json.encode(body), - isBase64Encoded: isBase64Encoded, - headers: headers, - statusCode: statusCode); + body: json.encode(body), + isBase64Encoded: isBase64Encoded, + headers: headers, + statusCode: statusCode, + ); } /// The Response that should be returned by the API Gateway for the @@ -48,55 +54,55 @@ class AwsApiGatewayResponse { /// But also it signals if the [body] is Base64 encoded and what the HTTP Status Code /// of the response is. AwsApiGatewayResponse({ - String body, - bool isBase64Encoded, - Map headers, - int statusCode, + String? body, + bool isBase64Encoded = false, + Map? headers, + int? statusCode, }) { - this.body = body ?? ''; - this.isBase64Encoded = isBase64Encoded ?? false; - this.headers = headers ?? {"Content-Type": "application/json"}; + this.body = body; + this.isBase64Encoded = isBase64Encoded; + this.headers = headers ?? {'Content-Type': 'application/json'}; this.statusCode = statusCode ?? HttpStatus.ok; } } /// API Gateway Event ... @JsonSerializable() -class AwsApiGatewayEvent { +class AwsApiGatewayEvent extends Event { /// URL Path ... @JsonKey() - final String path; + final String? path; /// Resource ... @JsonKey() - final String resource; + final String? resource; /// HTTP Method ... @JsonKey() - final String httpMethod; + final String? httpMethod; /// Body ... @JsonKey() - final String body; + final String? body; /// Headers ... @JsonKey() - final AwsApiGatewayEventHeaders headers; + final AwsApiGatewayEventHeaders? headers; /// Path Parameters ... @JsonKey() - final Map pathParameters; + final Map? pathParameters; /// Query String Parameters ... @JsonKey() - final Map queryStringParameters; + final Map? queryStringParameters; /// Stage Variables ... @JsonKey() - final Map stageVariables; + final Map? stageVariables; /// Request Context ... - final AwsApiGatewayEventRequestContext requestContext; + final AwsApiGatewayEventRequestContext? requestContext; factory AwsApiGatewayEvent.fromJson(Map json) => _$AwsApiGatewayEventFromJson(json); @@ -118,62 +124,62 @@ class AwsApiGatewayEvent { /// API Gateway Event Headers ... @JsonSerializable() class AwsApiGatewayEventHeaders { - @JsonKey(name: "Accept") - final String accept; + @JsonKey(name: 'Accept') + final String? accept; - @JsonKey(name: "Accept-Encoding") - final String acceptEncoding; + @JsonKey(name: 'Accept-Encoding') + final String? acceptEncoding; - @JsonKey(name: "CloudFront-Forwarded-Proto") - final String cloudfrontForwardProto; + @JsonKey(name: 'CloudFront-Forwarded-Proto') + final String? cloudfrontForwardProto; - @JsonKey(name: "CloudFront-Is-Desktop-Viewer") - final String cloudfrontIsDesktopViewer; + @JsonKey(name: 'CloudFront-Is-Desktop-Viewer') + final String? cloudfrontIsDesktopViewer; - @JsonKey(name: "CloudFront-Is-Mobile-Viewer") - final String cloudfrontIsMobileViewer; + @JsonKey(name: 'CloudFront-Is-Mobile-Viewer') + final String? cloudfrontIsMobileViewer; - @JsonKey(name: "CloudFront-Is-SmartTV-Viewer") - final String cloudfrontIsSmartTvViewer; + @JsonKey(name: 'CloudFront-Is-SmartTV-Viewer') + final String? cloudfrontIsSmartTvViewer; - @JsonKey(name: "CloudFront-Is-Tablet-Viewer") - final String cloudfrontIsTabletViewer; + @JsonKey(name: 'CloudFront-Is-Tablet-Viewer') + final String? cloudfrontIsTabletViewer; - @JsonKey(name: "CloudFront-Viewer-Country") - final String cloudfrontViewerCountry; + @JsonKey(name: 'CloudFront-Viewer-Country') + final String? cloudfrontViewerCountry; - @JsonKey(name: "Host") - final String host; + @JsonKey(name: 'Host') + final String? host; - @JsonKey(name: "Upgrade-Insecure-Requests") - final String upgradeInsecureRequests; + @JsonKey(name: 'Upgrade-Insecure-Requests') + final String? upgradeInsecureRequests; - @JsonKey(name: "User-Agent") - final String userAgent; + @JsonKey(name: 'User-Agent') + final String? userAgent; - @JsonKey(name: "Via") - final String via; + @JsonKey(name: 'Via') + final String? via; - @JsonKey(name: "X-Amz-Cf-Id") - final String xAmzCfId; + @JsonKey(name: 'X-Amz-Cf-Id') + final String? xAmzCfId; - @JsonKey(name: "X-Forwarded-For") - final String xForwardedFor; + @JsonKey(name: 'X-Forwarded-For') + final String? xForwardedFor; - @JsonKey(name: "X-Forwarded-Port") - final String xForwardedPort; + @JsonKey(name: 'X-Forwarded-Port') + final String? xForwardedPort; - @JsonKey(name: "X-Forwarded-Proto") - final String xForwardedProto; + @JsonKey(name: 'X-Forwarded-Proto') + final String? xForwardedProto; - @JsonKey(name: "Cache-Control") - final String cacheControl; + @JsonKey(name: 'Cache-Control') + final String? cacheControl; - @JsonKey(name: "X-Amzn-Trace-Id") - final String xAmznTraceId; + @JsonKey(name: 'X-Amzn-Trace-Id') + final String? xAmznTraceId; @JsonKey(ignore: true) - Map raw; + late Map raw; factory AwsApiGatewayEventHeaders.fromJson(Map json) { final event = _$AwsApiGatewayEventHeadersFromJson(json); @@ -209,25 +215,25 @@ class AwsApiGatewayEventHeaders { @JsonSerializable() class AwsApiGatewayEventRequestContext { @JsonKey() - final String accountId; + final String? accountId; @JsonKey() - final String resourceId; + final String? resourceId; @JsonKey() - final String stage; + final String? stage; @JsonKey() - final String requestId; + final String? requestId; @JsonKey() - final String resourcePath; + final String? resourcePath; @JsonKey() - final String httpMethod; + final String? httpMethod; @JsonKey() - final String apiId; + final String? apiId; factory AwsApiGatewayEventRequestContext.fromJson( Map json) => @@ -250,37 +256,37 @@ class AwsApiGatewayEventRequestContext { @JsonSerializable() class AwsApiGatewayEventRequestContextIdentity { @JsonKey() - final String cognitoIdentityPoolId; + final String? cognitoIdentityPoolId; @JsonKey() - final String accountId; + final String? accountId; @JsonKey() - final String cognitoIdentityId; + final String? cognitoIdentityId; @JsonKey() - final String caller; + final String? caller; @JsonKey() - final String apiKey; + final String? apiKey; @JsonKey() - final String sourceIp; + final String? sourceIp; @JsonKey() - final String cognitoAuthenticationType; + final String? cognitoAuthenticationType; @JsonKey() - final String cognitoAuthenticationProvider; + final String? cognitoAuthenticationProvider; @JsonKey() - final String userArn; + final String? userArn; @JsonKey() - final String userAgent; + final String? userAgent; @JsonKey() - final String user; + final String? user; factory AwsApiGatewayEventRequestContextIdentity.fromJson( Map json) => diff --git a/lib/events/apigateway_event.g.dart b/lib/events/apigateway_event.g.dart index df9aea8d..e1496487 100644 --- a/lib/events/apigateway_event.g.dart +++ b/lib/events/apigateway_event.g.dart @@ -8,22 +8,22 @@ part of 'apigateway_event.dart'; AwsApiGatewayEvent _$AwsApiGatewayEventFromJson(Map json) { return AwsApiGatewayEvent( - resource: json['resource'] as String, - path: json['path'] as String, - httpMethod: json['httpMethod'] as String, - body: json['body'] as String, + resource: json['resource'] as String?, + path: json['path'] as String?, + httpMethod: json['httpMethod'] as String?, + body: json['body'] as String?, headers: json['headers'] == null ? null : AwsApiGatewayEventHeaders.fromJson( json['headers'] as Map), queryStringParameters: - json['queryStringParameters'] as Map, - stageVariables: json['stageVariables'] as Map, + json['queryStringParameters'] as Map?, + stageVariables: json['stageVariables'] as Map?, requestContext: json['requestContext'] == null ? null : AwsApiGatewayEventRequestContext.fromJson( json['requestContext'] as Map), - pathParameters: json['pathParameters'] as Map, + pathParameters: json['pathParameters'] as Map?, ); } @@ -43,24 +43,24 @@ Map _$AwsApiGatewayEventToJson(AwsApiGatewayEvent instance) => AwsApiGatewayEventHeaders _$AwsApiGatewayEventHeadersFromJson( Map json) { return AwsApiGatewayEventHeaders( - accept: json['Accept'] as String, - acceptEncoding: json['Accept-Encoding'] as String, - cloudfrontIsDesktopViewer: json['CloudFront-Is-Desktop-Viewer'] as String, - cloudfrontIsMobileViewer: json['CloudFront-Is-Mobile-Viewer'] as String, - cloudfrontIsSmartTvViewer: json['CloudFront-Is-SmartTV-Viewer'] as String, - cloudfrontForwardProto: json['CloudFront-Forwarded-Proto'] as String, - cloudfrontIsTabletViewer: json['CloudFront-Is-Tablet-Viewer'] as String, - cloudfrontViewerCountry: json['CloudFront-Viewer-Country'] as String, - upgradeInsecureRequests: json['Upgrade-Insecure-Requests'] as String, - cacheControl: json['Cache-Control'] as String, - host: json['Host'] as String, - via: json['Via'] as String, - userAgent: json['User-Agent'] as String, - xAmzCfId: json['X-Amz-Cf-Id'] as String, - xAmznTraceId: json['X-Amzn-Trace-Id'] as String, - xForwardedFor: json['X-Forwarded-For'] as String, - xForwardedPort: json['X-Forwarded-Port'] as String, - xForwardedProto: json['X-Forwarded-Proto'] as String, + accept: json['Accept'] as String?, + acceptEncoding: json['Accept-Encoding'] as String?, + cloudfrontIsDesktopViewer: json['CloudFront-Is-Desktop-Viewer'] as String?, + cloudfrontIsMobileViewer: json['CloudFront-Is-Mobile-Viewer'] as String?, + cloudfrontIsSmartTvViewer: json['CloudFront-Is-SmartTV-Viewer'] as String?, + cloudfrontForwardProto: json['CloudFront-Forwarded-Proto'] as String?, + cloudfrontIsTabletViewer: json['CloudFront-Is-Tablet-Viewer'] as String?, + cloudfrontViewerCountry: json['CloudFront-Viewer-Country'] as String?, + upgradeInsecureRequests: json['Upgrade-Insecure-Requests'] as String?, + cacheControl: json['Cache-Control'] as String?, + host: json['Host'] as String?, + via: json['Via'] as String?, + userAgent: json['User-Agent'] as String?, + xAmzCfId: json['X-Amz-Cf-Id'] as String?, + xAmznTraceId: json['X-Amzn-Trace-Id'] as String?, + xForwardedFor: json['X-Forwarded-For'] as String?, + xForwardedPort: json['X-Forwarded-Port'] as String?, + xForwardedProto: json['X-Forwarded-Proto'] as String?, ); } @@ -90,13 +90,13 @@ Map _$AwsApiGatewayEventHeadersToJson( AwsApiGatewayEventRequestContext _$AwsApiGatewayEventRequestContextFromJson( Map json) { return AwsApiGatewayEventRequestContext( - accountId: json['accountId'] as String, - resourceId: json['resourceId'] as String, - stage: json['stage'] as String, - requestId: json['requestId'] as String, - resourcePath: json['resourcePath'] as String, - httpMethod: json['httpMethod'] as String, - apiId: json['apiId'] as String, + accountId: json['accountId'] as String?, + resourceId: json['resourceId'] as String?, + stage: json['stage'] as String?, + requestId: json['requestId'] as String?, + resourcePath: json['resourcePath'] as String?, + httpMethod: json['httpMethod'] as String?, + apiId: json['apiId'] as String?, ); } @@ -116,18 +116,18 @@ AwsApiGatewayEventRequestContextIdentity _$AwsApiGatewayEventRequestContextIdentityFromJson( Map json) { return AwsApiGatewayEventRequestContextIdentity( - cognitoIdentityPoolId: json['cognitoIdentityPoolId'] as String, + cognitoIdentityPoolId: json['cognitoIdentityPoolId'] as String?, cognitoAuthenticationProvider: - json['cognitoAuthenticationProvider'] as String, - cognitoAuthenticationType: json['cognitoAuthenticationType'] as String, - caller: json['caller'] as String, - accountId: json['accountId'] as String, - cognitoIdentityId: json['cognitoIdentityId'] as String, - apiKey: json['apiKey'] as String, - sourceIp: json['sourceIp'] as String, - user: json['user'] as String, - userAgent: json['userAgent'] as String, - userArn: json['userArn'] as String, + json['cognitoAuthenticationProvider'] as String?, + cognitoAuthenticationType: json['cognitoAuthenticationType'] as String?, + caller: json['caller'] as String?, + accountId: json['accountId'] as String?, + cognitoIdentityId: json['cognitoIdentityId'] as String?, + apiKey: json['apiKey'] as String?, + sourceIp: json['sourceIp'] as String?, + user: json['user'] as String?, + userAgent: json['userAgent'] as String?, + userArn: json['userArn'] as String?, ); } diff --git a/lib/events/appsync_event.dart b/lib/events/appsync_event.dart index 3223f6be..0a6ad7a9 100644 --- a/lib/events/appsync_event.dart +++ b/lib/events/appsync_event.dart @@ -1,18 +1,19 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'appsync_event.g.dart'; /// App Sync Event ... @JsonSerializable() -class AwsAppSyncEvent { - @JsonKey(name: "version") - final String version; +class AwsAppSyncEvent extends Event { + @JsonKey(name: 'version') + final String? version; - @JsonKey(name: "operation") - final String operation; + @JsonKey(name: 'operation') + final String? operation; - @JsonKey(name: "payload") - final String payload; + @JsonKey(name: 'payload') + final String? payload; factory AwsAppSyncEvent.fromJson(Map json) => _$AwsAppSyncEventFromJson(json); diff --git a/lib/events/appsync_event.g.dart b/lib/events/appsync_event.g.dart index 6ff0c8f3..edf22c6a 100644 --- a/lib/events/appsync_event.g.dart +++ b/lib/events/appsync_event.g.dart @@ -8,9 +8,9 @@ part of 'appsync_event.dart'; AwsAppSyncEvent _$AwsAppSyncEventFromJson(Map json) { return AwsAppSyncEvent( - version: json['version'] as String, - operation: json['operation'] as String, - payload: json['payload'] as String, + version: json['version'] as String?, + operation: json['operation'] as String?, + payload: json['payload'] as String?, ); } diff --git a/lib/events/cloudwatch_event.dart b/lib/events/cloudwatch_event.dart index 28aa9013..96d588f6 100644 --- a/lib/events/cloudwatch_event.dart +++ b/lib/events/cloudwatch_event.dart @@ -1,3 +1,4 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'cloudwatch_event.g.dart'; @@ -22,38 +23,38 @@ part 'cloudwatch_event.g.dart'; /// } /// ``` @JsonSerializable() -class AwsCloudwatchEvent { +class AwsCloudwatchEvent extends Event { /// Resources ... @JsonKey() - final List resources; + final List? resources; /// Region ... @JsonKey() - final String region; + final String? region; /// Id ... @JsonKey() - final String id; + final String? id; /// Source ... @JsonKey() - final String source; + final String? source; /// Account ... @JsonKey() - final String account; + final String? account; /// Data Type ... - @JsonKey(name: "detail-type") - final String detailType; + @JsonKey(name: 'detail-type') + final String? detailType; /// Detail ... @JsonKey() - final Map detail; + final Map? detail; /// Time ... @JsonKey() - final DateTime time; + final DateTime? time; factory AwsCloudwatchEvent.fromJson(Map json) => _$AwsCloudwatchEventFromJson(json); diff --git a/lib/events/cloudwatch_event.g.dart b/lib/events/cloudwatch_event.g.dart index c14b9eac..1726f885 100644 --- a/lib/events/cloudwatch_event.g.dart +++ b/lib/events/cloudwatch_event.g.dart @@ -8,13 +8,14 @@ part of 'cloudwatch_event.dart'; AwsCloudwatchEvent _$AwsCloudwatchEventFromJson(Map json) { return AwsCloudwatchEvent( - resources: (json['resources'] as List)?.map((e) => e as String)?.toList(), - region: json['region'] as String, - id: json['id'] as String, - source: json['source'] as String, - account: json['account'] as String, - detailType: json['detail-type'] as String, - detail: json['detail'] as Map, + resources: + (json['resources'] as List?)?.map((e) => e as String).toList(), + region: json['region'] as String?, + id: json['id'] as String?, + source: json['source'] as String?, + account: json['account'] as String?, + detailType: json['detail-type'] as String?, + detail: json['detail'] as Map?, time: json['time'] == null ? null : DateTime.parse(json['time'] as String), ); } diff --git a/lib/events/cloudwatch_log_event.dart b/lib/events/cloudwatch_log_event.dart index ea7ab929..366469e9 100644 --- a/lib/events/cloudwatch_log_event.dart +++ b/lib/events/cloudwatch_log_event.dart @@ -1,3 +1,4 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'cloudwatch_log_event.g.dart'; @@ -10,10 +11,10 @@ part 'cloudwatch_log_event.g.dart'; /// Cloudwatch Log Event ... @JsonSerializable() -class AwsCloudwatchLogEvent { +class AwsCloudwatchLogEvent extends Event { /// awslogs ... @JsonKey() - final Map awslogs; + final Map? awslogs; factory AwsCloudwatchLogEvent.fromJson(Map json) => _$AwsCloudwatchLogEventFromJson(json); diff --git a/lib/events/cloudwatch_log_event.g.dart b/lib/events/cloudwatch_log_event.g.dart index 73a181d1..dd032b02 100644 --- a/lib/events/cloudwatch_log_event.g.dart +++ b/lib/events/cloudwatch_log_event.g.dart @@ -9,7 +9,7 @@ part of 'cloudwatch_log_event.dart'; AwsCloudwatchLogEvent _$AwsCloudwatchLogEventFromJson( Map json) { return AwsCloudwatchLogEvent( - awslogs: json['awslogs'] as Map, + awslogs: json['awslogs'] as Map?, ); } diff --git a/lib/events/cognito_event.dart b/lib/events/cognito_event.dart index 4c8862f3..99baf2df 100644 --- a/lib/events/cognito_event.dart +++ b/lib/events/cognito_event.dart @@ -1,32 +1,33 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'cognito_event.g.dart'; @JsonSerializable() -class AwsCognitoEvent { +class AwsCognitoEvent extends Event { @JsonKey() - final int version; + final int? version; @JsonKey() - final String triggerSource; + final String? triggerSource; @JsonKey() - final String region; + final String? region; @JsonKey() - final String userPoolId; + final String? userPoolId; @JsonKey() - final String userName; + final String? userName; @JsonKey() - final Map callerContext; + final Map? callerContext; @JsonKey() - final AwsCognitoRequest request; + final AwsCognitoRequest? request; @JsonKey() - final AwsCognitoResponse response; + final AwsCognitoResponse? response; const AwsCognitoEvent( {this.version, @@ -47,25 +48,25 @@ class AwsCognitoEvent { @JsonSerializable() class AwsCognitoRequest { @JsonKey() - final Map userAttributes; + final Map? userAttributes; @JsonKey() - final Map validationData; + final Map? validationData; @JsonKey() - final Map clientMetadata; + final Map? clientMetadata; @JsonKey() - final bool newDeviceUsed; + final bool? newDeviceUsed; @JsonKey() - final AwsGroupConfiguration groupConfiguration; + final AwsGroupConfiguration? groupConfiguration; @JsonKey() - final String password; + final String? password; @JsonKey() - final String codeParameter; + final String? codeParameter; const AwsCognitoRequest( {this.userAttributes, @@ -85,40 +86,40 @@ class AwsCognitoRequest { @JsonSerializable() class AwsCognitoResponse { @JsonKey() - final bool autoConfirmUser; + final bool? autoConfirmUser; @JsonKey() - final bool autoVerifyPhone; + final bool? autoVerifyPhone; @JsonKey() - final bool autoVerifyEmail; + final bool? autoVerifyEmail; @JsonKey() - final AwsClaimOverrideDetails claimsOverrideDetails; + final AwsClaimOverrideDetails? claimsOverrideDetails; @JsonKey() - final Map userAttributes; + final Map? userAttributes; @JsonKey() - final String finalUserStatus; + final String? finalUserStatus; @JsonKey() - final String messageAction; + final String? messageAction; @JsonKey() - final List desiredDeliveryMediums; + final List? desiredDeliveryMediums; @JsonKey() - final bool forceAliasCreation; + final bool? forceAliasCreation; @JsonKey() - final String smsMessage; + final String? smsMessage; @JsonKey() - final String emailMessage; + final String? emailMessage; @JsonKey() - final String emailSubject; + final String? emailSubject; const AwsCognitoResponse( {this.autoConfirmUser, @@ -143,16 +144,16 @@ class AwsCognitoResponse { @JsonSerializable() class AwsGroupConfiguration { @JsonKey() - final List groupsToOverride; + final List? groupsToOverride; @JsonKey() - final List iamRolesToOverride; + final List? iamRolesToOverride; @JsonKey() - final String preferredRole; + final String? preferredRole; @JsonKey() - final Map clientMetadata; + final Map? clientMetadata; const AwsGroupConfiguration( {this.groupsToOverride, @@ -169,13 +170,13 @@ class AwsGroupConfiguration { @JsonSerializable() class AwsClaimOverrideDetails { @JsonKey() - final Map claimsToAddOrOverride; + final Map? claimsToAddOrOverride; @JsonKey() - final List claimsToSuppress; + final List? claimsToSuppress; @JsonKey() - final AwsGroupConfiguration groupOverrideDetails; + final AwsGroupConfiguration? groupOverrideDetails; const AwsClaimOverrideDetails( {this.claimsToAddOrOverride, diff --git a/lib/events/cognito_event.g.dart b/lib/events/cognito_event.g.dart index 99584150..b3e1e06e 100644 --- a/lib/events/cognito_event.g.dart +++ b/lib/events/cognito_event.g.dart @@ -8,12 +8,12 @@ part of 'cognito_event.dart'; AwsCognitoEvent _$AwsCognitoEventFromJson(Map json) { return AwsCognitoEvent( - version: json['version'] as int, - triggerSource: json['triggerSource'] as String, - region: json['region'] as String, - userPoolId: json['userPoolId'] as String, - userName: json['userName'] as String, - callerContext: (json['callerContext'] as Map)?.map( + version: json['version'] as int?, + triggerSource: json['triggerSource'] as String?, + region: json['region'] as String?, + userPoolId: json['userPoolId'] as String?, + userName: json['userName'] as String?, + callerContext: (json['callerContext'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), request: json['request'] == null @@ -39,16 +39,16 @@ Map _$AwsCognitoEventToJson(AwsCognitoEvent instance) => AwsCognitoRequest _$AwsCognitoRequestFromJson(Map json) { return AwsCognitoRequest( - userAttributes: json['userAttributes'] as Map, - validationData: (json['validationData'] as Map)?.map( + userAttributes: json['userAttributes'] as Map?, + validationData: (json['validationData'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), - clientMetadata: (json['clientMetadata'] as Map)?.map( + clientMetadata: (json['clientMetadata'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), - newDeviceUsed: json['newDeviceUsed'] as bool, - codeParameter: json['codeParameter'] as String, - password: json['password'] as String, + newDeviceUsed: json['newDeviceUsed'] as bool?, + codeParameter: json['codeParameter'] as String?, + password: json['password'] as String?, groupConfiguration: json['groupConfiguration'] == null ? null : AwsGroupConfiguration.fromJson( @@ -69,25 +69,25 @@ Map _$AwsCognitoRequestToJson(AwsCognitoRequest instance) => AwsCognitoResponse _$AwsCognitoResponseFromJson(Map json) { return AwsCognitoResponse( - autoConfirmUser: json['autoConfirmUser'] as bool, - autoVerifyEmail: json['autoVerifyEmail'] as bool, - autoVerifyPhone: json['autoVerifyPhone'] as bool, + autoConfirmUser: json['autoConfirmUser'] as bool?, + autoVerifyEmail: json['autoVerifyEmail'] as bool?, + autoVerifyPhone: json['autoVerifyPhone'] as bool?, claimsOverrideDetails: json['claimsOverrideDetails'] == null ? null : AwsClaimOverrideDetails.fromJson( json['claimsOverrideDetails'] as Map), - userAttributes: (json['userAttributes'] as Map)?.map( + userAttributes: (json['userAttributes'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), - finalUserStatus: json['finalUserStatus'] as String, - desiredDeliveryMediums: (json['desiredDeliveryMediums'] as List) + finalUserStatus: json['finalUserStatus'] as String?, + desiredDeliveryMediums: (json['desiredDeliveryMediums'] as List?) ?.map((e) => e as String) - ?.toList(), - forceAliasCreation: json['forceAliasCreation'] as bool, - messageAction: json['messageAction'] as String, - smsMessage: json['smsMessage'] as String, - emailMessage: json['emailMessage'] as String, - emailSubject: json['emailSubject'] as String, + .toList(), + forceAliasCreation: json['forceAliasCreation'] as bool?, + messageAction: json['messageAction'] as String?, + smsMessage: json['smsMessage'] as String?, + emailMessage: json['emailMessage'] as String?, + emailSubject: json['emailSubject'] as String?, ); } @@ -110,12 +110,14 @@ Map _$AwsCognitoResponseToJson(AwsCognitoResponse instance) => AwsGroupConfiguration _$AwsGroupConfigurationFromJson( Map json) { return AwsGroupConfiguration( - groupsToOverride: - (json['groupsToOverride'] as List)?.map((e) => e as String)?.toList(), - iamRolesToOverride: - (json['iamRolesToOverride'] as List)?.map((e) => e as String)?.toList(), - preferredRole: json['preferredRole'] as String, - clientMetadata: (json['clientMetadata'] as Map)?.map( + groupsToOverride: (json['groupsToOverride'] as List?) + ?.map((e) => e as String) + .toList(), + iamRolesToOverride: (json['iamRolesToOverride'] as List?) + ?.map((e) => e as String) + .toList(), + preferredRole: json['preferredRole'] as String?, + clientMetadata: (json['clientMetadata'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), ); @@ -134,11 +136,12 @@ AwsClaimOverrideDetails _$AwsClaimOverrideDetailsFromJson( Map json) { return AwsClaimOverrideDetails( claimsToAddOrOverride: - (json['claimsToAddOrOverride'] as Map)?.map( + (json['claimsToAddOrOverride'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), - claimsToSuppress: - (json['claimsToSuppress'] as List)?.map((e) => e as String)?.toList(), + claimsToSuppress: (json['claimsToSuppress'] as List?) + ?.map((e) => e as String) + .toList(), groupOverrideDetails: json['groupOverrideDetails'] == null ? null : AwsGroupConfiguration.fromJson( diff --git a/lib/events/dynamodb_event.dart b/lib/events/dynamodb_event.dart index 8ca4e06c..3ccf96c7 100644 --- a/lib/events/dynamodb_event.dart +++ b/lib/events/dynamodb_event.dart @@ -1,3 +1,4 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'dynamodb_event.g.dart'; @@ -5,18 +6,18 @@ part 'dynamodb_event.g.dart'; /// Event send by a DynamoDB stream that contains /// the updated records in the DynamoDB table. @JsonSerializable() -class AwsDynamoDBUpdateRecord { +class AwsDynamoDBUpdateRecord extends Event { /// Keys ... - @JsonKey(name: "Keys") - final Map keys; + @JsonKey(name: 'Keys') + final Map? keys; /// New Image ... - @JsonKey(name: "NewImage") - final Map oldImage; + @JsonKey(name: 'NewImage') + final Map? oldImage; /// Old Image .... - @JsonKey(name: "OldImage") - final Map newImage; + @JsonKey(name: 'OldImage') + final Map? newImage; factory AwsDynamoDBUpdateRecord.fromJson(Map json) => _$AwsDynamoDBUpdateRecordFromJson(json); @@ -31,27 +32,27 @@ class AwsDynamoDBUpdateRecord { class AwsDynamoDBUpdateEventRecord { /// Event Id ... @JsonKey() - final String eventId; + final String? eventId; /// Event Name ... @JsonKey() - final String eventName; + final String? eventName; /// Event Source ... @JsonKey() - final String eventSource; + final String? eventSource; /// Event Version ... @JsonKey() - final String eventVersion; + final String? eventVersion; /// AWS Region ... @JsonKey() - final String awsRegion; + final String? awsRegion; /// Event Source ARN ... @JsonKey() - final String eventSourceARN; + final String? eventSourceARN; factory AwsDynamoDBUpdateEventRecord.fromJson(Map json) => _$AwsDynamoDBUpdateEventRecordFromJson(json); @@ -69,10 +70,10 @@ class AwsDynamoDBUpdateEventRecord { /// DynamoDB Update Event ... @JsonSerializable() -class AwsDynamoDBUpdateEvent { +class AwsDynamoDBUpdateEvent extends Event { /// awslogs ... - @JsonKey(name: "Records") - final List records; + @JsonKey(name: 'Records') + final List? records; factory AwsDynamoDBUpdateEvent.fromJson(Map json) => _$AwsDynamoDBUpdateEventFromJson(json); diff --git a/lib/events/dynamodb_event.g.dart b/lib/events/dynamodb_event.g.dart index 82de5627..92d497a0 100644 --- a/lib/events/dynamodb_event.g.dart +++ b/lib/events/dynamodb_event.g.dart @@ -9,9 +9,9 @@ part of 'dynamodb_event.dart'; AwsDynamoDBUpdateRecord _$AwsDynamoDBUpdateRecordFromJson( Map json) { return AwsDynamoDBUpdateRecord( - keys: json['Keys'] as Map, - oldImage: json['NewImage'] as Map, - newImage: json['OldImage'] as Map, + keys: json['Keys'] as Map?, + oldImage: json['NewImage'] as Map?, + newImage: json['OldImage'] as Map?, ); } @@ -26,12 +26,12 @@ Map _$AwsDynamoDBUpdateRecordToJson( AwsDynamoDBUpdateEventRecord _$AwsDynamoDBUpdateEventRecordFromJson( Map json) { return AwsDynamoDBUpdateEventRecord( - eventId: json['eventId'] as String, - eventName: json['eventName'] as String, - eventSource: json['eventSource'] as String, - eventVersion: json['eventVersion'] as String, - awsRegion: json['awsRegion'] as String, - eventSourceARN: json['eventSourceARN'] as String, + eventId: json['eventId'] as String?, + eventName: json['eventName'] as String?, + eventSource: json['eventSource'] as String?, + eventVersion: json['eventVersion'] as String?, + awsRegion: json['awsRegion'] as String?, + eventSourceARN: json['eventSourceARN'] as String?, ); } @@ -49,11 +49,10 @@ Map _$AwsDynamoDBUpdateEventRecordToJson( AwsDynamoDBUpdateEvent _$AwsDynamoDBUpdateEventFromJson( Map json) { return AwsDynamoDBUpdateEvent( - records: (json['Records'] as List) - ?.map((e) => e == null - ? null - : AwsDynamoDBUpdateEventRecord.fromJson(e as Map)) - ?.toList(), + records: (json['Records'] as List?) + ?.map((e) => + AwsDynamoDBUpdateEventRecord.fromJson(e as Map)) + .toList(), ); } diff --git a/lib/events/kinesis_data_firehose_event.dart b/lib/events/kinesis_data_firehose_event.dart index fcfd8fdb..bea0ed0c 100644 --- a/lib/events/kinesis_data_firehose_event.dart +++ b/lib/events/kinesis_data_firehose_event.dart @@ -1,21 +1,22 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'kinesis_data_firehose_event.g.dart'; /// Kinesis ..... @JsonSerializable() -class AwsKinesisFirehoseData { +class AwsKinesisFirehoseData extends Event { /// Record ID ... @JsonKey() - final String recordId; + final String? recordId; /// Approximated Arrival Timestamp ... @JsonKey() - final int approximateArrivalTimestamp; + final int? approximateArrivalTimestamp; /// Data ... @JsonKey() - final String data; + final String? data; factory AwsKinesisFirehoseData.fromJson(Map json) { return _$AwsKinesisFirehoseDataFromJson(json); @@ -32,19 +33,19 @@ class AwsKinesisFirehoseData { class AwsKinesisFirehoseDataEvent { /// Invocation ID ... @JsonKey() - final String invocationId; + final String? invocationId; /// Delivery Stream ARN ... @JsonKey() - final String deliveryStreamArn; + final String? deliveryStreamArn; /// Region ... @JsonKey() - final String region; + final String? region; /// Records ... @JsonKey() - final List records; + final List? records; factory AwsKinesisFirehoseDataEvent.fromJson(Map json) { return _$AwsKinesisFirehoseDataEventFromJson(json); diff --git a/lib/events/kinesis_data_firehose_event.g.dart b/lib/events/kinesis_data_firehose_event.g.dart index 7785f615..028b9446 100644 --- a/lib/events/kinesis_data_firehose_event.g.dart +++ b/lib/events/kinesis_data_firehose_event.g.dart @@ -9,9 +9,9 @@ part of 'kinesis_data_firehose_event.dart'; AwsKinesisFirehoseData _$AwsKinesisFirehoseDataFromJson( Map json) { return AwsKinesisFirehoseData( - recordId: json['recordId'] as String, - data: json['data'] as String, - approximateArrivalTimestamp: json['approximateArrivalTimestamp'] as int, + recordId: json['recordId'] as String?, + data: json['data'] as String?, + approximateArrivalTimestamp: json['approximateArrivalTimestamp'] as int?, ); } @@ -26,14 +26,12 @@ Map _$AwsKinesisFirehoseDataToJson( AwsKinesisFirehoseDataEvent _$AwsKinesisFirehoseDataEventFromJson( Map json) { return AwsKinesisFirehoseDataEvent( - records: (json['records'] as List) - ?.map((e) => e == null - ? null - : AwsKinesisFirehoseData.fromJson(e as Map)) - ?.toList(), - invocationId: json['invocationId'] as String, - deliveryStreamArn: json['deliveryStreamArn'] as String, - region: json['region'] as String, + records: (json['records'] as List?) + ?.map((e) => AwsKinesisFirehoseData.fromJson(e as Map)) + .toList(), + invocationId: json['invocationId'] as String?, + deliveryStreamArn: json['deliveryStreamArn'] as String?, + region: json['region'] as String?, ); } diff --git a/lib/events/kinesis_data_stream_event.dart b/lib/events/kinesis_data_stream_event.dart index c83a0865..a3ea4b78 100644 --- a/lib/events/kinesis_data_stream_event.dart +++ b/lib/events/kinesis_data_stream_event.dart @@ -1,29 +1,30 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'kinesis_data_stream_event.g.dart'; /// Kinesis ..... @JsonSerializable() -class AwsKinesisDataStream { +class AwsKinesisDataStream extends Event { /// Partition Key ... @JsonKey() - final String partitionKey; + final String? partitionKey; /// Kinesis Schema Version ... @JsonKey() - final String kinesisSchemaVersion; + final String? kinesisSchemaVersion; /// Data ... @JsonKey() - final String data; + final String? data; /// Sequenzer Number ... @JsonKey() - final String sequenceNumber; + final String? sequenceNumber; /// Approximate Arrival Timestamp ... @JsonKey() - final int approximateArrivalTimestamp; + final int? approximateArrivalTimestamp; factory AwsKinesisDataStream.fromJson(Map json) { return _$AwsKinesisDataStreamFromJson(json); @@ -44,35 +45,35 @@ class AwsKinesisDataStream { class AwsKinesisDataStreamRecord { /// Data ... @JsonKey() - final AwsKinesisDataStream kinesis; + final AwsKinesisDataStream? kinesis; /// Source of the Event. @JsonKey() - final String eventSource; + final String? eventSource; /// Event Id ... @JsonKey() - final String eventID; + final String? eventID; /// Event Version ... @JsonKey() - final String eventVersion; + final String? eventVersion; /// Event Name ... @JsonKey() - final String eventName; + final String? eventName; /// Event Source ARN ... @JsonKey() - final String eventSourceARN; + final String? eventSourceARN; /// Invokey Identity ARN ... @JsonKey() - final String invokeIdentityArn; + final String? invokeIdentityArn; /// Aws Region this event was emitted from @JsonKey() - final String awsRegion; + final String? awsRegion; factory AwsKinesisDataStreamRecord.fromJson(Map json) { return _$AwsKinesisDataStreamRecordFromJson(json); @@ -93,10 +94,10 @@ class AwsKinesisDataStreamRecord { /// Kinesis Event ... @JsonSerializable() -class AwsKinesisDataStreamEvent { +class AwsKinesisDataStreamEvent extends Event { /// The SQS message records that have been send with the event. - @JsonKey(name: "Records") - final List records; + @JsonKey(name: 'Records') + final List? records; factory AwsKinesisDataStreamEvent.fromJson(Map json) { return _$AwsKinesisDataStreamEventFromJson(json); diff --git a/lib/events/kinesis_data_stream_event.g.dart b/lib/events/kinesis_data_stream_event.g.dart index 8bfd3cb6..c1bbf2ac 100644 --- a/lib/events/kinesis_data_stream_event.g.dart +++ b/lib/events/kinesis_data_stream_event.g.dart @@ -8,11 +8,11 @@ part of 'kinesis_data_stream_event.dart'; AwsKinesisDataStream _$AwsKinesisDataStreamFromJson(Map json) { return AwsKinesisDataStream( - partitionKey: json['partitionKey'] as String, - kinesisSchemaVersion: json['kinesisSchemaVersion'] as String, - data: json['data'] as String, - sequenceNumber: json['sequenceNumber'] as String, - approximateArrivalTimestamp: json['approximateArrivalTimestamp'] as int, + partitionKey: json['partitionKey'] as String?, + kinesisSchemaVersion: json['kinesisSchemaVersion'] as String?, + data: json['data'] as String?, + sequenceNumber: json['sequenceNumber'] as String?, + approximateArrivalTimestamp: json['approximateArrivalTimestamp'] as int?, ); } @@ -33,13 +33,13 @@ AwsKinesisDataStreamRecord _$AwsKinesisDataStreamRecordFromJson( ? null : AwsKinesisDataStream.fromJson( json['kinesis'] as Map), - invokeIdentityArn: json['invokeIdentityArn'] as String, - eventName: json['eventName'] as String, - eventID: json['eventID'] as String, - eventSource: json['eventSource'] as String, - eventVersion: json['eventVersion'] as String, - eventSourceARN: json['eventSourceARN'] as String, - awsRegion: json['awsRegion'] as String, + invokeIdentityArn: json['invokeIdentityArn'] as String?, + eventName: json['eventName'] as String?, + eventID: json['eventID'] as String?, + eventSource: json['eventSource'] as String?, + eventVersion: json['eventVersion'] as String?, + eventSourceARN: json['eventSourceARN'] as String?, + awsRegion: json['awsRegion'] as String?, ); } @@ -59,11 +59,10 @@ Map _$AwsKinesisDataStreamRecordToJson( AwsKinesisDataStreamEvent _$AwsKinesisDataStreamEventFromJson( Map json) { return AwsKinesisDataStreamEvent( - records: (json['Records'] as List) - ?.map((e) => e == null - ? null - : AwsKinesisDataStreamRecord.fromJson(e as Map)) - ?.toList(), + records: (json['Records'] as List?) + ?.map((e) => + AwsKinesisDataStreamRecord.fromJson(e as Map)) + .toList(), ); } diff --git a/lib/events/s3_event.dart b/lib/events/s3_event.dart index 26af55bf..67eede36 100644 --- a/lib/events/s3_event.dart +++ b/lib/events/s3_event.dart @@ -1,3 +1,4 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 's3_event.g.dart'; @@ -5,9 +6,9 @@ part 's3_event.g.dart'; /// Representing a recorded S3 Event send to the Lambda. /// This can be send in batches of operations. @JsonSerializable() -class AwsS3Event { - @JsonKey(name: "Records") - final List records; +class AwsS3Event extends Event { + @JsonKey(name: 'Records') + final List? records; const AwsS3Event({this.records}); @@ -20,15 +21,15 @@ class AwsS3Event { /// Notifcation Event for Lambda in S3. @JsonSerializable() class AwsS3EventRecord { - final String eventVersion; - final String eventSource; - final String awsRegion; - final DateTime eventTime; - final String eventName; - final AwsS3UserIdentity userIdentity; - final Map requestParameters; - final Map responseElements; - final AwsS3Data s3; + final String? eventVersion; + final String? eventSource; + final String? awsRegion; + final DateTime? eventTime; + final String? eventName; + final AwsS3UserIdentity? userIdentity; + final Map? requestParameters; + final Map? responseElements; + final AwsS3Data? s3; const AwsS3EventRecord( {this.eventName, @@ -49,10 +50,10 @@ class AwsS3EventRecord { @JsonSerializable() class AwsS3Data { - String s3SchemaVersion; - String configurationId; - AwsS3Bucket bucket; - AWSS3EventObject object; + String? s3SchemaVersion; + String? configurationId; + AwsS3Bucket? bucket; + AWSS3EventObject? object; AwsS3Data( {this.s3SchemaVersion, this.configurationId, this.bucket, this.object}); @@ -65,9 +66,9 @@ class AwsS3Data { @JsonSerializable() class AwsS3Bucket { - String name; - AwsS3UserIdentity ownerIdentity; - String arn; + String? name; + AwsS3UserIdentity? ownerIdentity; + String? arn; AwsS3Bucket({this.name, this.ownerIdentity, this.arn}); @@ -79,10 +80,10 @@ class AwsS3Bucket { @JsonSerializable() class AWSS3EventObject { - String key; - int size; - String eTag; - String sequencer; + String? key; + int? size; + String? eTag; + String? sequencer; AWSS3EventObject({this.key, this.size, this.eTag, this.sequencer}); @@ -94,7 +95,7 @@ class AWSS3EventObject { @JsonSerializable() class AwsS3UserIdentity { - String principalId; + String? principalId; AwsS3UserIdentity({this.principalId}); diff --git a/lib/events/s3_event.g.dart b/lib/events/s3_event.g.dart index 6654fdf8..a8a36df5 100644 --- a/lib/events/s3_event.g.dart +++ b/lib/events/s3_event.g.dart @@ -8,11 +8,9 @@ part of 's3_event.dart'; AwsS3Event _$AwsS3EventFromJson(Map json) { return AwsS3Event( - records: (json['Records'] as List) - ?.map((e) => e == null - ? null - : AwsS3EventRecord.fromJson(e as Map)) - ?.toList(), + records: (json['Records'] as List?) + ?.map((e) => AwsS3EventRecord.fromJson(e as Map)) + .toList(), ); } @@ -23,21 +21,22 @@ Map _$AwsS3EventToJson(AwsS3Event instance) => AwsS3EventRecord _$AwsS3EventRecordFromJson(Map json) { return AwsS3EventRecord( - eventName: json['eventName'] as String, - eventSource: json['eventSource'] as String, - awsRegion: json['awsRegion'] as String, + eventName: json['eventName'] as String?, + eventSource: json['eventSource'] as String?, + awsRegion: json['awsRegion'] as String?, eventTime: json['eventTime'] == null ? null : DateTime.parse(json['eventTime'] as String), - eventVersion: json['eventVersion'] as String, + eventVersion: json['eventVersion'] as String?, userIdentity: json['userIdentity'] == null ? null : AwsS3UserIdentity.fromJson( json['userIdentity'] as Map), - requestParameters: (json['requestParameters'] as Map)?.map( + requestParameters: + (json['requestParameters'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), - responseElements: (json['responseElements'] as Map)?.map( + responseElements: (json['responseElements'] as Map?)?.map( (k, e) => MapEntry(k, e as String), ), s3: json['s3'] == null @@ -61,8 +60,8 @@ Map _$AwsS3EventRecordToJson(AwsS3EventRecord instance) => AwsS3Data _$AwsS3DataFromJson(Map json) { return AwsS3Data( - s3SchemaVersion: json['s3SchemaVersion'] as String, - configurationId: json['configurationId'] as String, + s3SchemaVersion: json['s3SchemaVersion'] as String?, + configurationId: json['configurationId'] as String?, bucket: json['bucket'] == null ? null : AwsS3Bucket.fromJson(json['bucket'] as Map), @@ -81,12 +80,12 @@ Map _$AwsS3DataToJson(AwsS3Data instance) => { AwsS3Bucket _$AwsS3BucketFromJson(Map json) { return AwsS3Bucket( - name: json['name'] as String, + name: json['name'] as String?, ownerIdentity: json['ownerIdentity'] == null ? null : AwsS3UserIdentity.fromJson( json['ownerIdentity'] as Map), - arn: json['arn'] as String, + arn: json['arn'] as String?, ); } @@ -99,10 +98,10 @@ Map _$AwsS3BucketToJson(AwsS3Bucket instance) => AWSS3EventObject _$AWSS3EventObjectFromJson(Map json) { return AWSS3EventObject( - key: json['key'] as String, - size: json['size'] as int, - eTag: json['eTag'] as String, - sequencer: json['sequencer'] as String, + key: json['key'] as String?, + size: json['size'] as int?, + eTag: json['eTag'] as String?, + sequencer: json['sequencer'] as String?, ); } @@ -116,7 +115,7 @@ Map _$AWSS3EventObjectToJson(AWSS3EventObject instance) => AwsS3UserIdentity _$AwsS3UserIdentityFromJson(Map json) { return AwsS3UserIdentity( - principalId: json['principalId'] as String, + principalId: json['principalId'] as String?, ); } diff --git a/lib/events/sqs_event.dart b/lib/events/sqs_event.dart index b3cc57c8..21c6acdc 100644 --- a/lib/events/sqs_event.dart +++ b/lib/events/sqs_event.dart @@ -1,45 +1,46 @@ +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; import 'package:json_annotation/json_annotation.dart'; part 'sqs_event.g.dart'; /// SQS Event Record that is send via [AwsSQSEvent]. @JsonSerializable() -class AwsSQSEventRecord { +class AwsSQSEventRecord extends Event { /// Id of the SQS message. @JsonKey() - final String messageId; + final String? messageId; /// Name of the receipt handle. @JsonKey() - final String receiptHandle; + final String? receiptHandle; /// Body of the message @JsonKey() - final String body; + final String? body; /// Attributes that are send with the event. @JsonKey() - final Map attributes; + final Map? attributes; /// Message attributes that are send with the event. @JsonKey() - final Map messageAttributes; + final Map? messageAttributes; /// The md5 hash of the message body. @JsonKey() - final String md5OfBody; + final String? md5OfBody; /// Source of the Event. @JsonKey() - final String eventSource; + final String? eventSource; /// Source of the Event ARN. @JsonKey() - final String eventSourceARN; + final String? eventSourceARN; /// Aws Region this event was emitted from @JsonKey() - final String awsRegion; + final String? awsRegion; factory AwsSQSEventRecord.fromJson(Map json) { return _$AwsSQSEventRecordFromJson(json); @@ -62,10 +63,10 @@ class AwsSQSEventRecord { /// Event that is send via SQS to trigger for an innovation /// of a Lambda. @JsonSerializable() -class AwsSQSEvent { +class AwsSQSEvent extends Event { /// The SQS message records that have been send with the event. - @JsonKey(name: "Records") - final List records; + @JsonKey(name: 'Records') + final List? records; factory AwsSQSEvent.fromJson(Map json) { return _$AwsSQSEventFromJson(json); diff --git a/lib/events/sqs_event.g.dart b/lib/events/sqs_event.g.dart index df3b983f..ac257207 100644 --- a/lib/events/sqs_event.g.dart +++ b/lib/events/sqs_event.g.dart @@ -8,15 +8,15 @@ part of 'sqs_event.dart'; AwsSQSEventRecord _$AwsSQSEventRecordFromJson(Map json) { return AwsSQSEventRecord( - messageId: json['messageId'] as String, - body: json['body'] as String, - receiptHandle: json['receiptHandle'] as String, - attributes: json['attributes'] as Map, - messageAttributes: json['messageAttributes'] as Map, - md5OfBody: json['md5OfBody'] as String, - eventSource: json['eventSource'] as String, - eventSourceARN: json['eventSourceARN'] as String, - awsRegion: json['awsRegion'] as String, + messageId: json['messageId'] as String?, + body: json['body'] as String?, + receiptHandle: json['receiptHandle'] as String?, + attributes: json['attributes'] as Map?, + messageAttributes: json['messageAttributes'] as Map?, + md5OfBody: json['md5OfBody'] as String?, + eventSource: json['eventSource'] as String?, + eventSourceARN: json['eventSourceARN'] as String?, + awsRegion: json['awsRegion'] as String?, ); } @@ -35,11 +35,9 @@ Map _$AwsSQSEventRecordToJson(AwsSQSEventRecord instance) => AwsSQSEvent _$AwsSQSEventFromJson(Map json) { return AwsSQSEvent( - records: (json['Records'] as List) - ?.map((e) => e == null - ? null - : AwsSQSEventRecord.fromJson(e as Map)) - ?.toList(), + records: (json['Records'] as List?) + ?.map((e) => AwsSQSEventRecord.fromJson(e as Map)) + .toList(), ); } diff --git a/lib/runtime/context.dart b/lib/runtime/context.dart index 231eaafb..2bfe5801 100644 --- a/lib/runtime/context.dart +++ b/lib/runtime/context.dart @@ -1,4 +1,5 @@ import 'dart:io' show Platform; + import '../client/client.dart'; /// Context contains the Lambda execution context information. @@ -24,72 +25,74 @@ class Context { /// Creates a new [Context] from [NextInvocation] which is the data /// from the Lambda Runtime Interface for the next [Handler] invocation. - static fromNextInvocation(NextInvocation nextInvocation) { + static Context fromNextInvocation(NextInvocation nextInvocation) { return Context( - requestId: nextInvocation.requestId, - invokedFunction: nextInvocation.invokedFunctionArn); + handler: Client.handlerName!, + requestId: nextInvocation.requestId, + invokedFunction: nextInvocation.invokedFunctionArn, + ); } /// Handler that is used for the invocation of the function - String handler; + String? handler; /// Name of the function that is invoked. - String functionName; + String? functionName; /// Version of the function that is invoked. - String functionVersion; + String? functionVersion; /// Memory sized that is allocated to execution of the function. - String functionMemorySize; + String? functionMemorySize; /// Cloudwatch LogGroup that is associated with the Lambda. - String logGroupName; + String? logGroupName; /// Cloudwach LogStream that is associated with the Lambda. - String logStreamName; + String? logStreamName; /// Region that this function exists in. - String region; + String? region; /// The execution environment of the function. - String executionEnv; + String? executionEnv; /// Access key that is acquired via STS. - String accessKey; + String? accessKey; /// Secret access key that is acquired via STS. - String secretAccessKey; + String? secretAccessKey; /// The session token from STS. - String sessionToken; + String? sessionToken; /// Id of the request. /// You can use this to track the request for the invocation. - String requestId; + String? requestId; /// The ARN to identify the function. - String invokedFunctionArn; - - Context( - {String handler, - String functionName, - String functionMemorySize, - String logGroupName, - String logStreamName, - String requestId, - String invokedFunction, - String region, - String executionEnv, - String accessKey, - String secretAccessKey, - String sessionToken}) { - assert(requestId != null); + String? invokedFunctionArn; + + Context({ + String? handler, + String? functionName, + String? functionMemorySize, + String? logGroupName, + String? logStreamName, + required String requestId, + String? invokedFunction, + String? region, + String? executionEnv, + String? accessKey, + String? secretAccessKey, + String? sessionToken, + }) { assert(handler != null); this.handler = handler ?? Platform.environment[_kAWSLambdaHandler]; this.functionName = functionName ?? Platform.environment[_kAWSLambdaFunctionName]; - this.functionVersion = + functionVersion = functionVersion ?? Platform.environment[_kAWSLambdaFunctionVersion]; this.functionMemorySize = functionMemorySize ?? Platform.environment[_kAWSLambdaFunctionMemorySize]; @@ -98,7 +101,7 @@ class Context { this.logStreamName = logStreamName ?? Platform.environment[_kAWSLambdaLogStreamName]; this.requestId = requestId; - this.invokedFunctionArn = invokedFunctionArn; + invokedFunctionArn = invokedFunction; this.region = region ?? Platform.environment[_kAWSLambdaRegion]; this.executionEnv = executionEnv ?? Platform.environment[_kAWSLambdaExecutionEnv]; @@ -110,27 +113,28 @@ class Context { } /// Allows to copy a created [Context] over with some new settings. - Context copyWith( - {String handler, - String functionName, - String functionMemorySize, - String logGroupName, - String logStreamName, - String requestId, - String invokedFunction, - String region, - String executionEnv, - String accessKey, - String secretAccessKey, - String sessionToken}) { + Context copyWith({ + String? handler, + String? functionName, + String? functionMemorySize, + String? logGroupName, + String? logStreamName, + String? requestId, + String? invokedFunction, + String? region, + String? executionEnv, + String? accessKey, + String? secretAccessKey, + String? sessionToken, + }) { return Context( - handler: handler ?? this.handler, + handler: handler ?? this.handler!, functionName: functionName ?? this.functionName, functionMemorySize: functionMemorySize ?? this.functionMemorySize, logGroupName: logGroupName ?? this.logGroupName, logStreamName: logStreamName ?? this.logStreamName, - requestId: requestId ?? this.requestId, - invokedFunction: invokedFunction ?? this.invokedFunctionArn, + requestId: requestId ?? this.requestId!, + invokedFunction: invokedFunction ?? invokedFunctionArn, region: region ?? this.region, executionEnv: executionEnv ?? this.executionEnv, accessKey: accessKey ?? this.accessKey, diff --git a/lib/runtime/event.dart b/lib/runtime/event.dart index 3802e2cb..47ee9831 100644 --- a/lib/runtime/event.dart +++ b/lib/runtime/event.dart @@ -1,3 +1,5 @@ +import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; + import '../events/alb_event.dart'; import '../events/alexa_event.dart'; import '../events/apigateway_event.dart'; @@ -16,50 +18,47 @@ import '../events/kinesis_data_stream_event.dart'; /// Note is currently not supported to register your /// own events here. abstract class Event { - static final _registry = { - AwsCognitoEvent: (Map json) => - AwsCognitoEvent.fromJson(json), - AwsS3Event: (Map json) => AwsS3Event.fromJson(json), - AwsApiGatewayEvent: (Map json) => - AwsApiGatewayEvent.fromJson(json), - AwsAppSyncEvent: (Map json) => - AwsAppSyncEvent.fromJson(json), - AwsALBEvent: (Map json) => AwsALBEvent.fromJson(json), - AwsAlexaEvent: (Map json) => AwsAlexaEvent.fromJson(json), - AwsSQSEvent: (Map json) => AwsSQSEvent.fromJson(json), - AwsCloudwatchEvent: (Map json) => - AwsCloudwatchEvent.fromJson(json), - AwsCloudwatchLogEvent: (Map json) => - AwsCloudwatchLogEvent.fromJson(json), - AwsDynamoDBUpdateEvent: (Map json) => - AwsDynamoDBUpdateEvent.fromJson(json), - AwsKinesisDataStreamEvent: (Map json) => - AwsKinesisDataStreamEvent.fromJson(json) + const Event(); + static final Map)> _registry = { + AwsCognitoEvent: (Map? json) => + AwsCognitoEvent.fromJson(json!), + AwsS3Event: (Map? json) => AwsS3Event.fromJson(json!), + AwsApiGatewayEvent: (Map? json) => + AwsApiGatewayEvent.fromJson(json!), + AwsAppSyncEvent: (Map? json) => + AwsAppSyncEvent.fromJson(json!), + AwsALBEvent: (Map? json) => AwsALBEvent.fromJson(json!), + AwsAlexaEvent: (Map? json) => + AwsAlexaEvent.fromJson(json!), + AwsSQSEvent: (Map? json) => AwsSQSEvent.fromJson(json!), + AwsCloudwatchEvent: (Map? json) => + AwsCloudwatchEvent.fromJson(json!), + AwsCloudwatchLogEvent: (Map? json) => + AwsCloudwatchLogEvent.fromJson(json!), + AwsDynamoDBUpdateEvent: (Map? json) => + AwsDynamoDBUpdateEvent.fromJson(json!), + AwsKinesisDataStreamEvent: (Map? json) => + AwsKinesisDataStreamEvent.fromJson(json!) }; /// Checks if a type of event is already registered. - static exists() { + static bool exists() { return Event._registry.containsKey(T); } /// Returs the value of a registered event. It is [null] /// if no such event has been registered. - static value() { - return Event._registry[T]; - } + static T Function(Map)? value() => + Event._registry[T] as T Function(Map)?; /// Registers an event. - static registerEvent(func) { - Event._registry[T] = func; - } + static void registerEvent(T Function(Map) func) => + Event._registry[T] = func; /// Deregisters an event. - static deregisterEvent() { - Event._registry.remove(T); - } + static void deregisterEvent() => Event._registry.remove(T); /// Creates a new event from a handler type with the [NextInvocation.response]. - static fromHandler(Type type, Map json) { - return _registry[type](json); - } + static dynamic fromHandler(Type type, Map json) => + _registry[type]!(json); } diff --git a/lib/runtime/exception.dart b/lib/runtime/exception.dart index b655b0ad..b774f1e1 100644 --- a/lib/runtime/exception.dart +++ b/lib/runtime/exception.dart @@ -7,5 +7,5 @@ class RuntimeException implements Exception { final String cause; @override - String toString() => "RuntimeException: $cause"; + String toString() => 'RuntimeException: $cause'; } diff --git a/lib/runtime/runtime.dart b/lib/runtime/runtime.dart index 106d7474..06a929f7 100644 --- a/lib/runtime/runtime.dart +++ b/lib/runtime/runtime.dart @@ -1,23 +1,22 @@ import 'dart:async'; -import '../client/client.dart'; -import 'event.dart'; -import 'context.dart'; -import 'exception.dart'; +import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; + +import 'package:aws_lambda_dart_runtime/client/client.dart'; +import 'package:aws_lambda_dart_runtime/runtime/event.dart'; +import 'package:aws_lambda_dart_runtime/runtime/context.dart'; +import 'package:aws_lambda_dart_runtime/runtime/exception.dart'; /// A function which ingests and Event and a [Context] /// and returns a [InvocationResult]. The result is ecoded /// by the [Runtime] and posted to the Lambda API. -typedef Handler = Future Function( - Context context, T event); +typedef Handler = Future Function(Context context, E event); class _RuntimeHandler { final Type type; final dynamic handler; - const _RuntimeHandler(this.type, this.handler) - : assert(type != null), - assert(handler != null); + const _RuntimeHandler(this.type, this.handler) : assert(handler != null); } /// A Runtime manages the interface to the Lambda API. @@ -37,8 +36,8 @@ class _RuntimeHandler { /// ``` /// /// Note: You can register an -class Runtime { - Client _client; +class Runtime { + late Client _client; static final Runtime _singleton = Runtime._internal(); final Map _handlers = {}; @@ -54,7 +53,7 @@ class Runtime { /// Lists the registered handlers by name. /// The name is a simple [String] which reflects /// the name of the trigger in the Lambda Execution API. - List get handlers => _handlers.keys; + List get handlers => _handlers.keys.toList(); /// Checks if a specific handlers has been registered /// with the runtime. @@ -62,27 +61,24 @@ class Runtime { /// Register a handler function [Handler] with [name] /// which digests an event [T]. - Handler registerHandler(String name, Handler handler) { - _handlers[name] = _RuntimeHandler(T, handler); + Handler registerHandler(String name, Handler handler) { + _handlers[name] = _RuntimeHandler(E, handler); - return _handlers[name].handler; + return handler; } - /// Unregister a handler function [Handler] with [name]. - Handler deregisterHandler(String name) => - _handlers.remove(name).handler; + /// Unregister a handler function [Handler] with [name]. + Handler? deregisterHandler(String name) => + _handlers.remove(name)?.handler as Handler?; /// Register an new event to be ingested by a handler. /// The type should reflect your type in your handler definition [Handler]. - void registerEvent(func) { - Event.registerEvent(func); - } + void registerEvent(T Function(Map) func) => + Event.registerEvent(func); /// Deregister an new event to be ingested by a handler. /// The type should reflect your type in your handler definition [Handler]. - void deregisterEvent() { - Event.deregisterEvent(); - } + void deregisterEvent() => Event.deregisterEvent(); /// Run the [Runtime] in loop and digest events that are /// fetched from the AWS Lambda API Interface. The events are processed @@ -90,34 +86,31 @@ class Runtime { /// /// If the invocation of an event was successful the function /// sends the [InvocationResult] via [_client.postInvocationResponse(result)] to the API. - /// If there is an error during the execution. The execption gets catched + /// If there is an error during the execution. The exception gets caught /// and the error is posted via [_client.postInvocationError(err)] to the API. void invoke() async { - do { - NextInvocation nextInvocation; - - try { - // get the next invocation - nextInvocation = await _client.getNextInvocation(); - - // creating the new context - final context = Context.fromNextInvocation(nextInvocation); - - final func = _handlers[context.handler]; - if(func == null) { - throw RuntimeException('No handler with name "${context.handler}" registered in runtime!'); - } - final event = - Event.fromHandler(func.type, await nextInvocation.response); - final result = await func.handler(context, event); - - await _client.postInvocationResponse(result); - } on Exception catch (error, stacktrace) { - await _client.postInvocationError( - nextInvocation.requestId, InvocationError(error, stacktrace)); - } + while (true) { + await _handleInvocation(await _client.getNextInvocation()); + } + } + + Future _handleInvocation(NextInvocation nextInvocation) async { + try { + // creating the new context + final context = Context.fromNextInvocation(nextInvocation); - nextInvocation = null; - } while (true); + final func = _handlers[context.handler]; + if (func == null) { + throw RuntimeException( + 'No handler with name "${context.handler}" registered in runtime!'); + } + final event = Event.fromHandler(func.type, nextInvocation.response); + final result = await func.handler(context, event); + + await _client.postInvocationResponse(context.requestId, result); + } catch (error, stacktrace) { + await _client.postInvocationError( + nextInvocation.requestId, InvocationError(error, stacktrace)); + } } } diff --git a/pubspec.yaml b/pubspec.yaml index a2ea236f..cf577479 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -6,14 +6,16 @@ homepage: https://github.com/awslabs/aws-lambda-dart-runtime documentation: https://awslabs.github.io/aws-lambda-dart-runtime/ environment: - sdk: ">=2.6.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: - json_annotation: ^3.0.0 + json_annotation: ^4.0.1 + meta: ^1.3.0 + http: ^0.13.1 dev_dependencies: - json_serializable: ^3.2.3 + json_serializable: ^4.1.0 build_runner: ^1.7.2 - test: ^1.9.4 - mockito: ^4.1.1 - pedantic: ^1.0.0 + test: ^1.16.8 + mockito: ^5.0.3 + pedantic: ^1.11.0 diff --git a/test/alb_event_test.dart b/test/alb_event_test.dart index 5917753c..9ce66c04 100644 --- a/test/alb_event_test.dart +++ b/test/alb_event_test.dart @@ -1,46 +1,46 @@ import 'dart:io'; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; void main() { - group("albevent_default", () { - test("factory creates response with default values", () { - final response = AwsALBResponse.fromString("SUCCESS"); + group('albevent_default', () { + test('factory creates response with default values', () { + final response = AwsALBResponse.fromString('SUCCESS'); - expect(response.body, equals("SUCCESS")); + expect(response.body, equals('SUCCESS')); expect(response.statusCode, equals(200)); expect(response.isBase64Encoded, equals(false)); }); - test("factory creates a response with HTTP Status 400", () { - final response = AwsALBResponse.fromString("SUCCESS", + test('factory creates a response with HTTP Status 400', () { + final response = AwsALBResponse.fromString('SUCCESS', statusCode: HttpStatus.badRequest); - expect(response.body, equals("SUCCESS")); + expect(response.body, equals('SUCCESS')); expect(response.statusCode, equals(HttpStatus.badRequest)); expect(response.isBase64Encoded, equals(false)); }); - test("factory creates an event with html/text Header", () { - final response = AwsALBResponse.fromString(""); + test('factory creates an event with html/text Header', () { + final response = AwsALBResponse.fromString(''); expect(response.headers, - equals({"Content-Type": "text/html; charset=utf-8"})); + equals({'Content-Type': 'text/html; charset=utf-8'})); }); - test("factory creates an event with JSON Header", () { - final response = AwsALBResponse.fromString("", - headers: {"Content-Type": "application/json"}); + test('factory creates an event with JSON Header', () { + final response = AwsALBResponse.fromString('', + headers: {'Content-Type': 'application/json'}); - expect(response.headers, equals({"Content-Type": "application/json"})); + expect(response.headers, equals({'Content-Type': 'application/json'})); }); - test("factory creates response which is base64 encoded", () { + test('factory creates response which is base64 encoded', () { final response = - AwsALBResponse.fromString("SUCCESS", isBase64Encoded: true); + AwsALBResponse.fromString('SUCCESS', isBase64Encoded: true); - expect(response.body, equals("SUCCESS")); + expect(response.body, equals('SUCCESS')); expect(response.statusCode, equals(HttpStatus.ok)); expect(response.isBase64Encoded, equals(true)); }); diff --git a/test/apigateway_event_test.dart b/test/apigateway_event_test.dart index 09d7dc02..71be7e13 100644 --- a/test/apigateway_event_test.dart +++ b/test/apigateway_event_test.dart @@ -3,32 +3,33 @@ import 'dart:io' show File; import 'dart:convert'; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/apigateway_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final Map? json = + jsonDecode(contents) as Map?; void main() { - group("apigateway_default", () { - test("json got parsed and creates an event", () async { - final event = AwsApiGatewayEvent.fromJson(json); + group('apigateway_default', () { + test('json got parsed and creates an event', () async { + final event = AwsApiGatewayEvent.fromJson(json!); - expect(event.body, equals(jsonEncode({"foo": "bar"}))); - expect(event.path, equals("/test/hello")); - expect(event.headers.acceptEncoding, - equals("gzip, deflate, lzma, sdch, br")); - expect(event.requestContext.httpMethod, equals("POST")); - expect(event.requestContext.accountId, equals("123456789012")); - expect(event.requestContext.requestId, - equals("41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9")); - expect(event.queryStringParameters, equals({"name": "me"})); - expect(event.requestContext.resourcePath, equals("/{proxy+}")); - expect(event.headers.raw['Accept-Encoding'], - equals("gzip, deflate, lzma, sdch, br")); + expect(event.body, equals(jsonEncode({'foo': 'bar'}))); + expect(event.path, equals('/test/hello')); + expect(event.headers!.acceptEncoding, + equals('gzip, deflate, lzma, sdch, br')); + expect(event.requestContext!.httpMethod, equals('POST')); + expect(event.requestContext!.accountId, equals('123456789012')); + expect(event.requestContext!.requestId, + equals('41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9')); + expect(event.queryStringParameters, equals({'name': 'me'})); + expect(event.requestContext!.resourcePath, equals('/{proxy+}')); + expect(event.headers!.raw['Accept-Encoding'], + equals('gzip, deflate, lzma, sdch, br')); }); - test("factory creates event with default values", () { + test('factory creates event with default values', () { final response = AwsApiGatewayResponse.fromJson({}); expect(response.body, equals({}.toString())); @@ -36,7 +37,7 @@ void main() { expect(response.isBase64Encoded, equals(false)); }); - test("factory creates an event with HTTP Status 400", () { + test('factory creates an event with HTTP Status 400', () { final response = AwsApiGatewayResponse.fromJson({}, statusCode: HttpStatus.badRequest); @@ -45,21 +46,21 @@ void main() { expect(response.isBase64Encoded, equals(false)); }); - test("factory creates an event with JSON Header", () { + test('factory creates an event with JSON Header', () { final response = AwsApiGatewayResponse.fromJson({}); - expect(response.headers, equals({"Content-Type": "application/json"})); + expect(response.headers, equals({'Content-Type': 'application/json'})); }); - test("factory creates an event with text/html Header", () { + test('factory creates an event with text/html Header', () { final response = AwsApiGatewayResponse.fromJson({}, - headers: {"Content-Type": "text/html; charset=utf-8"}); + headers: {'Content-Type': 'text/html; charset=utf-8'}); expect(response.headers, - equals({"Content-Type": "text/html; charset=utf-8"})); + equals({'Content-Type': 'text/html; charset=utf-8'})); }); - test("factory creates an event with is based 64 encoded", () { + test('factory creates an event with is based 64 encoded', () { final response = AwsApiGatewayResponse.fromJson({}, isBase64Encoded: true); diff --git a/test/client_test.dart b/test/client_test.dart index 6552fe6f..1a3d2f5e 100644 --- a/test/client_test.dart +++ b/test/client_test.dart @@ -1,20 +1,20 @@ -import "package:test/test.dart"; +import 'package:test/test.dart'; import 'package:aws_lambda_dart_runtime/client/client.dart'; void main() { group('invocation', () { - test("invocation result gets populated", () { - final result = InvocationResult("1234567890", "SUCCESS"); + test('invocation result gets populated', () { + final result = InvocationResult('1234567890', 'SUCCESS'); - expect(result.requestId, "1234567890"); - expect(result.body, "SUCCESS"); + expect(result.requestId, '1234567890'); + expect(result.body, 'SUCCESS'); }); - test("invocation error gets populated", () { - final stateError = new StateError("foo"); + test('invocation error gets populated', () { + final stateError = StateError('foo'); final invocationError = - InvocationError(stateError, new StackTrace.fromString("")); + InvocationError(stateError, StackTrace.fromString('')); expect(invocationError.error, stateError); }); diff --git a/test/cloudwatch_event_test.dart b/test/cloudwatch_event_test.dart index 42717a24..2bbbcd12 100644 --- a/test/cloudwatch_event_test.dart +++ b/test/cloudwatch_event_test.dart @@ -2,24 +2,24 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/cloudwatch_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("cloudwatch_default", () { - test("json got parsed and creates an event", () async { - final event = AwsCloudwatchEvent.fromJson(json); + group('cloudwatch_default', () { + test('json got parsed and creates an event', () async { + final event = AwsCloudwatchEvent.fromJson(json!); - expect(event.account, equals("1234567890")); - expect(event.region, equals("eu-west-1")); - expect(event.detailType, equals("Scheduled Event")); - expect(event.id, equals("cdc73f9d-aea9-11e3-9d5a-835b769c0d9c")); + expect(event.account, equals('1234567890')); + expect(event.region, equals('eu-west-1')); + expect(event.detailType, equals('Scheduled Event')); + expect(event.id, equals('cdc73f9d-aea9-11e3-9d5a-835b769c0d9c')); expect(event.detail, equals({})); - expect(event.time, equals(DateTime.parse("1970-01-01T00:00:00Z"))); + expect(event.time, equals(DateTime.parse('1970-01-01T00:00:00Z'))); }); }); } diff --git a/test/cloudwatch_log_event_test.dart b/test/cloudwatch_log_event_test.dart index 316e4c5f..cb6faebb 100644 --- a/test/cloudwatch_log_event_test.dart +++ b/test/cloudwatch_log_event_test.dart @@ -2,23 +2,23 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/cloudwatch_log_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("cloudwatch_log_default", () { - test("json got parsed and creates an event", () async { - final event = AwsCloudwatchLogEvent.fromJson(json); + group('cloudwatch_log_default', () { + test('json got parsed and creates an event', () async { + final event = AwsCloudwatchLogEvent.fromJson(json!); expect( event.awslogs, equals({ - "data": - "H4sIAAAAAAAAAHWPwQqCQBCGX0Xm7EFtK+smZBEUgXoLCdMhFtKV3akI8d0bLYmibvPPN3wz00CJxmQnTO41whwWQRIctmEcB6sQbFC3CjW3XW8kxpOpP+OC22d1Wml1qZkQGtoMsScxaczKN3plG8zlaHIta5KqWsozoTYw3/djzwhpLwivWFGHGpAFe7DL68JlBUk+l7KSN7tCOEJ4M3/qOI49vMHj+zCKdlFqLaU2ZHV2a4Ct/an0/ivdX8oYc1UVX860fQDQiMdxRQEAAA==" + 'data': + 'H4sIAAAAAAAAAHWPwQqCQBCGX0Xm7EFtK+smZBEUgXoLCdMhFtKV3akI8d0bLYmibvPPN3wz00CJxmQnTO41whwWQRIctmEcB6sQbFC3CjW3XW8kxpOpP+OC22d1Wml1qZkQGtoMsScxaczKN3plG8zlaHIta5KqWsozoTYw3/djzwhpLwivWFGHGpAFe7DL68JlBUk+l7KSN7tCOEJ4M3/qOI49vMHj+zCKdlFqLaU2ZHV2a4Ct/an0/ivdX8oYc1UVX860fQDQiMdxRQEAAA==' })); }); }); diff --git a/test/cognito_event_test.dart b/test/cognito_event_test.dart index 24ba6966..25f69ed5 100644 --- a/test/cognito_event_test.dart +++ b/test/cognito_event_test.dart @@ -2,24 +2,24 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/cognito_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("cognito_default", () { - test("json got parsed and creates an event", () async { - final event = AwsCognitoEvent.fromJson(json); + group('cognito_default', () { + test('json got parsed and creates an event', () async { + final event = AwsCognitoEvent.fromJson(json!); expect(event.version, equals(1)); - expect(event.userPoolId, equals("1234567")); - expect(event.userName, equals("foo")); - expect(event.response.smsMessage, equals("foo")); - expect(event.response.emailSubject, equals("foo")); - expect(event.response.emailMessage, equals("bar")); + expect(event.userPoolId, equals('1234567')); + expect(event.userName, equals('foo')); + expect(event.response!.smsMessage, equals('foo')); + expect(event.response!.emailSubject, equals('foo')); + expect(event.response!.emailMessage, equals('bar')); }); }); } diff --git a/test/common.dart b/test/common.dart deleted file mode 100644 index 291d16c5..00000000 --- a/test/common.dart +++ /dev/null @@ -1,49 +0,0 @@ -import 'dart:io'; - -import 'package:mockito/mockito.dart'; - -class MockHttpClientResponse extends Mock implements HttpClientResponse { - MockHttpClientResponse(this.statusCode, - {this.result, this.headers, this.body}); - - @override - final int statusCode; - - final String result; - - @override - final HttpHeaders headers; - - // encode the response body as bytes. - final List body; -} - -/// A mocked [HttpHeaders] that ignores all writes. -class MockHttpHeaders extends HttpHeaders { - @override - List operator [](String name) => []; - - @override - void add(String name, Object value, {bool preserveHeaderCase = false}) {} - - @override - void clear() {} - - @override - void forEach(void Function(String name, List values) f) {} - - @override - void noFolding(String name) {} - - @override - void remove(String name, Object value) {} - - @override - void removeAll(String name) {} - - @override - void set(String name, Object value, {bool preserveHeaderCase = false}) {} - - @override - String value(String name) => null; -} diff --git a/test/context_test.dart b/test/context_test.dart index d6bfaad8..d587bd76 100644 --- a/test/context_test.dart +++ b/test/context_test.dart @@ -1,48 +1,43 @@ -import "dart:convert"; - -import "package:test/test.dart"; +import 'package:http/http.dart'; +import 'package:test/test.dart'; import 'package:aws_lambda_dart_runtime/runtime/context.dart'; import 'package:aws_lambda_dart_runtime/client/client.dart'; -import 'common.dart'; void main() { group('context', () { - test("Context gets initialized with a Platform.environment", () async { - final Map environment = { - "_HANDLER": "foo", - "AWS_LAMBDA_FUNCTION_NAME": "bar", - "AWS_LAMBDA_FUNCTION_VERSION": "1", - "AWS_LAMBDA_LOG_GROUP_NAME": "foo", - "AWS_LAMBDA_LOG_STREAM_NAME": "foo", - "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "128", - "AWS_REGION": "eu-west-1", - "AWS_EXECUTION_ENV": "foo", - "AWS_ACCESS_KEY_ID": "secret", - "AWS_SECRET_ACCESS_KEY": "key", - "AWS_SESSION_TOKEN": "1234567890" + test('Context gets initialized with a Platform.environment', () async { + final environment = { + '_HANDLER': 'foo', + 'AWS_LAMBDA_FUNCTION_NAME': 'bar', + 'AWS_LAMBDA_FUNCTION_VERSION': '1', + 'AWS_LAMBDA_LOG_GROUP_NAME': 'foo', + 'AWS_LAMBDA_LOG_STREAM_NAME': 'foo', + 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE': '128', + 'AWS_REGION': 'eu-west-1', + 'AWS_EXECUTION_ENV': 'foo', + 'AWS_ACCESS_KEY_ID': 'secret', + 'AWS_SECRET_ACCESS_KEY': 'key', + 'AWS_SESSION_TOKEN': '1234567890' }; - final headers = MockHttpHeaders(); - - final response = MockHttpClientResponse(200, - result: "", headers: headers, body: utf8.encode("{}")); - final nextInvocation = await NextInvocation.fromResponse(response); + final nextInvocation = + await NextInvocation.fromResponse(Response('{}', 200)); final ctx = Context.fromNextInvocation(nextInvocation); - expect(ctx.handler, environment["_HANDLER"]); - expect(ctx.functionName, environment["AWS_LAMBDA_FUNCTION_NAME"]); - expect(ctx.functionVersion, environment["AWS_LAMBDA_FUNCTION_VERSION"]); - expect(ctx.logGroupName, environment["AWS_LAMBDA_LOG_GROUP_NAME"]); - expect(ctx.logStreamName, environment["AWS_LAMBDA_LOG_STREAM_NAME"]); + expect(ctx.handler, environment['_HANDLER']); + expect(ctx.functionName, environment['AWS_LAMBDA_FUNCTION_NAME']); + expect(ctx.functionVersion, environment['AWS_LAMBDA_FUNCTION_VERSION']); + expect(ctx.logGroupName, environment['AWS_LAMBDA_LOG_GROUP_NAME']); + expect(ctx.logStreamName, environment['AWS_LAMBDA_LOG_STREAM_NAME']); expect(ctx.functionMemorySize, - environment["AWS_LAMBDA_FUNCTION_MEMORY_SIZE"]); - expect(ctx.region, environment["AWS_REGION"]); - expect(ctx.executionEnv, environment["AWS_EXECUTION_ENV"]); - expect(ctx.accessKey, environment["AWS_ACCESS_KEY_ID"]); - expect(ctx.secretAccessKey, environment["AWS_SECRET_ACCESS_KEY"]); - expect(ctx.sessionToken, environment["AWS_SESSION_TOKEN"]); + environment['AWS_LAMBDA_FUNCTION_MEMORY_SIZE']); + expect(ctx.region, environment['AWS_REGION']); + expect(ctx.executionEnv, environment['AWS_EXECUTION_ENV']); + expect(ctx.accessKey, environment['AWS_ACCESS_KEY_ID']); + expect(ctx.secretAccessKey, environment['AWS_SECRET_ACCESS_KEY']); + expect(ctx.sessionToken, environment['AWS_SESSION_TOKEN']); }); - }, skip: "the tests are not quite ready"); + }, skip: 'the tests are not quite ready'); } diff --git a/test/dynamodb_event_test.dart b/test/dynamodb_event_test.dart index 31ebb878..01daec3c 100644 --- a/test/dynamodb_event_test.dart +++ b/test/dynamodb_event_test.dart @@ -2,19 +2,19 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/dynamodb_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("dynamodb_default", () { - test("json got parsed and creates an event", () async { - final event = AwsDynamoDBUpdateEvent.fromJson(json); + group('dynamodb_default', () { + test('json got parsed and creates an event', () async { + final event = AwsDynamoDBUpdateEvent.fromJson(json!); - expect(event.records.length, equals(1)); + expect(event.records!.length, equals(1)); }); }); } diff --git a/test/event_test.dart b/test/event_test.dart index f7f7c416..4a04d655 100644 --- a/test/event_test.dart +++ b/test/event_test.dart @@ -1,8 +1,8 @@ -import "package:test/test.dart"; +import 'package:test/test.dart'; import 'package:aws_lambda_dart_runtime/runtime/event.dart'; -class CustomTestEvent { +class CustomTestEvent extends Event { factory CustomTestEvent.fromJson(Map json) { return CustomTestEvent(); } @@ -12,16 +12,16 @@ class CustomTestEvent { void main() { group('runtime', () { - test("Custom event is add to the events", () { + test('Custom event is add to the events', () { Event.registerEvent( - (Map json) => CustomTestEvent.fromJson({})); + (Map? json) => CustomTestEvent.fromJson({})); expect(Event.exists(), true); }); - test("Custom event is deregistered", () { + test('Custom event is deregistered', () { Event.registerEvent( - (Map json) => CustomTestEvent.fromJson({})); + (Map? json) => CustomTestEvent.fromJson({})); Event.deregisterEvent(); diff --git a/test/exception_test.dart b/test/exception_test.dart index 9d620fbd..e98457c0 100644 --- a/test/exception_test.dart +++ b/test/exception_test.dart @@ -1,17 +1,17 @@ -import "package:test/test.dart"; +import 'package:test/test.dart'; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; void main() { - group("runtime exception", () { - test("return the cause a string", () { - final exception = RuntimeException("missing handler"); - expect(exception.toString(), equals("RuntimeException: missing handler")); + group('runtime exception', () { + test('return the cause a string', () { + final exception = RuntimeException('missing handler'); + expect(exception.toString(), equals('RuntimeException: missing handler')); }); - test("catch exception with cause", () { + test('catch exception with cause', () { try { - throw RuntimeException("missing handler"); + throw RuntimeException('missing handler'); } on RuntimeException catch (e) { expect(e.cause, 'missing handler'); return; diff --git a/test/kinesis_data_firehose_event.dart b/test/kinesis_data_firehose_event.dart index 34a7f702..716d0fec 100644 --- a/test/kinesis_data_firehose_event.dart +++ b/test/kinesis_data_firehose_event.dart @@ -2,28 +2,28 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/kinesis_data_firehose_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("kinesis_firehose_default", () { - test("json got parsed and creates an event", () async { - final event = AwsKinesisFirehoseDataEvent.fromJson(json); + group('kinesis_firehose_default', () { + test('json got parsed and creates an event', () async { + final event = AwsKinesisFirehoseDataEvent.fromJson(json!); - expect(event.records.length, equals(1)); - expect(event.invocationId, equals("invocationIdExample")); - expect(event.deliveryStreamArn, equals("arn:aws:kinesis:EXAMPLE")); - expect(event.region, equals("eu-west-1")); - expect(event.records[0].recordId, - equals("49546986683135544286507457936321625675700192471156785154")); + expect(event.records!.length, equals(1)); + expect(event.invocationId, equals('invocationIdExample')); + expect(event.deliveryStreamArn, equals('arn:aws:kinesis:EXAMPLE')); + expect(event.region, equals('eu-west-1')); + expect(event.records![0].recordId, + equals('49546986683135544286507457936321625675700192471156785154')); expect( - event.records[0].approximateArrivalTimestamp, equals(1495072949453)); - expect(event.records[0].data, - equals("SGVsbG8sIHRoaXMgaXMgYSB0ZXN0IDEyMy4=")); + event.records![0].approximateArrivalTimestamp, equals(1495072949453)); + expect(event.records![0].data, + equals('SGVsbG8sIHRoaXMgaXMgYSB0ZXN0IDEyMy4=')); }); }); } diff --git a/test/kinesis_data_stream_event_test.dart b/test/kinesis_data_stream_event_test.dart index dc082785..0ad8bd66 100644 --- a/test/kinesis_data_stream_event_test.dart +++ b/test/kinesis_data_stream_event_test.dart @@ -2,35 +2,36 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/kinesis_data_stream_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("kinesis_default", () { - test("json got parsed and creates an event", () async { - final event = AwsKinesisDataStreamEvent.fromJson(json); + group('kinesis_default', () { + test('json got parsed and creates an event', () async { + final event = AwsKinesisDataStreamEvent.fromJson(json!); - expect(event.records.length, equals(1)); - expect(event.records[0].eventSource, equals("aws:kinesis")); + expect(event.records!.length, equals(1)); + expect(event.records![0].eventSource, equals('aws:kinesis')); expect( - event.records[0].eventID, + event.records![0].eventID, equals( - "shardId-000000000000:49545115243490985018280067714973144582180062593244200961")); + 'shardId-000000000000:49545115243490985018280067714973144582180062593244200961')); expect( - event.records[0].eventSourceARN, equals("arn:aws:kinesis:EXAMPLE")); - expect(event.records[0].awsRegion, equals("eu-west-1")); - expect(event.records[0].eventVersion, equals("1.0")); + event.records![0].eventSourceARN, equals('arn:aws:kinesis:EXAMPLE')); + expect(event.records![0].awsRegion, equals('eu-west-1')); + expect(event.records![0].eventVersion, equals('1.0')); expect( - event.records[0].invokeIdentityArn, equals("arn:aws:iam::EXAMPLE")); - expect(event.records[0].kinesis.partitionKey, equals("partitionKey-03")); - expect(event.records[0].kinesis.data, - equals("SGVsbG8sIHRoaXMgaXMgYSB0ZXN0IDEyMy4=")); - expect(event.records[0].kinesis.sequenceNumber, - equals("49545115243490985018280067714973144582180062593244200961")); + event.records![0].invokeIdentityArn, equals('arn:aws:iam::EXAMPLE')); + expect( + event.records![0].kinesis!.partitionKey, equals('partitionKey-03')); + expect(event.records![0].kinesis!.data, + equals('SGVsbG8sIHRoaXMgaXMgYSB0ZXN0IDEyMy4=')); + expect(event.records![0].kinesis!.sequenceNumber, + equals('49545115243490985018280067714973144582180062593244200961')); }); }); } diff --git a/test/runtime_test.dart b/test/runtime_test.dart index ecc614ae..e8edd5a6 100644 --- a/test/runtime_test.dart +++ b/test/runtime_test.dart @@ -1,44 +1,43 @@ -import "package:test/test.dart"; +import 'package:test/test.dart'; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; void main() { group('runtime', () { - test("instance is created without error", () { + test('instance is created without error', () { expect(() => Runtime(), returnsNormally); }); - test("instance is same accross invocation", () async { - final runtime = await Runtime(); + test('instance is same across invocation', () async { + final runtime = Runtime(); - expect(runtime, await Runtime()); + expect(runtime, Runtime()); }); - test("successfully add a handler to runtime", () async { - final runtime = await Runtime(); + test('successfully add a handler to runtime', () async { + final runtime = Runtime(); - final Handler testHandler = (context, event) async { - return new InvocationResult(context.requestId, "HELLO WORLD"); + final Handler testHandler = (context, event) async { + return true; }; - final addHandler = runtime.registerHandler("test.handler", testHandler); + final addHandler = runtime.registerHandler('test.handler', testHandler); - expect(runtime.handlerExists("test.handler"), equals(true)); + expect(runtime.handlerExists('test.handler'), equals(true)); expect(addHandler, equals(testHandler)); }); - test("successfully deregister a handler to runtime", () async { - final runtime = await Runtime(); + test('successfully deregister a handler to runtime', () async { + final runtime = Runtime(); - final Handler testHandler = (context, event) async { - return new InvocationResult(context.requestId, "HELLO WORLD"); + final testHandler = (context, event) async { + return true; }; - runtime.registerHandler("test.handler", testHandler); - final removedHandler = - runtime.deregisterHandler("test.handler"); + runtime.registerHandler('test.handler', testHandler); + final removedHandler = runtime.deregisterHandler('test.handler'); - expect(runtime.handlerExists("test.handler"), equals(false)); + expect(runtime.handlerExists('test.handler'), equals(false)); expect(removedHandler, equals(testHandler)); }); }); diff --git a/test/s3_event.dart b/test/s3_event.dart index 3f5a3d41..b02c59d4 100644 --- a/test/s3_event.dart +++ b/test/s3_event.dart @@ -2,29 +2,29 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/s3_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("s3_default", () { - test("json got parsed and creates an event", () async { - final event = AwsS3Event.fromJson(json); + group('s3_default', () { + test('json got parsed and creates an event', () async { + final event = AwsS3Event.fromJson(json!); - expect(event.records[0].eventVersion, equals("2.0")); - expect(event.records[0].eventSource, equals("aws:s3")); - expect(event.records[0].awsRegion, equals("eu-west-1")); - expect(event.records[0].eventTime, - equals(DateTime.parse("1970-01-01T00:00:00.000Z"))); - expect(event.records[0].eventName, equals("ObjectCreated:Put")); - expect(event.records[0].userIdentity.principalId, equals("EXAMPLE")); - expect(event.records[0].requestParameters["sourceIPAddress"], - equals("127.0.0.1")); - expect(event.records[0].s3.s3SchemaVersion, equals("1.0")); - expect(event.records[0].s3.configurationId, equals("testConfigRule")); + expect(event.records![0].eventVersion, equals('2.0')); + expect(event.records![0].eventSource, equals('aws:s3')); + expect(event.records![0].awsRegion, equals('eu-west-1')); + expect(event.records![0].eventTime, + equals(DateTime.parse('1970-01-01T00:00:00.000Z'))); + expect(event.records![0].eventName, equals('ObjectCreated:Put')); + expect(event.records![0].userIdentity!.principalId, equals('EXAMPLE')); + expect(event.records![0].requestParameters!['sourceIPAddress'], + equals('127.0.0.1')); + expect(event.records![0].s3!.s3SchemaVersion, equals('1.0')); + expect(event.records![0].s3!.configurationId, equals('testConfigRule')); }); }); } diff --git a/test/sqs_event_test.dart b/test/sqs_event_test.dart index 64f5f088..7782b96a 100644 --- a/test/sqs_event_test.dart +++ b/test/sqs_event_test.dart @@ -2,29 +2,29 @@ import 'dart:convert'; import 'dart:io' show File; import 'package:aws_lambda_dart_runtime/aws_lambda_dart_runtime.dart'; -import "package:test/test.dart"; +import 'package:test/test.dart'; final file = 'data/sqs_event.json'; -final String contents = new File(file).readAsStringSync(); -final Map json = jsonDecode(contents); +final String contents = File(file).readAsStringSync(); +final json = jsonDecode(contents) as Map?; void main() { - group("sqs_default", () { - test("json got parsed and creates an event", () async { - final event = AwsSQSEvent.fromJson(json); + group('sqs_default', () { + test('json got parsed and creates an event', () async { + final event = AwsSQSEvent.fromJson(json!); - expect(event.records.length, equals(1)); - expect(event.records[0].md5OfBody, - equals("7b270e59b47ff90a553787216d55d91d")); - expect(event.records[0].eventSource, equals("aws:sqs")); - expect(event.records[0].eventSourceARN, - equals("arn:aws:sqs:eu-west-1:123456789012:MyQueue")); - expect(event.records[0].awsRegion, equals("eu-west-1")); - expect(event.records[0].body, equals("Hello from SQS!")); - expect(event.records[0].messageId, - equals("19dd0b57-b21e-4ac1-bd88-01bbb068cb78")); - expect(event.records[0].receiptHandle, equals("MessageReceiptHandle")); + expect(event.records!.length, equals(1)); + expect(event.records![0].md5OfBody, + equals('7b270e59b47ff90a553787216d55d91d')); + expect(event.records![0].eventSource, equals('aws:sqs')); + expect(event.records![0].eventSourceARN, + equals('arn:aws:sqs:eu-west-1:123456789012:MyQueue')); + expect(event.records![0].awsRegion, equals('eu-west-1')); + expect(event.records![0].body, equals('Hello from SQS!')); + expect(event.records![0].messageId, + equals('19dd0b57-b21e-4ac1-bd88-01bbb068cb78')); + expect(event.records![0].receiptHandle, equals('MessageReceiptHandle')); }); }); } diff --git a/test/testing.dart b/test/testing.dart deleted file mode 100644 index 0b27728f..00000000 --- a/test/testing.dart +++ /dev/null @@ -1,3 +0,0 @@ -library testing; - -export 'common.dart';