├── .eslintrc.js ├── .gitignore ├── .npmignore ├── .npmrc ├── .nvmrc ├── .prettierrc ├── README.md ├── event-scout.excalidraw.png ├── lib ├── cdk │ ├── HttpInterceptor.ts │ ├── HttpInterceptorExtension.ts │ ├── applyHttpInterceptor.ts │ └── applyNodejsInternalExtension.ts ├── constants.ts ├── dynamoDbToolboxUtils │ ├── ddbtConstants.ts │ ├── getDefaultTtl.ts │ └── index.ts ├── index.ts ├── layer │ └── interceptor.ts └── sdk │ ├── client.ts │ ├── getEnv.ts │ ├── getFirstMatchingConfig.ts │ ├── index.ts │ ├── requestMatchConfig.test.ts │ ├── requestMatchConfig.ts │ ├── tables │ ├── entities │ │ ├── index.ts │ │ ├── lambdaHttpInterceptorConfigEntity │ │ │ ├── entity.ts │ │ │ ├── fetchLambdaHttpInterceptorConfig.ts │ │ │ ├── index.ts │ │ │ └── putLambdaHttpInterceptorConfig.ts │ │ └── lambdaHttpInterceptorInterceptedCallEntity │ │ │ ├── cleanInterceptedCalls.ts │ │ │ ├── entity.ts │ │ │ ├── fetchInterceptedCalls.ts │ │ │ ├── index.ts │ │ │ ├── putInterceptedCall.ts │ │ │ └── waitForNumberOfInterceptedCalls.ts │ ├── index.ts │ └── lambdaHttpInterceptorTable.ts │ └── types.ts ├── package.json ├── pnpm-lock.yaml ├── setupIntegration.ts ├── test ├── cdk.json ├── handler.integration-test.ts ├── handler.ts ├── index.ts ├── stack.ts └── testEnvVars.ts ├── tsconfig.build.json ├── tsconfig.json ├── vitest.config.ts └── vitest.integration.config.ts /.eslintrc.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-lines */ 2 | module.exports = { 3 | extends: ['eslint:recommended', 'plugin:import/recommended'], 4 | ignorePatterns: [ 5 | '**/node_modules/', 6 | '**/nx-cache/', 7 | '**/dist/', 8 | '**/cdk.out/', 9 | '**/coverage/', 10 | '**/build/', 11 | '**/public/', 12 | ], 13 | rules: { 14 | 'import/extensions': 0, 15 | 'import/no-unresolved': 0, 16 | 'import/prefer-default-export': 0, 17 | 'import/no-duplicates': 'error', 18 | complexity: ['error', 8], 19 | 'max-lines': ['error', 200], 20 | 'max-depth': ['error', 3], 21 | 'max-params': ['error', 4], 22 | eqeqeq: ['error', 'smart'], 23 | 'import/no-extraneous-dependencies': [ 24 | 'error', 25 | { 26 | devDependencies: true, 27 | optionalDependencies: false, 28 | peerDependencies: false, 29 | }, 30 | ], 31 | 'no-shadow': [ 32 | 'error', 33 | { 34 | hoist: 'all', 35 | }, 36 | ], 37 | 'prefer-const': 'error', 38 | 'import/order': [ 39 | 'error', 40 | { 41 | pathGroups: [{ pattern: '@swarmion-full-stack/**', group: 'unknown' }], 42 | groups: [ 43 | ['external', 'builtin'], 44 | 'unknown', 45 | 'internal', 46 | ['parent', 'sibling', 'index'], 47 | ], 48 | alphabetize: { 49 | order: 'asc', 50 | caseInsensitive: false, 51 | }, 52 | 'newlines-between': 'always', 53 | pathGroupsExcludedImportTypes: ['builtin'], 54 | }, 55 | ], 56 | 'sort-imports': [ 57 | 'error', 58 | { 59 | ignoreCase: true, 60 | ignoreDeclarationSort: true, 61 | ignoreMemberSort: false, 62 | memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'], 63 | }, 64 | ], 65 | 'padding-line-between-statements': [ 66 | 'error', 67 | { 68 | blankLine: 'always', 69 | prev: '*', 70 | next: 'return', 71 | }, 72 | ], 73 | 'prefer-arrow/prefer-arrow-functions': [ 74 | 'error', 75 | { 76 | disallowPrototype: true, 77 | singleReturnOnly: false, 78 | classPropertiesAllowed: false, 79 | }, 80 | ], 81 | 'no-restricted-imports': [ 82 | 'error', 83 | { 84 | patterns: [ 85 | { 86 | group: ['@swarmion-full-stack/*/*'], 87 | message: 88 | 'import of internal modules must be done at the root level.', 89 | }, 90 | ], 91 | paths: [ 92 | { 93 | name: 'lodash', 94 | message: 'Please use lodash/{module} import instead', 95 | }, 96 | { 97 | name: 'aws-sdk', 98 | message: 'Please use aws-sdk/{module} import instead', 99 | }, 100 | { 101 | name: '.', 102 | message: 'Please use explicit import file', 103 | }, 104 | ], 105 | }, 106 | ], 107 | curly: ['error', 'all'], 108 | }, 109 | root: true, 110 | env: { 111 | es6: true, 112 | node: true, 113 | jest: true, 114 | browser: true, 115 | }, 116 | plugins: ['prefer-arrow', 'import'], 117 | parserOptions: { 118 | ecmaVersion: 9, 119 | sourceType: 'module', 120 | }, 121 | overrides: [ 122 | { 123 | files: ['**/*.ts?(x)'], 124 | extends: [ 125 | 'plugin:@typescript-eslint/recommended', 126 | 'plugin:@typescript-eslint/recommended-requiring-type-checking', 127 | ], 128 | parser: '@typescript-eslint/parser', 129 | parserOptions: { 130 | project: 'tsconfig.json', 131 | }, 132 | rules: { 133 | '@typescript-eslint/prefer-optional-chain': 'error', 134 | 'no-shadow': 'off', 135 | '@typescript-eslint/no-shadow': 'error', 136 | '@typescript-eslint/prefer-nullish-coalescing': 'error', 137 | '@typescript-eslint/strict-boolean-expressions': [ 138 | 'error', 139 | { 140 | allowString: false, 141 | allowNumber: false, 142 | allowNullableObject: true, 143 | }, 144 | ], 145 | '@typescript-eslint/ban-ts-comment': [ 146 | 'error', 147 | { 148 | 'ts-ignore': 'allow-with-description', 149 | minimumDescriptionLength: 10, 150 | }, 151 | ], 152 | '@typescript-eslint/explicit-function-return-type': 0, 153 | '@typescript-eslint/explicit-member-accessibility': 0, 154 | '@typescript-eslint/camelcase': 0, 155 | '@typescript-eslint/interface-name-prefix': 0, 156 | '@typescript-eslint/explicit-module-boundary-types': 'error', 157 | '@typescript-eslint/no-explicit-any': 'error', 158 | '@typescript-eslint/no-unused-vars': 'error', 159 | '@typescript-eslint/ban-types': [ 160 | 'error', 161 | { 162 | types: { 163 | FC: 'Use `const MyComponent = (props: Props): JSX.Element` instead', 164 | SFC: 'Use `const MyComponent = (props: Props): JSX.Element` instead', 165 | FunctionComponent: 166 | 'Use `const MyComponent = (props: Props): JSX.Element` instead', 167 | 'React.FC': 168 | 'Use `const MyComponent = (props: Props): JSX.Element` instead', 169 | 'React.SFC': 170 | 'Use `const MyComponent = (props: Props): JSX.Element` instead', 171 | 'React.FunctionComponent': 172 | 'Use `const MyComponent = (props: Props): JSX.Element` instead', 173 | }, 174 | extendDefaults: true, 175 | }, 176 | ], 177 | '@typescript-eslint/no-unnecessary-boolean-literal-compare': 'error', 178 | '@typescript-eslint/no-unnecessary-condition': 'error', 179 | '@typescript-eslint/no-unnecessary-type-arguments': 'error', 180 | '@typescript-eslint/prefer-string-starts-ends-with': 'error', 181 | '@typescript-eslint/switch-exhaustiveness-check': 'error', 182 | '@typescript-eslint/restrict-template-expressions': [ 183 | 'error', 184 | { 185 | allowNumber: true, 186 | allowBoolean: true, 187 | }, 188 | ], 189 | }, 190 | }, 191 | { 192 | files: ['**/src/**'], 193 | excludedFiles: ['**/__tests__/**', '**/*.test.ts?(x)', '**/testUtils/**'], 194 | 195 | rules: { 196 | 'import/no-extraneous-dependencies': [ 197 | 'error', 198 | { 199 | devDependencies: false, 200 | optionalDependencies: false, 201 | peerDependencies: true, 202 | }, 203 | ], 204 | }, 205 | }, 206 | ], 207 | }; 208 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | 3 | # CDK asset staging directory 4 | .cdk.staging 5 | cdk.out 6 | 7 | # Compiled sources 8 | dist 9 | 10 | testEnvVarsCache.json 11 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | *.ts 2 | !*.d.ts 3 | 4 | # CDK asset staging directory 5 | .cdk.staging 6 | cdk.out 7 | test 8 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | auto-install-peers=true 2 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 18.16.0 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all", 4 | "arrowParens": "avoid" 5 | } 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HTTP Lambda Interceptor 2 | 3 | This library enables you intercept and mock HTTP call made by an AWS Lambda. It's useful for integration testing. 4 | 5 | Performing integration tests on deployed resources allows testing applications in the best prod alike environment. Thanks to the interceptor, lambda can be tested without interacting with costly external endpoints or non preprod external endpoints for example. 6 | 7 | ## Getting started 8 | 9 | This library is made of a CDK Construct to instantiate in your stack and a sdk to tool the integration tests. 10 | 11 | The HttpInterceptor construct needs to be instantiated in the stack, or inside another Construct. 12 | 13 | ```ts 14 | import { Stack, StackProps } from "aws-cdk-lib"; 15 | 16 | import { Construct } from "constructs"; 17 | import { HttpInterceptor, applyHttpInterceptor } from "http-lambda-interceptor"; 18 | import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs"; 19 | import { Runtime } from "aws-cdk-lib/aws-lambda"; 20 | 21 | export class MyStack extends Stack { 22 | constructor(scope: Construct, id: string, props?: StackProps) { 23 | super(scope, id, props); 24 | 25 | const interceptor = new HttpInterceptor(this, "HttpInterceptor"); 26 | 27 | const myLambdaFunctionThatMakesExternalCalls = new NodejsFunction( 28 | this, 29 | "MakeExternalCalls", 30 | { 31 | runtime: Runtime.NODEJS_18_X, 32 | handler: "index.handler", 33 | entry: './handler.ts', 34 | }, 35 | ); 36 | 37 | applyHttpInterceptor(myLambdaFunctionThatDoesExternalCalls, interceptor); 38 | } 39 | } 40 | ``` 41 | 42 | After deploying that part, everything is setup on the stack to perform integration tests. 43 | 44 | ```typescript 45 | import fetch from "node-fetch"; 46 | import { expect, describe, it } from "vitest"; 47 | 48 | process.env.HTTP_INTERCEPTOR_TABLE_NAME = '' 49 | 50 | import { setupLambdaHttpInterceptorConfig } from "http-lambda-interceptor"; 51 | 52 | import { triggerMyLambdaFunctionThatMakesExternalCalls } from './utils'; 53 | 54 | describe("hello function", () => { 55 | it("returns a 200", async () => { 56 | await setupLambdaHttpInterceptorConfig({ 57 | lambdaName: '', 58 | mockConfigs: [ 59 | { 60 | url: "https://api-1/*", 61 | response: { 62 | status: 404, 63 | body: JSON.stringify({ 64 | errorMessage: "Not found", 65 | }), 66 | }, 67 | }, 68 | { 69 | url: "https://api-2/path", 70 | response: { 71 | passThrough: true, 72 | }, 73 | }, 74 | ], 75 | }); 76 | const response = await triggerMyLambdaFunctionThatMakesExternalCalls(); 77 | expect(response.status).toBe(200); 78 | }); 79 | }); 80 | ``` 81 | 82 | >To resolve `` and `` easily, we recommend the usage of [@swarmion/integration-tests](https://www.swarmion.dev/docs/how-to-guides/use-integration-tests/) 83 | 84 | ## How it works 85 | 86 | ### The CDK Construct 87 | 88 | The `HttpInterceptor` needs to be instantiated inside a stack. It contains what is necessary to mock calls: 89 | - a DynamoDB table to store and fetch all calls to intercept and what to respond 90 | - an extension to intercept these calls 91 | - an aspect that applies this extension to every NodeJSFunction included in the stack 92 | 93 | Then the method `applyHttpInterceptor` needs to be used to link any Lambda to the extension that has been set. 94 | This method can be called with any construct and it will attach the extension to every NodejsFunction Construct nested inside it. Therefore, it can also be called with `this` in the constructor of the stack like the following. 95 | 96 | ```ts 97 | import { Stack, StackProps } from "aws-cdk-lib"; 98 | 99 | import { Construct } from "constructs"; 100 | import { HttpInterceptor, applyHttpInterceptor } from "http-lambda-interceptor"; 101 | import { NodejsFunction } from "aws-cdk-lib/aws-lambda-nodejs"; 102 | import { Runtime } from "aws-cdk-lib/aws-lambda"; 103 | 104 | export class MyStack extends Stack { 105 | constructor(scope: Construct, id: string, props?: StackProps) { 106 | super(scope, id, props); 107 | 108 | const interceptor = new HttpInterceptor(this, "HttpInterceptor"); 109 | 110 | const myLambdaFunctionThatMakesExternalCalls = new NodejsFunction( 111 | this, 112 | "MakeExternalCalls", 113 | { 114 | runtime: Runtime.NODEJS_18_X, 115 | handler: "index.handler", 116 | entry: './handler.ts', 117 | }, 118 | ); 119 | 120 | applyHttpInterceptor(this, interceptor); 121 | } 122 | } 123 | ``` 124 | 125 | The construct exposes the name of the DynamoDB table that is used to perform under the hood the configuration of all mocks. 126 | This variable needs to be instantiated to the test environment in which the integration tests are performed. 127 | 128 | You can also specify the name of this table yourself in the configuration of the HttpInterceptor construct. 129 | 130 | The other part of the library sits in the sdk used to perform the mocking part. Because with only this part, lambda work the same way they did before attaching the extension to it. 131 | 132 | ### The SDK to use in integration tests 133 | 134 | The SDK part is the tooling used to configure the calls that need to be intercepted. 135 | 136 | The extension also uses the SDK for fetching the configuration that are set in the tests. 137 | 138 | #### How to setup the calls configuration 139 | 140 | A method named `setupLambdaHttpInterceptorConfig` is used to set up the configuration that will be used by the lambda to handle the interception of the calls. 141 | 142 | The only requirement for the lambda calls to be intercepted is that this setup needs to be done synchronously before the call of the lambda. You can trigger the lambda synchronously or asynchronously, but the setup of the config needs to be done before that. 143 | 144 | This is the type of object you need to pass as argument to create the configuration 145 | 146 | ```typescript 147 | type LambdaHttpInterceptorConfigInput = { 148 | lambdaName: string; 149 | mockConfigs: { 150 | url?: string; 151 | method?: string; 152 | body?: string; 153 | headers?: { 154 | [x: string]: string; 155 | }; 156 | response: 157 | | { 158 | passThrough: true; 159 | } 160 | | { 161 | status: number; 162 | body?: string; 163 | headers?: { 164 | [x: string]: string; 165 | }; 166 | passThrough?: false; 167 | }; 168 | created?: string; 169 | modified?: string; 170 | queryParams?: 171 | | { 172 | [x: string]: string | undefined; 173 | } 174 | | undefined; 175 | }[]; 176 | }; 177 | ``` 178 | 179 | This is how to use the `setupLambdaHttpInterceptorConfig` method. 180 | 181 | ```typescript 182 | import fetch from "node-fetch"; 183 | import { expect, describe, it } from "vitest"; 184 | 185 | process.env.HTTP_INTERCEPTOR_TABLE_NAME = '' 186 | 187 | import { setupLambdaHttpInterceptorConfig } from "http-lambda-interceptor"; 188 | 189 | import { triggerMyLambdaFunctionThatMakesExternalCalls } from './utils'; 190 | 191 | describe("hello function", () => { 192 | it("returns a 200", async () => { 193 | await setupLambdaHttpInterceptorConfig({ 194 | lambdaName: '', 195 | mockConfigs: [ 196 | { 197 | url: "https://api-1/*", 198 | response: { 199 | status: 404, 200 | body: JSON.stringify({ 201 | errorMessage: "Not found", 202 | }), 203 | }, 204 | }, 205 | { 206 | url: "https://api-2/path", 207 | response: { 208 | passThrough: true, 209 | }, 210 | }, 211 | ], 212 | }); 213 | const response = await triggerMyLambdaFunctionThatMakesExternalCalls(); 214 | expect(response.status).toBe(200); 215 | }); 216 | }); 217 | ``` 218 | 219 | The url matching process works by 2 possible ways: 220 | - an exact match of the whole url (ex: `https://api-2/path-1/path-2`) 221 | - an exact match on part of the url. Every url beginning with the same path until the `*`, is matched (ex: `https://api-1/path/*` matches `https://api-1/path` and `https://api-1/path/path-3`) 222 | 223 | The method to be given in the method prop needs to be one the [standard HTTP request methods name](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). 224 | 225 | The response status to be given in the params needs to be one the [standard HTTP response status codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status). 226 | 227 | 228 | ### Multiple lambda triggers into a testing suite or across testing suites 229 | 230 | A `beforeEach` for setup and a `afterEach` with the cleaning method are required in order to make assertions independently between each test of a suite. 231 | 232 | For avoiding collisions between testing suites, if the cleaning method is not called in a test for a specific reason, the method needs to be called in a `afterAll`. 233 | 234 | And all tests dealing with the same lambda need to be performed in band, they can't be performed in parallel. 235 | 236 | An example of the code described here is available in the following section. 237 | 238 | ### Making expects on the intercepted calls 239 | 240 | The method waitForNumberOfInterceptedCalls is used to wait for all intercepted calls when they have been done. It needs configuration about the maximum time to wait before throwing because all supposed intercepted calls have been intercepted. 241 | 242 | ```typescript 243 | import fetch from "node-fetch"; 244 | import { expect, describe, it } from "vitest"; 245 | 246 | process.env.HTTP_INTERCEPTOR_TABLE_NAME = '' 247 | 248 | import { setupLambdaHttpInterceptorConfig } from "http-lambda-interceptor"; 249 | 250 | import { triggerMyLambdaFunctionThatMakesExternalCalls } from './utils'; 251 | 252 | describe("hello function", () => { 253 | it("returns a 200", async () => { 254 | await setupLambdaHttpInterceptorConfig({ 255 | lambdaName: '', 256 | mockConfigs: [ 257 | { 258 | url: "https://api-1/*", 259 | response: { 260 | status: 404, 261 | body: JSON.stringify({ 262 | errorMessage: "Not found", 263 | }), 264 | }, 265 | }, 266 | { 267 | url: "https://api-2/path", 268 | response: { 269 | passThrough: true, 270 | }, 271 | }, 272 | ], 273 | }); 274 | const response = await triggerMyLambdaFunctionThatMakesExternalCalls(); 275 | expect(response.status).toBe(200); 276 | }); 277 | afterEach(async () => { 278 | await cleanInterceptedCalls(''); 279 | }); 280 | it('returns 200 and catches 2 requests', async () => { 281 | const response = await fetch( 282 | `${TEST_ENV_VARS.API_URL}/make-external-call`, 283 | { 284 | method: 'post', 285 | }, 286 | ); 287 | 288 | const resp = await waitForNumberOfInterceptedCalls( 289 | '', 290 | 2, 291 | 5000, 292 | ); 293 | expect(response.status).toBe(200); 294 | expect(resp.length).toBe(2); 295 | }); 296 | it('returns also 200 and catches also 2 requests', async () => { 297 | const response = await fetch( 298 | `${TEST_ENV_VARS.API_URL}/make-external-call`, 299 | { 300 | method: 'post', 301 | }, 302 | ); 303 | 304 | const resp = await waitForNumberOfInterceptedCalls( 305 | '', 306 | 2, 307 | 5000, 308 | ); 309 | 310 | expect(response.status).toBe(200); 311 | expect(resp.length).toBe(2); 312 | // resp contains all information about the calls made to to external API endpoints mocked 313 | // Expects can be made on the content of the calls made once received 314 | }); 315 | }); 316 | ``` 317 | 318 | ## Coming next 319 | 320 | Having a class to instantiate in each test suite that will allow independent testing across all tests suites even on the same lambda. 321 | -------------------------------------------------------------------------------- /event-scout.excalidraw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MaximeVivier/lambda-http-interceptor/0c928656e3c1d7e1a4aaaeaf76b00c8460aa1955/event-scout.excalidraw.png -------------------------------------------------------------------------------- /lib/cdk/HttpInterceptor.ts: -------------------------------------------------------------------------------- 1 | import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb'; 2 | import { Construct } from 'constructs'; 3 | import { 4 | PARTITION_KEY, 5 | SORT_KEY, 6 | TTL_ATTRIBUTE_NAME, 7 | } from '../dynamoDbToolboxUtils'; 8 | import { HttpInterceptorExtension } from './HttpInterceptorExtension'; 9 | 10 | type Props = { 11 | configTableName?: string; 12 | }; 13 | export class HttpInterceptor extends Construct { 14 | public readonly extension: HttpInterceptorExtension; 15 | public readonly table: Table; 16 | constructor(scope: Construct, id: string, props?: Props) { 17 | super(scope, id); 18 | this.extension = new HttpInterceptorExtension(this, `${id}Extension`); 19 | 20 | this.table = new Table(this, 'ConfigTable', { 21 | partitionKey: { name: PARTITION_KEY, type: AttributeType.STRING }, 22 | sortKey: { name: SORT_KEY, type: AttributeType.STRING }, 23 | billingMode: BillingMode.PAY_PER_REQUEST, 24 | tableName: props?.configTableName, 25 | timeToLiveAttribute: TTL_ATTRIBUTE_NAME, 26 | }); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /lib/cdk/HttpInterceptorExtension.ts: -------------------------------------------------------------------------------- 1 | import { NodejsInternalExtension } from './applyNodejsInternalExtension'; 2 | import { 3 | Architecture, 4 | Code, 5 | LayerVersion, 6 | Runtime, 7 | } from 'aws-cdk-lib/aws-lambda'; 8 | import { Construct } from 'constructs'; 9 | 10 | export class HttpInterceptorExtension 11 | extends Construct 12 | implements NodejsInternalExtension 13 | { 14 | public readonly layerVersion: LayerVersion; 15 | public readonly entryPoint: string; 16 | constructor(scope: Construct, id: string) { 17 | super(scope, id); 18 | this.layerVersion = new LayerVersion(scope, 'HttpInterceptorLayer', { 19 | compatibleRuntimes: [Runtime.NODEJS_18_X], 20 | compatibleArchitectures: [Architecture.ARM_64], 21 | code: Code.fromAsset(`${__dirname}/../layer`), 22 | }); 23 | this.entryPoint = 'interceptor.js'; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /lib/cdk/applyHttpInterceptor.ts: -------------------------------------------------------------------------------- 1 | import { Construct } from 'constructs'; 2 | import { Aspects, IAspect } from 'aws-cdk-lib'; 3 | import { applyNodejsInternalExtensionToNodeJsFunction } from './applyNodejsInternalExtension'; 4 | import { HttpInterceptor } from './HttpInterceptor'; 5 | import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; 6 | import { HTTP_INTERCEPTOR_TABLE_NAME } from '../sdk'; 7 | 8 | class HttpInterceptorApplier implements IAspect { 9 | constructor(private httpInterceptor: HttpInterceptor) {} 10 | public visit(node: Construct): void { 11 | if (node instanceof NodejsFunction) { 12 | applyNodejsInternalExtensionToNodeJsFunction( 13 | node, 14 | this.httpInterceptor.extension, 15 | ); 16 | node.addEnvironment( 17 | HTTP_INTERCEPTOR_TABLE_NAME, 18 | this.httpInterceptor.table.tableName, 19 | ); 20 | this.httpInterceptor.table.grantReadData(node); 21 | this.httpInterceptor.table.grantWriteData(node); 22 | } 23 | } 24 | } 25 | export const applyHttpInterceptor = ( 26 | node: Construct, 27 | httpInterceptor: HttpInterceptor, 28 | ): void => { 29 | Aspects.of(node).add(new HttpInterceptorApplier(httpInterceptor)); 30 | }; 31 | -------------------------------------------------------------------------------- /lib/cdk/applyNodejsInternalExtension.ts: -------------------------------------------------------------------------------- 1 | import { Construct } from 'constructs'; 2 | import { Aspects, IAspect, Stack } from 'aws-cdk-lib'; 3 | import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; 4 | import { CfnFunction, LayerVersion } from 'aws-cdk-lib/aws-lambda'; 5 | 6 | export interface NodejsInternalExtension { 7 | layerVersion: LayerVersion; 8 | entryPoint: string; 9 | } 10 | 11 | const getPreviousNodeOptions = (node: NodejsFunction): string | undefined => { 12 | const env = Stack.of(node).resolve( 13 | (node.node.defaultChild as CfnFunction).environment, 14 | ) as { variables?: Record } | undefined; 15 | if (env === undefined) { 16 | return undefined; 17 | } 18 | return env.variables?.NODE_OPTIONS; 19 | }; 20 | 21 | export const applyNodejsInternalExtensionToNodeJsFunction = ( 22 | nodeJsFunction: NodejsFunction, 23 | internalExtension: NodejsInternalExtension, 24 | ): void => { 25 | const previousNodeOptions = getPreviousNodeOptions(nodeJsFunction); 26 | const requireExtensionOption = `--require /opt/${internalExtension.entryPoint}`; 27 | const newNodeOptions = previousNodeOptions 28 | ? [previousNodeOptions, requireExtensionOption].join(' ') 29 | : requireExtensionOption; 30 | 31 | nodeJsFunction.addEnvironment('NODE_OPTIONS', newNodeOptions); 32 | nodeJsFunction.addLayers(internalExtension.layerVersion); 33 | }; 34 | 35 | class NodejsInternalExtensionApplier implements IAspect { 36 | constructor(private internalExtension: NodejsInternalExtension) {} 37 | public visit(node: Construct): void { 38 | if (node instanceof NodejsFunction) { 39 | applyNodejsInternalExtensionToNodeJsFunction( 40 | node, 41 | this.internalExtension, 42 | ); 43 | } 44 | } 45 | } 46 | 47 | export const applyNodejsInternalExtension = ( 48 | node: Construct, 49 | internalExtension: NodejsInternalExtension, 50 | ): void => { 51 | Aspects.of(node).add(new NodejsInternalExtensionApplier(internalExtension)); 52 | }; 53 | -------------------------------------------------------------------------------- /lib/constants.ts: -------------------------------------------------------------------------------- 1 | export const oneHourInSeconds = 3600; 2 | -------------------------------------------------------------------------------- /lib/dynamoDbToolboxUtils/ddbtConstants.ts: -------------------------------------------------------------------------------- 1 | export const PARTITION_KEY = 'PK'; 2 | export const SORT_KEY = 'SK'; 3 | export const TTL_ATTRIBUTE_NAME = 'TTL'; 4 | -------------------------------------------------------------------------------- /lib/dynamoDbToolboxUtils/getDefaultTtl.ts: -------------------------------------------------------------------------------- 1 | import { oneHourInSeconds } from '../constants'; 2 | 3 | const getDefaultTtl = (): number => 4 | Math.ceil(new Date().getTime() / 1000) + oneHourInSeconds; 5 | 6 | export default getDefaultTtl; 7 | -------------------------------------------------------------------------------- /lib/dynamoDbToolboxUtils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './ddbtConstants'; 2 | export { default as getDefaultTtl } from './getDefaultTtl'; 3 | -------------------------------------------------------------------------------- /lib/index.ts: -------------------------------------------------------------------------------- 1 | export * from './cdk/applyHttpInterceptor'; 2 | export * from './cdk/HttpInterceptorExtension'; 3 | export * from './cdk/HttpInterceptor'; 4 | -------------------------------------------------------------------------------- /lib/layer/interceptor.ts: -------------------------------------------------------------------------------- 1 | import { ResponseTransformer, rest } from 'msw'; 2 | import { setupServer } from 'msw/node'; 3 | import debug from 'debug'; 4 | import { 5 | getEnv, 6 | getRequestResponse, 7 | AWS_LAMBDA_FUNCTION_NAME, 8 | HTTP_INTERCEPTOR_TABLE_NAME, 9 | putInterceptedCall, 10 | fetchLambdaHttpInterceptorConfig, 11 | } from '../sdk'; 12 | 13 | const log = debug('http-interceptor'); 14 | 15 | const server = setupServer( 16 | rest.all('*', async (req, res, ctx) => { 17 | try { 18 | const queryParams: Record = {}; 19 | req.url.searchParams.forEach((value, key) => (queryParams[key] = value)); 20 | const request = { 21 | url: req.url.toString(), 22 | method: req.method, 23 | headers: req.headers.all(), 24 | body: await req.text(), 25 | queryParams, 26 | }; 27 | 28 | if ( 29 | request.url.match(/dynamodb\..*\.amazonaws.com/) && 30 | request.body.match( 31 | new RegExp(`"TableName":"${getEnv(HTTP_INTERCEPTOR_TABLE_NAME)}"`), 32 | ) 33 | ) { 34 | return req.passthrough(); 35 | } 36 | 37 | log('request intercepted: ', JSON.stringify(request, null, 2)); 38 | 39 | const mockConfigs = await fetchLambdaHttpInterceptorConfig(); 40 | if (mockConfigs === undefined) { 41 | return req.passthrough(); 42 | } 43 | 44 | const mockResponse = getRequestResponse(request, mockConfigs); 45 | 46 | if (mockResponse.isOneOfConfiguredMocks) { 47 | await putInterceptedCall({ 48 | lambdaName: getEnv(AWS_LAMBDA_FUNCTION_NAME), 49 | callParams: request, 50 | }); 51 | } 52 | if (mockResponse.passThrough) { 53 | log(`letting ${request.method} ${request.url} pass through`); 54 | return req.passthrough(); 55 | } 56 | 57 | const responseTransformers = [ 58 | ctx.status(mockResponse.status), 59 | mockResponse.body && ctx.text(mockResponse.body), 60 | ...Object.entries(mockResponse.headers ?? {}).map( 61 | ([key, value]) => value && ctx.set(key, value), 62 | ), 63 | ].filter((transformer): transformer is ResponseTransformer => 64 | Boolean(transformer), 65 | ); 66 | 67 | log( 68 | `responding to ${request.method} ${request.url}`, 69 | JSON.stringify(mockResponse, null, 2), 70 | ); 71 | 72 | return res(...responseTransformers); 73 | } catch (err) { 74 | console.error('Extension http interceptor ERROR:', err); 75 | return res(); 76 | } 77 | }), 78 | ); 79 | 80 | server.listen({ onUnhandledRequest: 'bypass' }); 81 | -------------------------------------------------------------------------------- /lib/sdk/client.ts: -------------------------------------------------------------------------------- 1 | import { 2 | LambdaHttpInterceptorConfigInput, 3 | cleanInterceptedCalls, 4 | putLambdaHttpInterceptorConfig, 5 | pollInterceptedCalls, 6 | PollInterceptedCallsParams, 7 | } from './tables'; 8 | import { InterceptedCallParams } from './types'; 9 | 10 | export class HttpLambdaInterceptorClient { 11 | public lambdaName: string; 12 | 13 | constructor(lambdaName: string) { 14 | this.lambdaName = lambdaName; 15 | } 16 | 17 | /** 18 | * Creates the ddb records in the ddb table used to intercept http calls. 19 | * 20 | * @param configs - the configs to use for mocking http calls 21 | * 22 | */ 23 | async createConfigs( 24 | configs: LambdaHttpInterceptorConfigInput['mockConfigs'], 25 | ): Promise { 26 | const params = { 27 | lambdaName: this.lambdaName, 28 | mockConfigs: configs, 29 | }; 30 | await putLambdaHttpInterceptorConfig(params); 31 | } 32 | 33 | /** 34 | * Clean all InterceptedCall made with this lambda name. 35 | * 36 | * This is especially recommended to use between each execution of the lambda that is being tested in order not to have collisions between different tests. 37 | */ 38 | async cleanInterceptedCalls(): Promise { 39 | return cleanInterceptedCalls(this.lambdaName); 40 | } 41 | 42 | /** 43 | * Poll all intercepted calls of this lambda. 44 | * 45 | * @returns intercepted calls of this lambda. Assertions can be made on the results of this method that returns what has been intercepted based on the config created in the first place. 46 | * If the @numberOfCallsToExpect is strictly greater than the number of configured calls intercepted, this method will timeout. The default timeout used, if no @timeout is specified, is 10 seconds. 47 | */ 48 | async pollInterceptedCalls( 49 | params: PollInterceptedCallsParams, 50 | ): Promise { 51 | return pollInterceptedCalls(this.lambdaName, params); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /lib/sdk/getEnv.ts: -------------------------------------------------------------------------------- 1 | export const HTTP_INTERCEPTOR_TABLE_NAME = 'HTTP_INTERCEPTOR_TABLE_NAME'; 2 | export const AWS_LAMBDA_FUNCTION_NAME = 'AWS_LAMBDA_FUNCTION_NAME'; // AWS Lambda automatically sets this variable 3 | 4 | export type EnvVariableName = 5 | | typeof HTTP_INTERCEPTOR_TABLE_NAME 6 | | typeof AWS_LAMBDA_FUNCTION_NAME; 7 | 8 | export const getEnv = (key: EnvVariableName): string => { 9 | const value = process.env[key]; 10 | if (!value) { 11 | throw new Error(`Missing environment variable ${key}`); 12 | } 13 | return value; 14 | }; 15 | -------------------------------------------------------------------------------- /lib/sdk/getFirstMatchingConfig.ts: -------------------------------------------------------------------------------- 1 | import { MockConfig, Request } from './types'; 2 | import { requestMatchConfig } from './requestMatchConfig'; 3 | 4 | export const getFirstMatchingConfig = ( 5 | request: Request, 6 | configs: MockConfig[], 7 | ): MockConfig | undefined => 8 | configs.find(config => { 9 | return requestMatchConfig(request, config); 10 | }); 11 | 12 | export const getRequestResponse = ( 13 | request: Request, 14 | configs: MockConfig[], 15 | ): MockConfig['response'] & { isOneOfConfiguredMocks: boolean } => { 16 | const firstMatchingConfig = getFirstMatchingConfig(request, configs); 17 | if (firstMatchingConfig === undefined) { 18 | return { 19 | passThrough: true, 20 | isOneOfConfiguredMocks: false, 21 | }; 22 | } 23 | return { 24 | ...firstMatchingConfig.response, 25 | isOneOfConfiguredMocks: true, 26 | }; 27 | }; 28 | -------------------------------------------------------------------------------- /lib/sdk/index.ts: -------------------------------------------------------------------------------- 1 | export * from './tables'; 2 | export * from './getEnv'; 3 | export * from './requestMatchConfig'; 4 | export * from './getFirstMatchingConfig'; 5 | export * from './types'; 6 | export * from './client'; 7 | -------------------------------------------------------------------------------- /lib/sdk/requestMatchConfig.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'vitest'; 2 | import { requestMatchConfig } from './requestMatchConfig'; 3 | 4 | describe('requestMatchConfig', () => { 5 | describe('exact match config', () => { 6 | const config = { 7 | url: 'https://api.coindesk.com/', 8 | method: 'GET', 9 | body: '', 10 | headers: { 11 | 'Content-Type': 'application/json', 12 | }, 13 | response: { 14 | status: 200, 15 | }, 16 | }; 17 | it('returns true when the request matches the config', () => { 18 | const request = { 19 | url: 'https://api.coindesk.com/', 20 | method: 'GET', 21 | body: '', 22 | headers: { 23 | 'content-type': 'application/json', 24 | }, 25 | }; 26 | expect(requestMatchConfig(request, config)).toBe(true); 27 | }); 28 | it('returns false when the request does not match the config', () => { 29 | const request = { 30 | url: 'https://api.coindesk.com/', 31 | method: 'POST', 32 | body: '', 33 | headers: { 34 | 'content-type': 'application/json', 35 | }, 36 | }; 37 | expect(requestMatchConfig(request, config)).toBe(false); 38 | }); 39 | }); 40 | describe('method exact match config', () => { 41 | const config = { 42 | method: 'GET', 43 | response: { 44 | status: 200, 45 | }, 46 | }; 47 | it('returns true when the request matches the config', () => { 48 | const request = { 49 | url: 'https://api.coindesk.com/', 50 | method: 'GET', 51 | body: '', 52 | headers: {}, 53 | }; 54 | expect(requestMatchConfig(request, config)).toBe(true); 55 | }); 56 | it('returns false when the request does not match the config', () => { 57 | const request = { 58 | url: 'https://api.coindesk.com/', 59 | method: 'POST', 60 | body: '', 61 | headers: {}, 62 | }; 63 | expect(requestMatchConfig(request, config)).toBe(false); 64 | }); 65 | }); 66 | describe('headers match config', () => { 67 | const config = { 68 | headers: { 69 | 'Content-Type': 'application/json', 70 | 'X-Api-Key': '1234', 71 | }, 72 | response: { 73 | status: 200, 74 | }, 75 | }; 76 | it('returns true when the headers contains all the ones of the config', () => { 77 | const request = { 78 | url: 'https://api.coindesk.com/', 79 | method: 'GET', 80 | body: '', 81 | headers: { 82 | 'content-type': 'application/json', 83 | 'x-api-key': '1234', 84 | accept: 'application/json', 85 | }, 86 | }; 87 | expect(requestMatchConfig(request, config)).toBe(true); 88 | }); 89 | it('returns false when an header does not match with the one of the config', () => { 90 | const request = { 91 | url: 'https://api.coindesk.com/', 92 | method: 'GET', 93 | body: '', 94 | headers: { 95 | 'content-type': 'application/json', 96 | 'x-api-key': '5678', 97 | accept: 'application/json', 98 | }, 99 | }; 100 | expect(requestMatchConfig(request, config)).toBe(false); 101 | }); 102 | it('returns false when an header is missing from the config', () => { 103 | const request = { 104 | url: 'https://api.coindesk.com/', 105 | method: 'GET', 106 | body: '', 107 | headers: { 108 | 'content-type': 'application/json', 109 | accept: 'application/json', 110 | }, 111 | }; 112 | expect(requestMatchConfig(request, config)).toBe(false); 113 | }); 114 | }); 115 | describe('url exact match config', () => { 116 | const config = { 117 | url: 'https://api.coindesk.com/', 118 | response: { 119 | status: 200, 120 | }, 121 | }; 122 | it('returns true when the url match the regex', () => { 123 | const request = { 124 | url: 'https://api.coindesk.com/', 125 | method: 'GET', 126 | body: '', 127 | headers: {}, 128 | }; 129 | expect(requestMatchConfig(request, config)).toBe(true); 130 | }); 131 | it('returns false when the url does not match the regex', () => { 132 | const request = { 133 | url: 'https://api.coindesk.fr/', 134 | method: 'GET', 135 | body: '', 136 | headers: {}, 137 | }; 138 | expect(requestMatchConfig(request, config)).toBe(false); 139 | }); 140 | }); 141 | describe('url wildcard match config', () => { 142 | const config = { 143 | url: 'https://api.coindesk.com/*', 144 | response: { 145 | status: 200, 146 | }, 147 | }; 148 | it('returns true when the url match with wildcard', () => { 149 | const request = { 150 | url: 'https://api.coindesk.com/BTC', 151 | method: 'GET', 152 | body: '', 153 | headers: {}, 154 | }; 155 | expect(requestMatchConfig(request, config)).toBe(true); 156 | }); 157 | it('returns false when the url does not match', () => { 158 | const request = { 159 | url: 'https://api.coindesk.fr/BTC', 160 | method: 'GET', 161 | body: '', 162 | headers: {}, 163 | }; 164 | expect(requestMatchConfig(request, config)).toBe(false); 165 | }); 166 | }); 167 | describe('body exact match config', () => { 168 | const config = { 169 | body: JSON.stringify({ foo: 'bar' }), 170 | response: { 171 | status: 200, 172 | }, 173 | }; 174 | it('returns true when the body match', () => { 175 | const request = { 176 | url: 'https://api.coindesk.com/', 177 | method: 'GET', 178 | body: JSON.stringify({ foo: 'bar' }), 179 | headers: {}, 180 | }; 181 | expect(requestMatchConfig(request, config)).toBe(true); 182 | }); 183 | it('returns false when the body does not match', () => { 184 | const request = { 185 | url: 'https://api.coindesk.com/', 186 | method: 'GET', 187 | body: JSON.stringify({ foo: 'baz' }), 188 | headers: {}, 189 | }; 190 | expect(requestMatchConfig(request, config)).toBe(false); 191 | }); 192 | }); 193 | it('returns always true with an empty config', () => { 194 | const config = { 195 | response: { 196 | status: 200, 197 | }, 198 | }; 199 | const request = { 200 | url: 'https://api.coindesk.com/', 201 | method: 'GET', 202 | body: '', 203 | headers: { 204 | 'content-type': 'application/json', 205 | }, 206 | }; 207 | expect(requestMatchConfig(request, config)).toBe(true); 208 | }); 209 | it('returns true when all present member match', () => { 210 | const config = { 211 | url: 'https://api.coindesk.com/*', 212 | method: 'GET', 213 | response: { 214 | status: 200, 215 | }, 216 | }; 217 | const request = { 218 | url: 'https://api.coindesk.com/BTC', 219 | method: 'GET', 220 | body: '', 221 | headers: { 222 | 'content-type': 'application/json', 223 | }, 224 | }; 225 | expect(requestMatchConfig(request, config)).toBe(true); 226 | }); 227 | it('returns false when one member does not match', () => { 228 | const config = { 229 | url: 'https://api.coindesk.com/*', 230 | method: 'GET', 231 | response: { 232 | status: 200, 233 | }, 234 | }; 235 | const request = { 236 | url: 'https://api.coindesk.com/BTC', 237 | method: 'POST', 238 | body: '', 239 | headers: { 240 | 'content-type': 'application/json', 241 | }, 242 | }; 243 | expect(requestMatchConfig(request, config)).toBe(false); 244 | }); 245 | }); 246 | -------------------------------------------------------------------------------- /lib/sdk/requestMatchConfig.ts: -------------------------------------------------------------------------------- 1 | import { MockConfig, Request } from './types'; 2 | 3 | const urlMatch = ( 4 | requestUrl: string, 5 | configUrl: string | undefined, 6 | ): boolean => { 7 | if (!configUrl) { 8 | return true; 9 | } 10 | if (configUrl === requestUrl) { 11 | return true; 12 | } 13 | if ( 14 | configUrl.endsWith('*') && 15 | requestUrl.startsWith(configUrl.slice(0, -1)) 16 | ) { 17 | return true; 18 | } 19 | return false; 20 | }; 21 | 22 | const methodMatch = ( 23 | requestMethod: string, 24 | configMethod: string | undefined, 25 | ): boolean => configMethod === undefined || configMethod === requestMethod; 26 | 27 | const bodyMatch = ( 28 | requestBody: string, 29 | configBody: string | undefined, 30 | ): boolean => configBody === undefined || configBody === requestBody; 31 | 32 | const sanitizeHeaders = ( 33 | headers: Record, 34 | ): Record => 35 | Object.entries(headers).reduce>( 36 | (acc, [key, value]) => { 37 | acc[key.toLowerCase()] = value; 38 | return acc; 39 | }, 40 | {}, 41 | ); 42 | const headersMatch = ( 43 | requestHeaders: Record, 44 | configHeaders: Record | undefined, 45 | ): boolean => { 46 | if (configHeaders === undefined) { 47 | return true; 48 | } 49 | const sanitizedRequestHeaders = sanitizeHeaders(requestHeaders); 50 | for (const [key, value] of Object.entries(configHeaders)) { 51 | if (sanitizedRequestHeaders[key.toLowerCase()] !== value) { 52 | return false; 53 | } 54 | } 55 | return true; 56 | }; 57 | export const requestMatchConfig = ( 58 | request: Request, 59 | config: MockConfig, 60 | ): boolean => 61 | urlMatch(request.url, config.url) && 62 | methodMatch(request.method, config.method) && 63 | bodyMatch(request.body, config.body) && 64 | headersMatch(request.headers, config.headers); 65 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/index.ts: -------------------------------------------------------------------------------- 1 | export * from './lambdaHttpInterceptorConfigEntity'; 2 | export * from './lambdaHttpInterceptorInterceptedCallEntity'; 3 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorConfigEntity/entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | EntityV2, 3 | schema, 4 | string, 5 | map, 6 | boolean, 7 | number, 8 | record, 9 | list, 10 | anyOf, 11 | PutItemInput, 12 | FormattedItem, 13 | } from 'dynamodb-toolbox'; 14 | 15 | import { lambdaHttpInterceptorTable } from '../../lambdaHttpInterceptorTable'; 16 | import { 17 | TTL_ATTRIBUTE_NAME, 18 | getDefaultTtl, 19 | } from '../../../../dynamoDbToolboxUtils'; 20 | 21 | const lambdaHttpInterceptorConfigSchema = schema({ 22 | lambdaName: string().key().savedAs('PK'), 23 | entityName: string().key().const('lambdaHttpInterceptorConfig').savedAs('SK'), 24 | mockConfigs: list( 25 | map({ 26 | url: string().optional(), 27 | method: string().optional(), 28 | body: string().optional(), 29 | headers: record(string(), string()).optional(), 30 | queryParams: record(string(), string()).optional(), 31 | response: anyOf([ 32 | map({ 33 | passThrough: boolean().enum(true), 34 | }), 35 | map({ 36 | passThrough: boolean().enum(false).optional(), 37 | status: number(), 38 | headers: record(string(), string()).optional(), 39 | body: string().optional(), 40 | }), 41 | ]), 42 | }), 43 | ), 44 | [TTL_ATTRIBUTE_NAME]: number().default(getDefaultTtl), 45 | }); 46 | 47 | export const lambdaHttpInterceptorConfigEntity = new EntityV2({ 48 | name: 'LambdaHttpInterceptorConfigEntity', 49 | table: lambdaHttpInterceptorTable, 50 | schema: lambdaHttpInterceptorConfigSchema, 51 | }); 52 | 53 | export type LambdaHttpInterceptorConfigInput = PutItemInput< 54 | typeof lambdaHttpInterceptorConfigEntity 55 | >; 56 | 57 | export type LambdaHttpInterceptorConfig = FormattedItem< 58 | typeof lambdaHttpInterceptorConfigEntity 59 | >; 60 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorConfigEntity/fetchLambdaHttpInterceptorConfig.ts: -------------------------------------------------------------------------------- 1 | import { GetItemCommand } from 'dynamodb-toolbox'; 2 | import { MockConfig } from '../../../types'; 3 | import { lambdaHttpInterceptorConfigEntity } from './entity'; 4 | import { AWS_LAMBDA_FUNCTION_NAME, getEnv } from '../../../getEnv'; 5 | 6 | export const fetchLambdaHttpInterceptorConfig = async (): Promise< 7 | MockConfig[] | undefined 8 | > => { 9 | const command = new GetItemCommand(lambdaHttpInterceptorConfigEntity, { 10 | lambdaName: getEnv(AWS_LAMBDA_FUNCTION_NAME), 11 | }); 12 | 13 | const { Item } = await command.send(); 14 | 15 | return Item?.mockConfigs; 16 | }; 17 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorConfigEntity/index.ts: -------------------------------------------------------------------------------- 1 | export * from './entity'; 2 | export * from './fetchLambdaHttpInterceptorConfig'; 3 | export * from './putLambdaHttpInterceptorConfig'; 4 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorConfigEntity/putLambdaHttpInterceptorConfig.ts: -------------------------------------------------------------------------------- 1 | import { PutItemCommand } from 'dynamodb-toolbox'; 2 | import { 3 | lambdaHttpInterceptorConfigEntity, 4 | LambdaHttpInterceptorConfigInput, 5 | } from './entity'; 6 | 7 | export const putLambdaHttpInterceptorConfig = async ( 8 | params: LambdaHttpInterceptorConfigInput, 9 | ) => { 10 | const command = new PutItemCommand(lambdaHttpInterceptorConfigEntity, params); 11 | 12 | await command.send(); 13 | }; 14 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorInterceptedCallEntity/cleanInterceptedCalls.ts: -------------------------------------------------------------------------------- 1 | import { DeleteItemCommand } from 'dynamodb-toolbox'; 2 | import { interceptedCallEntity } from './entity'; 3 | import { listInterceptedCallsPkAndSk } from './fetchInterceptedCalls'; 4 | 5 | export const cleanInterceptedCalls = async (lambdaName: string) => { 6 | const interceptedCallsPkAndSk = await listInterceptedCallsPkAndSk(lambdaName); 7 | await Promise.all( 8 | interceptedCallsPkAndSk.map(async recordToDelete => { 9 | const command = new DeleteItemCommand(interceptedCallEntity, { 10 | lambdaName: recordToDelete.PK, 11 | entityName: recordToDelete.SK, 12 | }); 13 | 14 | await command.send(); 15 | }), 16 | ); 17 | }; 18 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorInterceptedCallEntity/entity.ts: -------------------------------------------------------------------------------- 1 | import { 2 | EntityV2, 3 | schema, 4 | string, 5 | map, 6 | number, 7 | record, 8 | PutItemInput, 9 | FormattedItem, 10 | } from 'dynamodb-toolbox'; 11 | import { ulid } from 'ulid'; 12 | 13 | import { lambdaHttpInterceptorTable } from '../../lambdaHttpInterceptorTable'; 14 | import { 15 | TTL_ATTRIBUTE_NAME, 16 | getDefaultTtl, 17 | } from '../../../../dynamoDbToolboxUtils'; 18 | 19 | export const interceptedCallEntityStartName = 'interceptedCall'; 20 | 21 | const getInterceptedCallEntityName = (): string => 22 | `${interceptedCallEntityStartName}#${ulid()}`; 23 | 24 | const interceptedCallSchema = schema({ 25 | lambdaName: string().key().savedAs('PK'), 26 | entityName: string() 27 | .key() 28 | .default(getInterceptedCallEntityName) 29 | .savedAs('SK'), 30 | callParams: map({ 31 | url: string(), 32 | method: string(), 33 | body: string().optional(), 34 | headers: record(string(), string()).optional(), 35 | queryParams: record(string(), string()).optional(), 36 | }), 37 | 38 | [TTL_ATTRIBUTE_NAME]: number().default(getDefaultTtl), 39 | }); 40 | 41 | export const interceptedCallEntity = new EntityV2({ 42 | name: 'interceptedCallEntity', 43 | table: lambdaHttpInterceptorTable, 44 | schema: interceptedCallSchema, 45 | }); 46 | 47 | export type InterceptedCallInput = PutItemInput; 48 | 49 | export type InterceptedCall = FormattedItem; 50 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorInterceptedCallEntity/fetchInterceptedCalls.ts: -------------------------------------------------------------------------------- 1 | import { 2 | InterceptedCall, 3 | interceptedCallEntity, 4 | interceptedCallEntityStartName, 5 | } from './entity'; 6 | import { InterceptedCallParams } from '../../../types'; 7 | import { QueryCommand, QueryCommandInput } from '@aws-sdk/lib-dynamodb'; 8 | import { PARTITION_KEY, SORT_KEY } from '../../../../dynamoDbToolboxUtils'; 9 | import { lambdaHttpInterceptorTable } from '../../lambdaHttpInterceptorTable'; 10 | 11 | export const fetchInterceptedCalls = async ( 12 | lambdaName: string, 13 | ): Promise => { 14 | // --- TODO: replace all this when ddbt qurey command will be available ---- 15 | const queryInputCommand = { 16 | TableName: interceptedCallEntity.table.name, 17 | KeyConditionExpression: '#pk = :pkval and begins_with(#sk, :skval)', 18 | ExpressionAttributeNames: { 19 | '#pk': PARTITION_KEY, // Replace with your actual PK attribute name 20 | '#sk': SORT_KEY, // Replace with your actual SK attribute name 21 | }, 22 | ExpressionAttributeValues: { 23 | ':pkval': lambdaName, // Replace with your actual PK value 24 | ':skval': interceptedCallEntityStartName, // Replace with your actual SK prefix 25 | }, 26 | } satisfies QueryCommandInput; 27 | const command = new QueryCommand(queryInputCommand); 28 | 29 | const { Items: interceptedCalls } = 30 | (await lambdaHttpInterceptorTable.documentClient.send( 31 | command, 32 | )) as unknown as { Items?: InterceptedCall[] }; 33 | 34 | // ------------------------------- END TODO ------------------------------- 35 | 36 | if (interceptedCalls === undefined) return []; 37 | 38 | return interceptedCalls.map(({ callParams }) => callParams); 39 | }; 40 | 41 | type InterceptedCallsPkAndSk = { 42 | [PARTITION_KEY]: string; 43 | [SORT_KEY]: string; 44 | }[]; 45 | 46 | export const listInterceptedCallsPkAndSk = async ( 47 | lambdaName: string, 48 | ): Promise => { 49 | // --- TODO: replace all this when ddbt qurey command will be available ---- 50 | const queryInputCommand = { 51 | TableName: interceptedCallEntity.table.name, 52 | KeyConditionExpression: '#pk = :pkval and begins_with(#sk, :skval)', 53 | ExpressionAttributeNames: { 54 | '#pk': PARTITION_KEY, // Replace with your actual PK attribute name 55 | '#sk': SORT_KEY, // Replace with your actual SK attribute name 56 | }, 57 | ExpressionAttributeValues: { 58 | ':pkval': lambdaName, // Replace with your actual PK value 59 | ':skval': interceptedCallEntityStartName, // Replace with your actual SK prefix 60 | }, 61 | ProjectionExpression: `${PARTITION_KEY}, ${SORT_KEY}`, 62 | } satisfies QueryCommandInput; 63 | const command = new QueryCommand(queryInputCommand); 64 | 65 | const { Items: interceptedCalls } = 66 | (await lambdaHttpInterceptorTable.documentClient.send( 67 | command, 68 | )) as unknown as { 69 | Items?: InterceptedCallsPkAndSk; 70 | }; 71 | 72 | // ------------------------------- END TODO ------------------------------- 73 | 74 | if (interceptedCalls === undefined) return []; 75 | 76 | return interceptedCalls; 77 | }; 78 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorInterceptedCallEntity/index.ts: -------------------------------------------------------------------------------- 1 | export * from './entity'; 2 | export * from './cleanInterceptedCalls'; 3 | export * from './putInterceptedCall'; 4 | export * from './fetchInterceptedCalls'; 5 | export * from './waitForNumberOfInterceptedCalls'; 6 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorInterceptedCallEntity/putInterceptedCall.ts: -------------------------------------------------------------------------------- 1 | import { PutItemCommand } from 'dynamodb-toolbox'; 2 | import { InterceptedCallInput, interceptedCallEntity } from './entity'; 3 | 4 | export const putInterceptedCall = async (params: InterceptedCallInput) => { 5 | const command = new PutItemCommand(interceptedCallEntity, params); 6 | 7 | await command.send(); 8 | }; 9 | -------------------------------------------------------------------------------- /lib/sdk/tables/entities/lambdaHttpInterceptorInterceptedCallEntity/waitForNumberOfInterceptedCalls.ts: -------------------------------------------------------------------------------- 1 | import { InterceptedCallParams } from 'sdk'; 2 | import { 3 | fetchInterceptedCalls, 4 | listInterceptedCallsPkAndSk, 5 | } from './fetchInterceptedCalls'; 6 | 7 | const sleep = (delayInMs: number) => 8 | new Promise(resolve => setTimeout(resolve, delayInMs)); 9 | 10 | const DEFAULT_TIMEOUT = 10000; 11 | 12 | export type PollInterceptedCallsParams = { 13 | numberOfCallsToExpect: number; 14 | timeout?: number; 15 | }; 16 | 17 | /** 18 | * Wait for intercepted calls to be available 19 | * 20 | * @param lambdaName string 21 | * @param numberOfCallsToExpect number 22 | * @param timeout number in milliseconds - default value to 10000ms 23 | */ 24 | export const pollInterceptedCalls = async ( 25 | lambdaName: string, 26 | { numberOfCallsToExpect, timeout }: PollInterceptedCallsParams, 27 | ): Promise => { 28 | const startTime = Date.now(); 29 | let currentInterceptedCallsCount: number = 0; 30 | do { 31 | const interceptedCallsPkAndSk = await listInterceptedCallsPkAndSk( 32 | lambdaName, 33 | ); 34 | currentInterceptedCallsCount = interceptedCallsPkAndSk.length; 35 | if (currentInterceptedCallsCount >= numberOfCallsToExpect) { 36 | return fetchInterceptedCalls(lambdaName); 37 | } 38 | sleep(200); 39 | } while (Date.now() - startTime <= (timeout ?? DEFAULT_TIMEOUT)); 40 | throw new Error( 41 | `[waitForNumberOfInterceptedCalls ERROR] Waited for ${timeout}ms for ${numberOfCallsToExpect} intercepted calls but only got ${currentInterceptedCallsCount}`, 42 | ); 43 | }; 44 | -------------------------------------------------------------------------------- /lib/sdk/tables/index.ts: -------------------------------------------------------------------------------- 1 | export * from './entities'; 2 | export * from './lambdaHttpInterceptorTable'; 3 | -------------------------------------------------------------------------------- /lib/sdk/tables/lambdaHttpInterceptorTable.ts: -------------------------------------------------------------------------------- 1 | import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; 2 | import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb'; 3 | // Will be renamed Table in the official release 😉 4 | import { TableV2 } from 'dynamodb-toolbox'; 5 | 6 | const dynamoDBClient = new DynamoDBClient({}); 7 | const documentClient = DynamoDBDocumentClient.from(dynamoDBClient); 8 | 9 | export const lambdaHttpInterceptorTable = new TableV2({ 10 | name: process.env.HTTP_INTERCEPTOR_TABLE_NAME ?? 'NeverUsed', 11 | partitionKey: { 12 | name: 'PK', 13 | type: 'string', // 'string' | 'number' | 'binary' 14 | }, 15 | sortKey: { 16 | name: 'SK', 17 | type: 'string', 18 | }, 19 | documentClient, 20 | }); 21 | -------------------------------------------------------------------------------- /lib/sdk/types.ts: -------------------------------------------------------------------------------- 1 | import { LambdaHttpInterceptorConfig } from './tables/entities/lambdaHttpInterceptorConfigEntity/entity'; 2 | import { InterceptedCall } from './tables/entities/lambdaHttpInterceptorInterceptedCallEntity/entity'; 3 | 4 | export type MockConfig = LambdaHttpInterceptorConfig['mockConfigs'][number]; 5 | export type InterceptedCallParams = InterceptedCall['callParams']; 6 | 7 | export type Request = { 8 | url: string; 9 | method: string; 10 | body: string; 11 | headers: Record; 12 | }; 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lambda-http-interceptor", 3 | "version": "0.1.1", 4 | "main": "dist/index.js", 5 | "types": "dist/index.d.ts", 6 | "sideEffects": false, 7 | "scripts": { 8 | "build": "rm -rf dist && tsc -p ./tsconfig.build.json && pnpm build:interceptor", 9 | "build:interceptor": "./node_modules/.bin/esbuild --bundle --platform=node --main-fields=module,main --sourcemap lib/layer/interceptor.ts --outfile='./dist/layer/interceptor.js'", 10 | "watch": "tsc -w", 11 | "test:type": "tsc --noEmit", 12 | "test:unit": "vitest", 13 | "test:integration": "vitest run --config vitest.integration.config.ts --passWithNoTests", 14 | "deploy-test-stack": "cd test; cdk deploy", 15 | "synth-test-stack": "cd test; cdk synth", 16 | "publish-package": "pnpm run build; npm publish" 17 | }, 18 | "devDependencies": { 19 | "@aws-cdk/aws-apigatewayv2-alpha": "2.88.0-alpha.0", 20 | "@aws-cdk/aws-apigatewayv2-integrations-alpha": "2.88.0-alpha.0", 21 | "@serverless/typescript": "^3.30.1", 22 | "@swarmion/integration-tests": "^0.28.2", 23 | "@swarmion/serverless-helpers": "^0.28.2", 24 | "@types/aws-lambda": "^8.10.115", 25 | "@types/debug": "^4.1.8", 26 | "@types/node": "18.14.6", 27 | "aws-cdk": "^2.88.0", 28 | "aws-cdk-lib": "^2.88.0", 29 | "aws-lambda": "^1.0.7", 30 | "constructs": "^10.2.69", 31 | "esbuild": "^0.17.19", 32 | "node-fetch": "^3.3.1", 33 | "prettier": "^3.0.0", 34 | "ts-jest": "^29.0.5", 35 | "typescript": "~4.9.5", 36 | "vite-tsconfig-paths": "^4.2.0", 37 | "vitest": "^0.33.0" 38 | }, 39 | "dependencies": { 40 | "@aws-sdk/client-dynamodb": "^3.363.0", 41 | "@aws-sdk/lib-dynamodb": "^3.365.0", 42 | "@swarmion/serverless-helpers": "^0.28.2", 43 | "debug": "^4.3.4", 44 | "dynamodb-toolbox": "1.0.0-beta.0", 45 | "msw": "^1.2.3", 46 | "ulid": "^2.3.0" 47 | }, 48 | "packageManager": "pnpm@8.4.0", 49 | "peerDependencies": { 50 | "aws-cdk-lib": "^2.72.1", 51 | "constructs": "^10.0.0", 52 | "msw": "^1.2.2" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /setupIntegration.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | 3 | import { syncTestEnvVars } from '@swarmion/integration-tests'; 4 | 5 | // @ts-ignore 6 | await syncTestEnvVars({ 7 | scope: 'http-interceptor-test', 8 | cacheFilePath: path.resolve(__dirname, './testEnvVarsCache.json'), 9 | }); 10 | -------------------------------------------------------------------------------- /test/cdk.json: -------------------------------------------------------------------------------- 1 | { 2 | "app": "npx ts-node --prefer-ts-exts index.ts", 3 | "watch": { 4 | "include": ["**"], 5 | "exclude": [ 6 | "README.md", 7 | "cdk*.json", 8 | "**/*.d.ts", 9 | "**/*.js", 10 | "tsconfig.json", 11 | "package*.json", 12 | "yarn.lock", 13 | "node_modules", 14 | "test" 15 | ] 16 | }, 17 | "context": { 18 | "@aws-cdk/aws-lambda:recognizeLayerVersion": true, 19 | "@aws-cdk/core:checkSecretUsage": true, 20 | "@aws-cdk/core:target-partitions": ["aws", "aws-cn"], 21 | "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true, 22 | "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true, 23 | "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true, 24 | "@aws-cdk/aws-iam:minimizePolicies": true, 25 | "@aws-cdk/core:validateSnapshotRemovalPolicy": true, 26 | "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true, 27 | "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true, 28 | "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true, 29 | "@aws-cdk/aws-apigateway:disableCloudWatchRole": true, 30 | "@aws-cdk/core:enablePartitionLiterals": true, 31 | "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true, 32 | "@aws-cdk/aws-iam:standardizedServicePrincipals": true, 33 | "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true, 34 | "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true, 35 | "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true, 36 | "@aws-cdk/aws-route53-patters:useCertificate": true, 37 | "@aws-cdk/customresources:installLatestAwsSdkDefault": false, 38 | "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true, 39 | "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true, 40 | "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true, 41 | "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true, 42 | "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true, 43 | "@aws-cdk/aws-redshift:columnId": true, 44 | "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true, 45 | "testEnvVarTypePath": "./testEnvVars.ts", 46 | "testEnvVarScope": "http-interceptor-test" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /test/handler.integration-test.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | import { expect, describe, it, beforeAll, afterEach, afterAll } from 'vitest'; 3 | 4 | import { TEST_ENV_VARS } from './testEnvVars'; 5 | import { HttpLambdaInterceptorClient } from '../lib/sdk'; 6 | 7 | describe('hello function', () => { 8 | const interceptorClient = new HttpLambdaInterceptorClient( 9 | TEST_ENV_VARS.MAKE_EXTERNAL_CALLS_FUNCTION_NAME, 10 | ); 11 | beforeAll(async () => { 12 | await interceptorClient.createConfigs([ 13 | { 14 | url: 'https://api.coindesk.com/*', 15 | response: { 16 | status: 404, 17 | body: JSON.stringify({ 18 | errorMessage: 'Not found', 19 | }), 20 | }, 21 | }, 22 | { 23 | url: 'https://catfact.ninja/fact', 24 | response: { 25 | passThrough: true, 26 | }, 27 | }, 28 | ]); 29 | }); 30 | afterEach(async () => { 31 | await interceptorClient.cleanInterceptedCalls(); 32 | }); 33 | it('returns 200 and catches 2 requests', async () => { 34 | const response = await fetch( 35 | `${TEST_ENV_VARS.API_URL}/make-external-call`, 36 | { 37 | method: 'post', 38 | }, 39 | ); 40 | 41 | const resp = await interceptorClient.pollInterceptedCalls({ 42 | numberOfCallsToExpect: 2, 43 | timeout: 5000, 44 | }); 45 | expect(response.status).toBe(200); 46 | expect(resp.length).toBe(2); 47 | }); 48 | it('returns also 200 and catches also 2 requests', async () => { 49 | const response = await fetch( 50 | `${TEST_ENV_VARS.API_URL}/make-external-call`, 51 | { 52 | method: 'post', 53 | }, 54 | ); 55 | 56 | const resp = await interceptorClient.pollInterceptedCalls({ 57 | numberOfCallsToExpect: 2, 58 | timeout: 5000, 59 | }); 60 | 61 | expect(response.status).toBe(200); 62 | expect(resp.length).toBe(2); 63 | }); 64 | }); 65 | -------------------------------------------------------------------------------- /test/handler.ts: -------------------------------------------------------------------------------- 1 | import fetch from 'node-fetch'; 2 | 3 | export const handler = async (event: any) => { 4 | console.log('Received event', event); 5 | const firstCall = await fetch('https://catfact.ninja/fact'); 6 | const firstCallJson = (await firstCall.json()) as Record; 7 | console.log('First call response', firstCall.status, firstCallJson); 8 | const secondCall = await fetch( 9 | 'https://api.coindesk.com/v1/bpi/currentprice.json', 10 | ); 11 | const secondCallJson = (await secondCall.json()) as Record; 12 | console.log('Second call response', secondCall.status, secondCallJson); 13 | if ( 14 | firstCall.status !== 200 || 15 | !('fact' in firstCallJson) || 16 | !('length' in firstCallJson) 17 | ) { 18 | throw new Error('First call has been intercepted'); 19 | } 20 | if (secondCall.status !== 404 || !('errorMessage' in secondCallJson)) { 21 | throw new Error('Second call has not been intercepted'); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /test/index.ts: -------------------------------------------------------------------------------- 1 | import 'source-map-support/register'; 2 | import * as cdk from 'aws-cdk-lib'; 3 | import { LambdaHttpInterceptorTestStack } from './stack'; 4 | 5 | const app = new cdk.App(); 6 | new LambdaHttpInterceptorTestStack(app, 'LambdaHttpInterceptorTestStack', { 7 | /* If you don't specify 'env', this stack will be environment-agnostic. 8 | * Account/Region-dependent features and context lookups will not work, 9 | * but a single synthesized template can be deployed anywhere. */ 10 | /* Uncomment the next line to specialize this stack for the AWS Account 11 | * and Region that are implied by the current CLI configuration. */ 12 | // env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }, 13 | /* Uncomment the next line if you know exactly what Account and Region you 14 | * want to deploy the stack to. */ 15 | // env: { account: '123456789012', region: 'us-east-1' }, 16 | /* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */ 17 | }); 18 | -------------------------------------------------------------------------------- /test/stack.ts: -------------------------------------------------------------------------------- 1 | import { Stack, StackProps } from 'aws-cdk-lib'; 2 | import { HttpApi, HttpMethod } from '@aws-cdk/aws-apigatewayv2-alpha'; 3 | import { HttpLambdaIntegration } from '@aws-cdk/aws-apigatewayv2-integrations-alpha'; 4 | 5 | import { Construct } from 'constructs'; 6 | import { HttpInterceptor, applyHttpInterceptor } from '../dist'; // We need to use build package here to have the correct link to layer code -> The code must be built between two tests 7 | import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; 8 | import { getCdkHandlerPath } from '@swarmion/serverless-helpers'; 9 | import { Runtime } from 'aws-cdk-lib/aws-lambda'; 10 | import { TestEnvVar } from '@swarmion/integration-tests'; 11 | import { HTTP_INTERCEPTOR_TABLE_NAME } from '../lib/sdk'; 12 | 13 | export class LambdaHttpInterceptorTestStack extends Stack { 14 | constructor(scope: Construct, id: string, props?: StackProps) { 15 | super(scope, id, props); 16 | 17 | const httpApi = new HttpApi(this, 'HttpApi'); 18 | 19 | new TestEnvVar(this, 'API_URL', { 20 | value: httpApi.url as string, 21 | }); 22 | 23 | const interceptor = new HttpInterceptor(this, 'HttpInterceptor'); 24 | 25 | new TestEnvVar(this, 'HTTP_INTERCEPTOR_TABLE_NAME', { 26 | value: interceptor.table.tableName, 27 | }); 28 | 29 | const makeExternalCallFunction = new NodejsFunction( 30 | this, 31 | 'MakeExternalCalls', 32 | { 33 | runtime: Runtime.NODEJS_18_X, 34 | handler: 'index.handler', 35 | entry: getCdkHandlerPath(__dirname), 36 | environment: { 37 | NODE_OPTIONS: '--enable-source-maps', 38 | }, 39 | }, 40 | ); 41 | applyHttpInterceptor(makeExternalCallFunction, interceptor); 42 | 43 | new TestEnvVar(this, 'MAKE_EXTERNAL_CALLS_FUNCTION_NAME', { 44 | value: makeExternalCallFunction.functionName, 45 | }); 46 | 47 | const makeExternalCallIntegration = new HttpLambdaIntegration( 48 | 'MakeExternalCallsIntegration', 49 | makeExternalCallFunction, 50 | ); 51 | 52 | httpApi.addRoutes({ 53 | path: '/make-external-call', 54 | methods: [HttpMethod.POST], 55 | integration: makeExternalCallIntegration, 56 | }); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /test/testEnvVars.ts: -------------------------------------------------------------------------------- 1 | // This file is automatically generated. Do not edit it manually. cf https://www.swarmion.dev/docs/how-to-guides/use-integration-tests 2 | import { getTestEnvVars } from '@swarmion/integration-tests'; 3 | 4 | export type TestEnvVarsType = { 5 | API_URL: string; 6 | HTTP_INTERCEPTOR_TABLE_NAME: string; 7 | MAKE_EXTERNAL_CALLS_FUNCTION_NAME: string; 8 | }; 9 | 10 | export const TEST_ENV_VARS = getTestEnvVars(); 11 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["lib/layer/**/*"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "lib", 4 | "target": "ES2020", 5 | "module": "CommonJS", 6 | "lib": ["ES2020"], 7 | "declaration": true, 8 | "strict": true, 9 | "noImplicitAny": true, 10 | "strictNullChecks": true, 11 | "noImplicitThis": true, 12 | "alwaysStrict": true, 13 | "noUnusedLocals": false, 14 | "noUnusedParameters": false, 15 | "noImplicitReturns": true, 16 | "noFallthroughCasesInSwitch": false, 17 | "inlineSourceMap": true, 18 | "inlineSources": true, 19 | "experimentalDecorators": true, 20 | "strictPropertyInitialization": false, 21 | "moduleResolution": "node", // Not really understood all errors coming from removing this line 22 | "typeRoots": ["./node_modules/@types"], 23 | "outDir": "dist", 24 | "skipLibCheck": true 25 | }, 26 | "include": ["lib/**/*"] 27 | } 28 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config'; 2 | 3 | export default defineConfig({ 4 | test: { 5 | testTimeout: 30 * 1000, // 30 seconds 6 | clearMocks: true, 7 | }, 8 | }); 9 | -------------------------------------------------------------------------------- /vitest.integration.config.ts: -------------------------------------------------------------------------------- 1 | import tsconfigPaths from 'vite-tsconfig-paths'; 2 | import { defineConfig } from 'vitest/config'; 3 | 4 | export default defineConfig({ 5 | plugins: [tsconfigPaths()], 6 | test: { 7 | include: [ 8 | '**/*.{integration-test,integration-spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}', 9 | ], 10 | setupFiles: ['setupIntegration'], 11 | testTimeout: 100000, 12 | hookTimeout: 100000, 13 | }, 14 | }); 15 | --------------------------------------------------------------------------------