Skip to content

refactor(all): add middy-like types to commons #1225

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/commons/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export * from './utils/lambda';
export * from './Utility';
export * from './config';
export * as ContextExamples from './samples/resources/contexts';
export * as Events from './samples/resources/events';
export * as Events from './samples/resources/events';
export * from './types/middy';
33 changes: 33 additions & 0 deletions packages/commons/src/types/middy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Context } from 'aws-lambda';

/**
* We need to define these types and interfaces here because we can't import them from @middy/core.
* Importing them from @middy/core would introduce a dependency on @middy/core, which we don't want
* because we want to keep it as an optional dependency. Those users who don't use the Powertools middleware
* and use `tsc` to compile their code will get an error if we import from @middy/core, see #1068.
* Given that we use a subset of the @middy/core types, we can define them here and avoid the dependency.
*/
type Request<TEvent = unknown, TResult = unknown, TErr = Error, TContext extends Context = Context> = {
event: TEvent
context: TContext
response: TResult | null
error: TErr | null
internal: {
[key: string]: unknown
}
};

declare type MiddlewareFn<TEvent = unknown, TResult = unknown, TErr = Error, TContext extends Context = Context> = (request: Request<TEvent, TResult, TErr, TContext>) => unknown;

export type MiddlewareLikeObj<TEvent = unknown, TResult = unknown, TErr = Error, TContext extends Context = Context> = {
before?: MiddlewareFn<TEvent, TResult, TErr, TContext>
after?: MiddlewareFn<TEvent, TResult, TErr, TContext>
onError?: MiddlewareFn<TEvent, TResult, TErr, TContext>
};

export type MiddyLikeRequest = {
event: unknown
context: Context
response: unknown | null
error: Error | null
};
9 changes: 6 additions & 3 deletions packages/logger/src/middleware/middy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Logger } from '../Logger';
import type middy from '@middy/core';
import { HandlerOptions, LogAttributes } from '../types';
import type {
MiddlewareLikeObj,
MiddyLikeRequest
} from '@aws-lambda-powertools/commons';

/**
* A middy middleware that helps emitting CloudWatch EMF metrics in your logs.
Expand All @@ -26,12 +29,12 @@ import { HandlerOptions, LogAttributes } from '../types';
* @param options - (_optional_) Options for the middleware
* @returns - The middy middleware object
*/
const injectLambdaContext = (target: Logger | Logger[], options?: HandlerOptions): middy.MiddlewareObj => {
const injectLambdaContext = (target: Logger | Logger[], options?: HandlerOptions): MiddlewareLikeObj => {

const loggers = target instanceof Array ? target : [target];
const persistentAttributes: LogAttributes[] = [];

const injectLambdaContextBefore = async (request: middy.Request): Promise<void> => {
const injectLambdaContextBefore = async (request: MiddyLikeRequest): Promise<void> => {
loggers.forEach((logger: Logger) => {
if (options && options.clearState === true) {
persistentAttributes.push({ ...logger.getPersistentLogAttributes() });
Expand Down
9 changes: 6 additions & 3 deletions packages/metrics/src/middleware/middy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { Metrics } from '../Metrics';
import type middy from '@middy/core';
import type { ExtraOptions } from '../types';
import type {
MiddlewareLikeObj,
MiddyLikeRequest
} from '@aws-lambda-powertools/commons';

/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
Expand Down Expand Up @@ -29,10 +32,10 @@ import type { ExtraOptions } from '../types';
* @param options - (_optional_) Options for the middleware
* @returns middleware - The middy middleware object
*/
const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): middy.MiddlewareObj => {
const logMetrics = (target: Metrics | Metrics[], options: ExtraOptions = {}): MiddlewareLikeObj => {
const metricsInstances = target instanceof Array ? target : [target];

const logMetricsBefore = async (request: middy.Request): Promise<void> => {
const logMetricsBefore = async (request: MiddyLikeRequest): Promise<void> => {
metricsInstances.forEach((metrics: Metrics) => {
metrics.setFunctionName(request.context.functionName);
const { throwOnEmptyMetrics, defaultDimensions, captureColdStartMetric } = options;
Expand Down
11 changes: 7 additions & 4 deletions packages/tracer/src/middleware/middy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import type middy from '@middy/core';
import type { Tracer } from '../Tracer';
import type { Segment, Subsegment } from 'aws-xray-sdk-core';
import type { CaptureLambdaHandlerOptions } from '../types';
import type {
MiddlewareLikeObj,
MiddyLikeRequest
} from '@aws-lambda-powertools/commons';

/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
Expand Down Expand Up @@ -30,7 +33,7 @@ import type { CaptureLambdaHandlerOptions } from '../types';
* @param options - (_optional_) Options for the middleware
* @returns middleware - The middy middleware object
*/
const captureLambdaHandler = (target: Tracer, options?: CaptureLambdaHandlerOptions): middy.MiddlewareObj => {
const captureLambdaHandler = (target: Tracer, options?: CaptureLambdaHandlerOptions): MiddlewareLikeObj => {
let lambdaSegment: Subsegment | Segment;

const open = (): void => {
Expand All @@ -53,7 +56,7 @@ const captureLambdaHandler = (target: Tracer, options?: CaptureLambdaHandlerOpti
}
};

const captureLambdaHandlerAfter = async (request: middy.Request): Promise<void> => {
const captureLambdaHandlerAfter = async (request: MiddyLikeRequest): Promise<void> => {
if (target.isTracingEnabled()) {
if (options?.captureResponse ?? true) {
target.addResponseAsMetadata(request.response, process.env._HANDLER);
Expand All @@ -62,7 +65,7 @@ const captureLambdaHandler = (target: Tracer, options?: CaptureLambdaHandlerOpti
}
};

const captureLambdaHandlerError = async (request: middy.Request): Promise<void> => {
const captureLambdaHandlerError = async (request: MiddyLikeRequest): Promise<void> => {
if (target.isTracingEnabled()) {
target.addErrorAsMetadata(request.error as Error);
close();
Expand Down