Repository navigation
feat: add spread middleware which will help to spread information around the event body - #4186
Conversation
…ound the event body
Summary by CodeRabbit
WalkthroughThe pull request introduces a middleware system to spread data across arrays. An abstract class ( Changes
Sequence Diagram(s)sequenceDiagram
participant Client as Client
participant Router as Koa Router
participant MS as SecretSpreader (ArraySpreader)
participant Controller as DestinationController
Client ->> Router: POST /routerTransform
Router ->> MS: Invoke SecretSpreader.middleware()
MS ->> MS: Extract values from headers, body, and query via BaseSpreader
MS ->> MS: Process spreadData using applySpreadData (calls getNestedValue/setNestedValue)
MS -->> Router: Return modified request context
Router ->> Controller: Forward request to destinationTransformAtRouter
Controller -->> Router: Send response
Router -->> Client: Return final response
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #4186 +/- ##
===========================================
- Coverage 91.05% 91.05% -0.01%
===========================================
Files 627 628 +1
Lines 33049 32990 -59
Branches 7818 7808 -10
===========================================
- Hits 30092 30038 -54
- Misses 2710 2735 +25
+ Partials 247 217 -30 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/middlewares/arraySpreader.ts (2)
4-27: Optimize the rule lookup in theapplySpreadDatamethod.The same rule lookup operation
this.config.rules.find((rule) => rule.target.path === key)is performed twice in lines 10 and 11-12, which is inefficient, especially if there are many rules.Consider storing the result of the first lookup and reusing it:
// Apply spread data to each array item Object.entries(ctx.spreadData).forEach(([key, value]) => { - if (this.config.rules.find((rule) => rule.target.path === key)?.target.arrayPath) { - const arrayPath = this.config.rules.find((rule) => rule.target.path === key)?.target - .arrayPath; + const matchingRule = this.config.rules.find((rule) => rule.target.path === key); + if (matchingRule?.target.arrayPath) { + const arrayPath = matchingRule.target.arrayPath; let array: any[] = []; if (arrayPath) { array = this.getNestedValue(body, arrayPath); }
29-44: Add test coverage for edge cases insetNestedValue.The
setNestedValuemethod has lines that aren't covered by tests according to static analysis. Consider adding tests for these scenarios to ensure robustness.Specifically, add tests for:
- Cases where parts of the nested path don't exist
- Edge cases with falsy values
- Different types of nested objects
// Example test to add it('should create nested objects when parts of the path do not exist', async () => { // Arrange const config = { name: 'test', rules: [] }; const arraySpreader = new ArraySpreader(config); const obj = {}; // Act - use private method through reflection or test a public method that uses it // @ts-ignore - accessing private method for testing arraySpreader['setNestedValue'](obj, 'deeply.nested.property', 'value'); // Assert expect(obj).toEqual({ deeply: { nested: { property: 'value' } } }); });🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 36-40: src/middlewares/arraySpreader.ts#L36-L40
Added lines #L36 - L40 were not covered by testssrc/middlewares/baseSpreader.ts (1)
31-42: Potential extension to support additional source types.
Currently, onlyheader,body, andqueryare supported. Consider extending this method to handle other sources like path parameters if needed.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/middlewares/arraySpreader.ts(1 hunks)src/middlewares/baseSpreader.ts(1 hunks)src/middlewares/tests/arraySpreader.test.ts(1 hunks)src/middlewares/types/spreader.ts(1 hunks)src/routes/destination.ts(2 hunks)
🧰 Additional context used
🧬 Code Definitions (4)
src/routes/destination.ts (1)
src/middlewares/arraySpreader.ts (1)
SecretSpreader(48-63)
src/middlewares/baseSpreader.ts (1)
src/middlewares/types/spreader.ts (2)
SpreaderConfig(15-19)SpreaderContext(21-23)
src/middlewares/arraySpreader.ts (1)
src/middlewares/types/spreader.ts (1)
SpreaderContext(21-23)
src/middlewares/tests/arraySpreader.test.ts (1)
src/middlewares/arraySpreader.ts (1)
ArraySpreader(4-45)
🪛 GitHub Check: codecov/patch
src/middlewares/arraySpreader.ts
[warning] 36-40: src/middlewares/arraySpreader.ts#L36-L40
Added lines #L36 - L40 were not covered by tests
🔇 Additional comments (14)
src/routes/destination.ts (2)
6-6: Import statement looks good.The import for the
SecretSpreaderis correctly added, facilitating the integration of the new middleware functionality.
22-22: Middleware integration looks good.The
SecretSpreader.middleware()is properly integrated into the middleware chain for the/routerTransformroute, positioned logically after the route activation and feature flag middleware and before the controller method.src/middlewares/types/spreader.ts (3)
3-13: Well-defined interface for spread rules.The
SpreadRuleinterface provides a clear structure for defining how data should be spread from a source to a target, with appropriate type constraints and optional transformation capability.
15-19: Good configuration interface design.The
SpreaderConfiginterface provides a clean way to configure the spreader with an array of rules, a name for identification, and an optional description for documentation purposes.
21-23: Appropriate extension of Koa Context.The
SpreaderContextinterface correctly extends Koa's Context to include thespreadDataproperty, which will be used to store the data that will be spread across array elements.src/middlewares/tests/arraySpreader.test.ts (3)
4-42: Test case correctly verifies basic array spreading functionality.This test effectively validates that the
ArraySpreadermiddleware correctly applies spread data (tenant ID) to each item in an array based on the configuration rules.
44-74: Test case thoroughly validates nested path handling.The test properly verifies that the
ArraySpreadercan correctly set nested values within array items, demonstrating the dot notation path functionality works as expected.
76-106: Edge case handling for empty arrays is well-tested.The test appropriately verifies that the
ArraySpreaderhandles empty arrays gracefully without throwing errors, which is important for robustness in production environments.src/middlewares/arraySpreader.ts (1)
29-44:Details
❓ Verification inconclusive
Consider handling falsy values consistently in
setNestedValue.The current implementation only sets values when
valueis truthy (line 40), which means falsy values likefalse,0, or empty strings won't be set. This might be intentional, but ensure it aligns with the expected behavior throughout the application.Consider modifying the check to allow setting all values including falsy ones (except
undefinedandnull):private setNestedValue(obj: any, path: string, value: any): void { const parts = path.split('.'); const last = parts.pop(); if (last) { const target = parts.reduce((acc, part) => { if (!acc[part]) { acc[part] = {}; } return acc[part]; }, obj); - if (value) { + if (value !== undefined && value !== null) { target[last] = value; } } }Run the following script to verify if falsy values are used in the codebase:
🏁 Script executed:
#!/bin/bash # Check for usage patterns of setNestedValue with falsy values rg -A 3 "setNestedValue|target\[last\]" --type typescriptLength of output: 94
I've updated the review comment to reflect that while switching to a more inclusive falsy value check is a good idea, the automated verification wasn’t conclusive. Please make sure that allowing falsy values (like 0, false, or empty strings) does not break any intended behavior in the application.
- The current logic only assigns the value if it's truthy, which may be skipping valid falsy values.
- The proposed change is to update the condition from:
to:if (value) {if (value !== undefined && value !== null) {- Since our initial verification script encountered issues (it reported an unrecognized file type), please manually verify that all usages of
setNestedValuein the codebase handle falsy values as expected.🧰 Tools
🪛 GitHub Check: codecov/patch
[warning] 36-40: src/middlewares/arraySpreader.ts#L36-L40
Added lines #L36 - L40 were not covered by testssrc/middlewares/baseSpreader.ts (5)
1-3: Well-structured import statements.
No issues found with the import declarations and usage of types.
4-6: Clear and concise class definition.
The abstract class design aligns with typical middleware patterns and naming conventions.
7-9: Constructor logic is straightforward.
Storing the config is handled properly; no concerns.
44-46: Robust nested value access.
Using optional chaining withreduceis a concise and clean approach. No issues found.
48-48: Abstract method encourages consistent subclass implementation.
Requiring subclasses to implement their own data-application logic is a good design choice.
|
make sure to have 100% coverage |
|
Allure Test reports for this run are available at:
|
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/middlewares/baseSpreader.ts (1)
17-31: 🛠️ Refactor suggestionHandle asynchronous transforms properly.
This block processes each rule synchronously and does not await the transform if it returns a Promise. This concern matches a past comment pointing out that asynchronous transformations won't be handled correctly with
forEach.A potential fix is to replace
forEachwith afor...ofloop, ensuring we can await each transform:- this.config.rules.forEach((rule) => { - const value = this.extractValue(spreaderCtx, rule.source); - if (value !== undefined) { - try { - spreaderCtx.spreadData[rule.target.path] = rule.transform - ? rule.transform(value) - : value; - } catch (e) { - throw new PlatformError( - `Error applying transform function for rule: ${JSON.stringify(rule)}`, - ); - } - } - }); + for (const rule of this.config.rules) { + const value = this.extractValue(spreaderCtx, rule.source); + if (value !== undefined) { + try { + spreaderCtx.spreadData[rule.target.path] = rule.transform + ? await rule.transform(value) + : value; + } catch (e) { + throw new PlatformError( + `Error applying transform function for rule: ${JSON.stringify(rule)}`, + ); + } + } + }
🧹 Nitpick comments (3)
src/middlewares/baseSpreader.ts (3)
25-28: Include the original error message for better debugging.Currently, the code rethrows a generic
PlatformError. Adding the original error message can help with faster troubleshooting.} catch (e) { - throw new PlatformError( - `Error applying transform function for rule: ${JSON.stringify(rule)}`, - ); + throw new PlatformError(` + Error applying transform function for rule: ${JSON.stringify(rule)}. + Original error: ${e instanceof Error ? e.message : e} + `); }
40-50: Check for unrecognized source types.Although returning
undefinedby default is valid, consider warning or throwing an error if the source type is not recognized to quickly expose bugs or misconfigurations.
53-55: Support array indexing in nested paths if required.This method currently splits on dots and returns
undefinedfor any array indexing in the path. If you expect array indices, consider an enhanced parser for nested paths.
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
src/middlewares/tests/arraySpreader.test.tsis excluded by!**/tests/**
📒 Files selected for processing (1)
src/middlewares/baseSpreader.ts(1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
src/middlewares/baseSpreader.ts (1)
src/middlewares/types/spreader.ts (2)
SpreaderConfig(15-19)SpreaderContext(21-23)
⏰ Context from checks skipped due to timeout of 90000ms (8)
- GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
- GitHub Check: Code Coverage
- GitHub Check: test_and_publish
- GitHub Check: ingestion-service-test
- GitHub Check: UT Tests
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Analyze (go)
|
Allure Test reports for this run are available at:
|
Only baseSpreader is at 95.23% as the default scenario in the |
|
Allure Test reports for this run are available at:
|
|



What are the changes introduced in this PR?
We are creating a middleware that will help to spread data all over the event body.
What is the related Linear task?
Resolves INT-3390
Please explain the objectives of your changes below
Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here
Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?
N/A
Any new dependencies introduced with this change?
N/A
Any new generic utility introduced or modified. Please explain the changes.
N/A
Any technical or performance related pointers to consider with the change?
N/A
@coderabbitai review
Developer checklist
My code follows the style guidelines of this project
No breaking changes are being introduced.
All related docs linked with the PR?
All changes manually tested?
Any documentation changes needed with this change?
Is the PR limited to 10 file changes?
Is the PR limited to one linear task?
Are relevant unit and component test-cases added in new readability format?
Reviewer checklist
Is the type of change in the PR title appropriate as per the changes?
Verified that there are no credentials or confidential data exposed with the changes.