Skip to content

fix(journey-client): create JourneyLoginFailure step, handle Login Failure case#574

Open
vatsalparikh wants to merge 3 commits intomainfrom
sdks-4796
Open

fix(journey-client): create JourneyLoginFailure step, handle Login Failure case#574
vatsalparikh wants to merge 3 commits intomainfrom
sdks-4796

Conversation

@vatsalparikh
Copy link
Copy Markdown
Contributor

@vatsalparikh vatsalparikh commented Apr 20, 2026

JIRA Ticket

https://pingidentity.atlassian.net/browse/SDKS-4796

Description

While working on the Journey Client migration, I noticed that when AM returns a failure response (e.g., unauthorized / invalid credentials), the Journey Client was returning a generic “no data” error and the LoginFailure path in createJourneyObject() was effectively never reached. This PR closes that gap by ensuring LoginFailure is triggered and a JourneyLoginFailure is returned when the server provides a failure payload with a code.

What changed

  • start() / next() now map RTK Query error responses that include a code into createJourneyObject(), which returns JourneyLoginFailure (hitting the previously-unreached LoginFailure branch).
  • Added unit coverage for the LoginFailure mapping.
  • Updated the journey-app e2e consumer to avoid throwing on LoginFailure and instead renders the LoginFailure error message.
  • Added a changeset for @forgerock/journey-client.

Edit

Ryan shared his closed PR that was trying to fix this issue: #541. Will use this as a reference.

How to test

  • Build and start the e2e/journey-app
  • Go to http://localhost:5829/?clientId=tenant and enter incorrect credentials
  • You should see 'Login Failure' with the change in this PR. When you remove the error handling logic from journey.api.ts file, you should see unknown node in console, which means login failure is not handled as a step.

Summary by CodeRabbit

  • Bug Fixes

    • Login failures containing error codes now properly return the correct failure type instead of a generic error response, enabling better error handling and user feedback.
  • UI Updates

    • Streamlined login failure error display by removing unnecessary form re-rendering, improving performance.

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Apr 20, 2026

🦋 Changeset detected

Latest commit: 3cce531

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 12 packages
Name Type
@forgerock/journey-client Patch
@forgerock/davinci-client Patch
@forgerock/device-client Patch
@forgerock/oidc-client Patch
@forgerock/protect Patch
@forgerock/sdk-types Patch
@forgerock/sdk-utilities Patch
@forgerock/iframe-manager Patch
@forgerock/sdk-logger Patch
@forgerock/sdk-oidc Patch
@forgerock/sdk-request-middleware Patch
@forgerock/storage Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 20, 2026

Warning

Rate limit exceeded

@vatsalparikh has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 58 minutes and 22 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 58 minutes and 22 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4c875689-564a-4677-b5a1-5d3d585d8014

📥 Commits

Reviewing files that changed from the base of the PR and between 16dd372 and 3cce531.

📒 Files selected for processing (5)
  • .changeset/whole-mangos-find.md
  • e2e/journey-app/main.ts
  • packages/journey-client/src/lib/client.store.test.ts
  • packages/journey-client/src/lib/client.store.ts
  • packages/journey-client/src/lib/journey.api.ts
📝 Walkthrough

Walkthrough

Client API and tests updated so that HTTP error responses containing an error payload with a Step object including a numeric code are treated as journey data (returning JourneyLoginFailure) instead of a generic error; UI handling for LoginFailure no longer re-renders the form.

Changes

Cohort / File(s) Summary
Journey API
packages/journey-client/src/lib/journey.api.ts
Treat certain error responses' error.data as successful Step results when errorData.code is in LOGIN_FAILURE_CODES, returning it as data from start/next.
Client store
packages/journey-client/src/lib/client.store.ts
Refactored start()/next() control flow to return createJourneyObject(data) only when data is truthy; otherwise return a GenericError object.
Tests
packages/journey-client/src/lib/client.store.test.ts
Extended mock fetch to parametrize authenticate status; added tests asserting code: 401 error body yields LoginFailure from start()/next(); forced Node Vitest env and added window.location shim for redirect test.
E2E UI
e2e/journey-app/main.ts
On step?.type === 'LoginFailure' in submit handler, removed renderForm() call so only renderError() runs.
Changesets / Docs
.changeset/journey-loginfailure-on-error-code.md, .changeset/polite-horses-dig.md
Added changeset entries documenting that JourneyLoginFailure is returned when failure payloads include a code field.

