|
| 1 | +import middy from '@middy/core'; |
| 2 | +import { describe, expect, it } from 'vitest'; |
| 3 | +import { SchemaValidationError } from '../../src/errors.js'; |
| 4 | +import { validation } from '../../src/middleware.js'; |
| 5 | + |
| 6 | +const inboundSchema = { |
| 7 | + type: 'object', |
| 8 | + properties: { |
| 9 | + inputValue: { type: 'number' }, |
| 10 | + }, |
| 11 | + required: ['inputValue'], |
| 12 | + additionalProperties: false, |
| 13 | +}; |
| 14 | + |
| 15 | +const outboundSchema = { |
| 16 | + type: 'object', |
| 17 | + properties: { |
| 18 | + outputValue: { type: 'number' }, |
| 19 | + }, |
| 20 | + required: ['outputValue'], |
| 21 | + additionalProperties: false, |
| 22 | +}; |
| 23 | + |
| 24 | +const response = { outputValue: 20 }; |
| 25 | +const baseHandler = async (event: unknown) => { |
| 26 | + return response; |
| 27 | +}; |
| 28 | + |
| 29 | +describe('validation middleware with Middy', () => { |
| 30 | + it('should validate inbound and outbound successfully', async () => { |
| 31 | + // Prepare |
| 32 | + const middleware = validation({ inboundSchema, outboundSchema }); |
| 33 | + const wrappedHandler = middy(baseHandler).use(middleware); |
| 34 | + const event = { inputValue: 10 }; |
| 35 | + // Act |
| 36 | + const result = await wrappedHandler(event); |
| 37 | + // Assess |
| 38 | + expect(result).toEqual(response); |
| 39 | + }); |
| 40 | + |
| 41 | + it('should throw error on inbound validation failure', async () => { |
| 42 | + // Prepare |
| 43 | + const middleware = validation({ inboundSchema }); |
| 44 | + const wrappedHandler = middy(baseHandler).use(middleware); |
| 45 | + const invalidEvent = { inputValue: 'invalid' }; |
| 46 | + // Act & Assess |
| 47 | + await expect(wrappedHandler(invalidEvent)).rejects.toThrow( |
| 48 | + SchemaValidationError |
| 49 | + ); |
| 50 | + }); |
| 51 | + |
| 52 | + it('should throw error on outbound validation failure', async () => { |
| 53 | + const invalidHandler = async (_event: unknown) => { |
| 54 | + return { outputValue: 'invalid' }; |
| 55 | + }; |
| 56 | + const middleware = validation({ outboundSchema }); |
| 57 | + const wrappedHandler = middy(invalidHandler).use(middleware); |
| 58 | + const event = { any: 'value' }; |
| 59 | + // Act & Assess |
| 60 | + await expect(wrappedHandler(event)).rejects.toThrow(SchemaValidationError); |
| 61 | + }); |
| 62 | + |
| 63 | + it('should no-op when no schemas are provided', async () => { |
| 64 | + // Prepare |
| 65 | + const middleware = validation({}); |
| 66 | + const wrappedHandler = middy(baseHandler).use(middleware); |
| 67 | + const event = { anyKey: 'anyValue' }; |
| 68 | + // Act |
| 69 | + const result = await wrappedHandler(event); |
| 70 | + // Assess |
| 71 | + expect(result).toEqual(response); |
| 72 | + }); |
| 73 | +}); |
0 commit comments