-
Notifications
You must be signed in to change notification settings - Fork 146
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
feat(parser): implement middy parser middleware #1823
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,56 @@ | ||||||
import { MiddyLikeRequest } from '@aws-lambda-powertools/commons/types'; | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. All these imports could be converted to |
||||||
import { MiddlewareObj } from '@middy/core'; | ||||||
import { ZodSchema } from 'zod'; | ||||||
import { Envelope } from '../types/envelope.js'; | ||||||
|
||||||
interface ParserOptions<S extends ZodSchema> { | ||||||
schema: S; | ||||||
envelope?: Envelope; | ||||||
} | ||||||
|
||||||
/** | ||||||
* A middiy middleware to parse your event. | ||||||
* | ||||||
* @exmaple | ||||||
* ```typescirpt | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
* import { parser } from '@aws-lambda-powertools/parser/middleware'; | ||||||
* import middy from '@middy/core'; | ||||||
* import { sqsEnvelope } from '@aws-lambda-powertools/parser/envelopes/sqs;' | ||||||
* | ||||||
* const oderSchema = z.object({ | ||||||
* id: z.number(), | ||||||
* description: z.string(), | ||||||
* quantity: z.number(), | ||||||
* }); | ||||||
* | ||||||
* type Order = z.infer<typeof oderSchema>; | ||||||
* | ||||||
* export const handler = middy( | ||||||
* async (event: Order, _context: unknown): Promise<void> => { | ||||||
* // event is validated as sqs message envelope | ||||||
* // the body is unwrapped and parsed into object ready to use | ||||||
* // you can now use event as Order in your code | ||||||
* } | ||||||
* ).use(parser({ schema: oderSchema, envelope: sqsEnvelope })); | ||||||
* ``` | ||||||
* | ||||||
* @param options | ||||||
*/ | ||||||
const parser = <S extends ZodSchema>( | ||||||
options: ParserOptions<S> | ||||||
): MiddlewareObj => { | ||||||
const before = (request: MiddyLikeRequest): void => { | ||||||
const { schema, envelope } = options; | ||||||
if (envelope) { | ||||||
request.event = envelope(request.event, schema); | ||||||
} else { | ||||||
request.event = schema.parse(request.event); | ||||||
} | ||||||
}; | ||||||
|
||||||
return { | ||||||
before, | ||||||
}; | ||||||
}; | ||||||
|
||||||
export { parser }; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { apiGatewayEnvelope } from '../envelopes/apigw.js'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think these imports can also be converted to |
||
import { apiGatewayV2Envelope } from '../envelopes/apigwv2.js'; | ||
import { cloudWatchEnvelope } from '../envelopes/cloudwatch.js'; | ||
import { dynamoDDStreamEnvelope } from '../envelopes/dynamodb.js'; | ||
import { kafkaEnvelope } from '../envelopes/kafka.js'; | ||
import { kinesisEnvelope } from '../envelopes/kinesis.js'; | ||
import { kinesisFirehoseEnvelope } from '../envelopes/kinesis-firehose.js'; | ||
import { lambdaFunctionUrlEnvelope } from '../envelopes/lambda.js'; | ||
import { snsEnvelope } from '../envelopes/sns.js'; | ||
import { snsSqsEnvelope } from '../envelopes/sns.js'; | ||
import { sqsEnvelope } from '../envelopes/sqs.js'; | ||
import { vpcLatticeEnvelope } from '../envelopes/vpc-lattice.js'; | ||
import { vpcLatticeV2Envelope } from '../envelopes/vpc-latticev2.js'; | ||
import { eventBridgeEnvelope } from '../envelopes/event-bridge.js'; | ||
|
||
export type Envelope = | ||
| typeof apiGatewayEnvelope | ||
| typeof apiGatewayV2Envelope | ||
| typeof cloudWatchEnvelope | ||
| typeof dynamoDDStreamEnvelope | ||
| typeof eventBridgeEnvelope | ||
| typeof kafkaEnvelope | ||
| typeof kinesisEnvelope | ||
| typeof kinesisFirehoseEnvelope | ||
| typeof lambdaFunctionUrlEnvelope | ||
| typeof snsEnvelope | ||
| typeof snsSqsEnvelope | ||
| typeof sqsEnvelope | ||
| typeof vpcLatticeEnvelope | ||
| typeof vpcLatticeV2Envelope; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
/** | ||
* Test middelware parser | ||
* | ||
* @group unit/parser | ||
*/ | ||
|
||
import middy from '@middy/core'; | ||
import { Context } from 'aws-lambda'; | ||
import { parser } from '../../src/middleware/parser.js'; | ||
import { generateMock } from '@anatine/zod-mock'; | ||
import { SqsSchema } from '../../src/schemas/sqs.js'; | ||
import { z, ZodSchema } from 'zod'; | ||
import { sqsEnvelope } from '../../src/envelopes/sqs'; | ||
import { TestSchema } from './schema/utils'; | ||
|
||
describe('Middleware: parser', () => { | ||
const schema = z.object({ | ||
name: z.string(), | ||
age: z.number().min(18).max(99), | ||
}); | ||
type schema = z.infer<typeof schema>; | ||
const handler = async ( | ||
event: schema | unknown, | ||
_context: Context | ||
): Promise<schema | unknown> => { | ||
return event; | ||
}; | ||
|
||
describe(' when envelope is provided ', () => { | ||
const middyfiedHandler = middy(handler).use( | ||
parser({ schema: TestSchema, envelope: sqsEnvelope }) | ||
); | ||
|
||
it('should parse request body with schema and envelope', async () => { | ||
const bodyMock = generateMock(TestSchema); | ||
parser({ schema: schema, envelope: sqsEnvelope }); | ||
|
||
const event = generateMock(SqsSchema, { | ||
stringMap: { | ||
body: () => JSON.stringify(bodyMock), | ||
}, | ||
}); | ||
|
||
const result = (await middyfiedHandler(event, {} as Context)) as schema[]; | ||
result.forEach((item) => { | ||
expect(item).toEqual(bodyMock); | ||
}); | ||
}); | ||
|
||
it('should throw when envelope does not match', async () => { | ||
await expect(async () => { | ||
await middyfiedHandler({ name: 'John', age: 18 }, {} as Context); | ||
}).rejects.toThrowError(); | ||
}); | ||
|
||
it('should throw when schema does not match', async () => { | ||
const event = generateMock(SqsSchema, { | ||
stringMap: { | ||
body: () => '42', | ||
}, | ||
}); | ||
|
||
await expect(middyfiedHandler(event, {} as Context)).rejects.toThrow(); | ||
}); | ||
it('should throw when provided schema is invalid', async () => { | ||
const middyfiedHandler = middy(handler).use( | ||
parser({ schema: {} as ZodSchema, envelope: sqsEnvelope }) | ||
); | ||
|
||
await expect(middyfiedHandler(42, {} as Context)).rejects.toThrowError(); | ||
}); | ||
it('should throw when envelope is correct but schema is invalid', async () => { | ||
const event = generateMock(SqsSchema, { | ||
stringMap: { | ||
body: () => JSON.stringify({ name: 'John', foo: 'bar' }), | ||
}, | ||
}); | ||
|
||
const middyfiedHandler = middy(handler).use( | ||
parser({ schema: {} as ZodSchema, envelope: sqsEnvelope }) | ||
); | ||
|
||
await expect( | ||
middyfiedHandler(event, {} as Context) | ||
).rejects.toThrowError(); | ||
}); | ||
}); | ||
|
||
describe(' when envelope is not provided', () => { | ||
it('should parse the event with built-in schema', async () => { | ||
const event = generateMock(SqsSchema); | ||
|
||
const middyfiedHandler = middy(handler).use( | ||
parser({ schema: SqsSchema }) | ||
); | ||
|
||
expect(await middyfiedHandler(event, {} as Context)).toEqual(event); | ||
}); | ||
|
||
it('should parse custom event', async () => { | ||
const event = { name: 'John', age: 18 }; | ||
const middyfiedHandler = middy(handler).use( | ||
parser({ schema: TestSchema }) | ||
); | ||
|
||
expect(await middyfiedHandler(event, {} as Context)).toEqual(event); | ||
}); | ||
|
||
it('should throw when the schema does not match', async () => { | ||
const middyfiedHandler = middy(handler).use( | ||
parser({ schema: TestSchema }) | ||
); | ||
|
||
await expect(middyfiedHandler(42, {} as Context)).rejects.toThrow(); | ||
}); | ||
|
||
it('should throw when provided schema is invalid', async () => { | ||
const middyfiedHandler = middy(handler).use( | ||
parser({ schema: {} as ZodSchema }) | ||
); | ||
|
||
await expect( | ||
middyfiedHandler({ foo: 'bar' }, {} as Context) | ||
).rejects.toThrowError(); | ||
}); | ||
}); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Mostly for future reference, since we already merged these files in the previous PR, but the
zod
import could be changed toimport { z, type ZodSchema } from 'zod';
.