Sequence Diagram(s)

sequenceDiagram
    participant User as "User / UI"
    participant Client as "JourneyClient"
    participant Fetch as "fetch (network)"
    participant Server as "Auth Server"
    participant Renderer as "Renderer"

    User->>Client: start()/next(payload)
    Client->>Fetch: HTTP request
    Fetch->>Server: forward request
    Server-->>Fetch: 4xx response with error body { error: { data: Step{ code } } }
    Fetch-->>Client: error-shaped response
    alt error.data.code ∈ LOGIN_FAILURE_CODES
        Client->>Client: extract error.data as Step\nreturn JourneyLoginFailure
        Client->>Renderer: invoke renderError()
        Renderer-->>User: display login failure
    else otherwise
        Client->>Client: return GenericError
        Client->>Renderer: render generic error
        Renderer-->>User: display generic error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • ryanbas21
  • cerebrl
  • ancheetah
  • SteinGabriel

Poem

🐰 A hop, a sniff, a tiny cheer—
When server codes make danger near,
I fetch the truth from error's shell,
Return the step, and ring the bell.
LoginFailure hops in—speedy and clear!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and specifically describes the main changes: creating JourneyLoginFailure and handling the Login Failure case in journey-client.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The pull request description includes all required template sections with comprehensive details: JIRA ticket link, detailed description of the changes, what was modified, and testing instructions.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch sdks-4796

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nx-cloud
Copy link
Copy Markdown
Contributor

nx-cloud Bot commented Apr 20, 2026

View your CI Pipeline Execution ↗ for commit 3cce531

Command Status Duration Result
nx run-many -t build --no-agents ✅ Succeeded <1s View ↗
nx affected -t build lint test typecheck e2e-ci ✅ Succeeded 4m 56s View ↗

☁️ Nx Cloud last updated this comment at 2026-04-23 20:31:34 UTC

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
packages/journey-client/src/lib/client.store.test.ts (1)

265-277: Minor: globalThis.window is assigned but never cleaned up, and the initial defineProperty is redundant.

Two small points on the new shim:

  1. (globalThis as unknown as { window?: unknown }).window = {} leaks across tests within this file (no matching cleanup in afterEach). It happens to be benign today because this is the only test using window, but a future test run in any other order could observe a stray window global. Consider restoring it alongside locationSpy.mockRestore().
  2. The Object.defineProperty(window, 'location', { get: () => ({ assign: vi.fn() }) }) on lines 268–273 is immediately overridden by vi.spyOn(window, 'location', 'get').mockReturnValue(...) on line 274 — the inner assign: vi.fn() is never invoked, and the spread ...window.location on line 275 just reads the spied getter. Keeping only the defineProperty (so the property exists as a getter for spyOn to replace) with a minimal value, or dropping one of the two, would make the intent clearer.
♻️ Suggested cleanup
-    // Node test environment doesn't provide `window`, so create a minimal shim
-    // with a real `location` getter so we can keep using vi.spyOn(..., 'get').
-    (globalThis as unknown as { window?: unknown }).window = {};
-    Object.defineProperty(window, 'location', {
-      configurable: true,
-      get: () => ({
-        assign: vi.fn(),
-      }),
-    });
-    const locationSpy = vi.spyOn(window, 'location', 'get').mockReturnValue({
-      ...window.location,
-      assign: assignMock,
-    });
+    // Node test environment doesn't provide `window`, so create a minimal shim
+    // with a real `location` getter so we can keep using vi.spyOn(..., 'get').
+    (globalThis as unknown as { window: unknown }).window = {};
+    Object.defineProperty(window, 'location', {
+      configurable: true,
+      get: () => ({ assign: assignMock }),
+    });
+    const locationSpy = vi.spyOn(window, 'location', 'get');
     ...
     locationSpy.mockRestore();
+    delete (globalThis as unknown as { window?: unknown }).window;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/journey-client/src/lib/client.store.test.ts` around lines 265 - 277,
The test creates a global window shim and defines a getter for window.location
but never cleans up; modify the test to (1) make the minimal defineProperty for
window.location (so vi.spyOn can replace the getter) and remove the redundant
inner assign fn, and (2) restore the original state in afterEach by calling
locationSpy.mockRestore() and deleting or restoring globalThis.window (or saving
and reassigning the original window) so the global isn't leaked; reference the
locationSpy, assignMock and the temporary globalThis.window assignment when
updating the test.
packages/journey-client/src/lib/client.store.ts (1)

159-200: Consider extracting the error-mapping logic into a shared helper.

The start and next methods now contain near-identical blocks (lines 159–175 and 182–200) that unwrap { data, error }, map error.data with a defined code to createJourneyObject, and fall back to a GenericError with only the message string differing. Extracting a small helper (e.g., mapJourneyResult(result, fallbackMessage)) would remove the duplication and keep the two methods symmetric going forward.

Also, the errorData as Step | undefined cast is unchecked — if the server ever returns a non-object body (e.g., a string or HTML), errorStep?.code would still pass the optional-chain but could be against a non-Step shape. A narrow typeof errorData === 'object' && errorData !== null guard before the cast would be safer.

♻️ Proposed refactor
+    const mapResult = (
+      { data, error }: { data?: Step; error?: unknown },
+      fallbackMessage: string,
+    ): JourneyResult => {
+      if (data) {
+        return createJourneyObject(data);
+      }
+      const errorData = (error as FetchBaseQueryError | undefined)?.data;
+      if (typeof errorData === 'object' && errorData !== null) {
+        const errorStep = errorData as Step;
+        if (errorStep.code !== undefined) {
+          return createJourneyObject(errorStep);
+        }
+      }
+      return {
+        error: 'no_response_data',
+        message: fallbackMessage,
+        type: 'unknown_error',
+      };
+    };

Then start/next reduce to a single return mapResult(await store.dispatch(...), '...') call.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/journey-client/src/lib/client.store.ts` around lines 159 - 200,
Extract the duplicated error-unwrapping logic used in start and next into a
shared helper (e.g., mapJourneyResult or mapJourneyResponse) that accepts the
dispatch result and a fallback message; the helper should check for data and
return createJourneyObject(data) when present, then safely inspect error data by
first guarding typeof errorData === 'object' && errorData !== null before
treating it as a Step and returning createJourneyObject(errorStep) if
errorStep.code is defined, and finally return a GenericError object with the
provided fallbackMessage if neither path yields a Journey object—then replace
the duplicated blocks in start and next with a single call to this helper.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/journey-client/src/lib/client.store.test.ts`:
- Around line 265-277: The test creates a global window shim and defines a
getter for window.location but never cleans up; modify the test to (1) make the
minimal defineProperty for window.location (so vi.spyOn can replace the getter)
and remove the redundant inner assign fn, and (2) restore the original state in
afterEach by calling locationSpy.mockRestore() and deleting or restoring
globalThis.window (or saving and reassigning the original window) so the global
isn't leaked; reference the locationSpy, assignMock and the temporary
globalThis.window assignment when updating the test.

In `@packages/journey-client/src/lib/client.store.ts`:
- Around line 159-200: Extract the duplicated error-unwrapping logic used in
start and next into a shared helper (e.g., mapJourneyResult or
mapJourneyResponse) that accepts the dispatch result and a fallback message; the
helper should check for data and return createJourneyObject(data) when present,
then safely inspect error data by first guarding typeof errorData === 'object'
&& errorData !== null before treating it as a Step and returning
createJourneyObject(errorStep) if errorStep.code is defined, and finally return
a GenericError object with the provided fallbackMessage if neither path yields a
Journey object—then replace the duplicated blocks in start and next with a
single call to this helper.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3033ff09-5ae0-426f-9ba5-70f1baf0c83b

📥 Commits

Reviewing files that changed from the base of the PR and between 9088443 and bec0866.

📒 Files selected for processing (4)
  • .changeset/journey-loginfailure-on-error-code.md
  • e2e/journey-app/main.ts
  • packages/journey-client/src/lib/client.store.test.ts
  • packages/journey-client/src/lib/client.store.ts
💤 Files with no reviewable changes (1)
  • e2e/journey-app/main.ts

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented Apr 20, 2026

Open in StackBlitz

@forgerock/davinci-client

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/davinci-client@574

@forgerock/device-client

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/device-client@574

@forgerock/journey-client

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/journey-client@574

@forgerock/oidc-client

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/oidc-client@574

@forgerock/protect

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/protect@574

@forgerock/sdk-types

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/sdk-types@574

@forgerock/sdk-utilities

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/sdk-utilities@574

@forgerock/iframe-manager

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/iframe-manager@574

@forgerock/sdk-logger

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/sdk-logger@574

@forgerock/sdk-oidc

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/sdk-oidc@574

@forgerock/sdk-request-middleware

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/sdk-request-middleware@574

@forgerock/storage

pnpm add https://pkg.pr.new/ForgeRock/ping-javascript-sdk/@forgerock/storage@574

commit: 3cce531

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Apr 20, 2026

Codecov Report

❌ Patch coverage is 80.00000% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 15.72%. Comparing base (5d6747a) to head (3cce531).
⚠️ Report is 37 commits behind head on main.

Files with missing lines Patch % Lines
packages/journey-client/src/lib/client.store.ts 64.70% 6 Missing ⚠️

❌ Your project status has failed because the head coverage (15.72%) is below the target coverage (40.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff             @@
##             main     #574       +/-   ##
===========================================
- Coverage   70.90%   15.72%   -55.19%     
===========================================
  Files          53      154      +101     
  Lines        2021    26677    +24656     
  Branches      377     1132      +755     
===========================================
+ Hits         1433     4194     +2761     
- Misses        588    22483    +21895     
Files with missing lines Coverage Δ
packages/journey-client/src/lib/journey.api.ts 69.48% <100.00%> (+2.81%) ⬆️
packages/journey-client/src/lib/client.store.ts 80.22% <64.70%> (+6.84%) ⬆️

... and 100 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 20, 2026

Deployed 6ae11ee to https://ForgeRock.github.io/ping-javascript-sdk/pr-574/6ae11ee617b4e7edd176b4141f005819912238b0 branch gh-pages in ForgeRock/ping-javascript-sdk

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 20, 2026

📦 Bundle Size Analysis

📦 Bundle Size Analysis

🚨 Significant Changes

🔻 @forgerock/device-client - 0.0 KB (-9.9 KB, -100.0%)
🔻 @forgerock/journey-client - 0.0 KB (-89.9 KB, -100.0%)

📊 Minor Changes

📉 @forgerock/device-client - 9.9 KB (-0.0 KB)
📉 @forgerock/davinci-client - 48.0 KB (-0.0 KB)
📈 @forgerock/journey-client - 90.3 KB (+0.3 KB)

➖ No Changes

@forgerock/oidc-client - 25.2 KB
@forgerock/sdk-utilities - 11.2 KB
@forgerock/sdk-types - 7.9 KB
@forgerock/protect - 150.1 KB
@forgerock/storage - 1.5 KB
@forgerock/sdk-oidc - 4.8 KB
@forgerock/sdk-request-middleware - 4.5 KB
@forgerock/sdk-logger - 1.6 KB
@forgerock/iframe-manager - 2.4 KB


14 packages analyzed • Baseline from latest main build

Legend

🆕 New package
🔺 Size increased
🔻 Size decreased
➖ No change

ℹ️ How bundle sizes are calculated
  • Current Size: Total gzipped size of all files in the package's dist directory
  • Baseline: Comparison against the latest build from the main branch
  • Files included: All build outputs except source maps and TypeScript build cache
  • Exclusions: .map, .tsbuildinfo, and .d.ts.map files

🔄 Updated automatically on each push to this PR

Copy link
Copy Markdown

@SteinGabriel SteinGabriel left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor findings.

Comment thread packages/journey-client/src/lib/client.store.ts Outdated
Comment thread packages/journey-client/src/lib/client.store.test.ts Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/journey-client/src/lib/journey.api.ts (1)

139-202: Extract the duplicated login-failure mapping into a helper.

The blocks at lines 139-155 and 186-202 are identical. Consider extracting into a small helper to reduce drift risk when the set of failure codes or the shape handling evolves.

♻️ Proposed refactor
+function mapLoginFailureResponse(
+  response: QueryReturnValue<unknown, FetchBaseQueryError, FetchBaseQueryMeta>,
+): QueryReturnValue<Step, FetchBaseQueryError, FetchBaseQueryMeta> {
+  if ('error' in response) {
+    const errorData = (response.error as FetchBaseQueryError | undefined)?.data as
+      | Step
+      | undefined;
+    if (errorData?.code && LOGIN_FAILURE_CODES.includes(errorData.code)) {
+      return { data: errorData };
+    }
+  }
+  return response as QueryReturnValue<Step, FetchBaseQueryError, FetchBaseQueryMeta>;
+}

Then use return mapLoginFailureResponse(response); in both start and next.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/journey-client/src/lib/journey.api.ts` around lines 139 - 202,
Extract the duplicated login-failure mapping into a small helper (e.g.
mapLoginFailureResponse) that accepts the endpoint response and returns a
QueryReturnValue<Step, FetchBaseQueryError, FetchBaseQueryMeta> when the
response body is a Step with a code in LOGIN_FAILURE_CODES, or undefined/falsey
otherwise; move the logic that inspects ('error' in response), casts to
(response.error as FetchBaseQueryError)?.data as Step, checks data.code and
LOGIN_FAILURE_CODES into this helper, then replace the duplicated blocks in both
the start and next builder handlers with a single call like: return
mapLoginFailureResponse(response) ?? (continue with existing return).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/journey-client/src/lib/journey.api.ts`:
- Around line 139-202: Extract the duplicated login-failure mapping into a small
helper (e.g. mapLoginFailureResponse) that accepts the endpoint response and
returns a QueryReturnValue<Step, FetchBaseQueryError, FetchBaseQueryMeta> when
the response body is a Step with a code in LOGIN_FAILURE_CODES, or
undefined/falsey otherwise; move the logic that inspects ('error' in response),
casts to (response.error as FetchBaseQueryError)?.data as Step, checks data.code
and LOGIN_FAILURE_CODES into this helper, then replace the duplicated blocks in
both the start and next builder handlers with a single call like: return
mapLoginFailureResponse(response) ?? (continue with existing return).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2d2a0334-1d00-4e63-85af-4145e953a6d4

📥 Commits

Reviewing files that changed from the base of the PR and between bec0866 and 16dd372.

📒 Files selected for processing (4)
  • .changeset/polite-horses-dig.md
  • packages/journey-client/src/lib/client.store.test.ts
  • packages/journey-client/src/lib/client.store.ts
  • packages/journey-client/src/lib/journey.api.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/journey-client/src/lib/client.store.ts
  • .changeset/polite-horses-dig.md

Copy link
Copy Markdown

@SteinGabriel SteinGabriel left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look great! Everything worked as expected when I tested it locally. Just need to update a stale copyright date.

Comment thread packages/journey-client/src/lib/journey.api.ts Outdated
Copy link
Copy Markdown
Collaborator

@cerebrl cerebrl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left some alternative thoughts on this solution.

Comment on lines +157 to +166
if (data) {
return createJourneyObject(data);
}
return createJourneyObject(data);

const genericError: GenericError = {
error: 'no_response_data',
message: 'No data received from server when starting journey',
type: 'unknown_error',
};
return genericError;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this just a stylistic change, or was there a functional reason for it? I ask because we have the pattern of error conditions first, then operate with success condition last. This would break that pattern.

Comment on lines +174 to +183
if (data) {
return createJourneyObject(data);
}
return createJourneyObject(data);

const genericError: GenericError = {
error: 'no_response_data',
message: 'No data received from server when submitting step',
type: 'unknown_error',
};
return genericError;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here. Doing success last, rather than first, helps narrow types and sometimes prevents complex conditionals and nesting.

Comment on lines +139 to +143
/**
* If the endpoint returned an HTTP error whose body is an AM Step with a
* login-failure code, treat it as successful data so callers receive the
* Step via the `data` path (keeps downstream logic simpler).
*/
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit worried about tightly coupling our understanding of "true errors" to validation or authentication errors by relying solely on the error code. The logic we use in the original SDK was much more "liberal". It essentially treated all errors as FRLoginFailure: https://github.com/ForgeRock/forgerock-javascript-sdk/blob/develop/packages/javascript-sdk/src/fr-auth/index.ts#L76.

Rather than doing all of this logic here, we could grab error from this destructure: https://github.com/ForgeRock/ping-javascript-sdk/blob/main/packages/journey-client/src/lib/client.store.ts#L174, and pass it to createJourneyObject here: https://github.com/ForgeRock/ping-javascript-sdk/blob/main/packages/journey-client/src/lib/client.store.ts#L183. Finally, just handle the logic here: https://github.com/ForgeRock/ping-javascript-sdk/blob/main/packages/journey-client/src/lib/journey.utils.ts#L28.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

4 participants