Skip to content

Support passing name filter to ListStores#586

Merged
rhamzeh merged 9 commits intoopenfga:mainfrom
Oscmage:passing-name-filter-list-stores
Sep 4, 2025
Merged

Support passing name filter to ListStores#586
rhamzeh merged 9 commits intoopenfga:mainfrom
Oscmage:passing-name-filter-list-stores

Conversation

@Oscmage
Copy link
Contributor

@Oscmage Oscmage commented Aug 8, 2025

My original idea was to address this only for the Go SDK to support passing the name filter but it had cascading effects due to having to update the OpenAPI schema which is used by all clients (ofc).

Hence, this PR is updating the schema and making sure that all clients are compatible.

See related issue here: openfga/go-sdk#186

The failure for shellcheck seems unrelated to this PR and is also happening on main. To not make the scope of this PR even larger I've not addressed that here.

Here is the follow up PR for the Go SDK which is what I originally fixed: openfga/go-sdk#213

Summary by CodeRabbit

  • New Features

    • Added support for filtering stores by name when listing stores in Go, Java, and JavaScript/TypeScript client libraries.
    • Enhanced example and documentation to demonstrate store name filtering.
  • Bug Fixes

    • None.
  • Tests

    • Added new test cases in Go, Java, and JavaScript/TypeScript clients to verify listing stores with a name filter.
  • Chores

    • Updated OpenAPI specification reference used in the build process.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This change adds support for filtering stores by name in the ListStores API across Go, Java, and JavaScript client SDKs. It introduces a new name filter option, updates method signatures, modifies client and test code, and updates the OpenAPI reference to ensure compatibility with the new filter parameter.

Changes

Cohort / File(s) Change Summary
Go Client: Add name filter to ListStores
config/clients/go/template/client/client.mustache, config/clients/go/template/client/client_test.mustache, config/clients/go/template/README_calling_api.mustache, config/clients/go/template/example/example1/example1.go
Adds a Name field to ClientListStoresOptions, updates ListStoresExecute to support the filter, adds helper function, updates usage examples, and adds a test for name filtering.
Java Client: Add name filter to ListStores
config/clients/java/template/src/main/api/client/OpenFgaClient.java.mustache, config/clients/java/template/src/main/api/configuration/ClientListStoresOptions.java.mustache, config/clients/java/template/src/test/api/OpenFgaApiTest.java.mustache, config/clients/java/template/src/test/api/client/OpenFgaClientTest.java.mustache, config/clients/java/template/src/test-integration/api/OpenFgaApiIntegrationTest.java.mustache
Adds a name field and getter/setter to options, updates client methods to accept the new parameter, and adds/updates tests for name filtering.
JavaScript Client: Add name filter to ListStores
config/clients/js/template/client.mustache, config/clients/js/template/tests/client.test.ts.mustache, config/clients/js/template/tests/helpers/nocks.ts.mustache
Extends PaginationOptions with name, updates client and API calls, adds tests for name filtering, and updates mocking helpers to support query parameters.
OpenAPI Reference Update
Makefile
Updates the OpenAPI spec reference to a newer commit hash to ensure compatibility with the new name filter parameter.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ClientSDK (Go/Java/JS)
    participant API

    User->>ClientSDK (Go/Java/JS): ListStores({ name: "My Store" })
    ClientSDK (Go/Java/JS)->>API: GET /stores?name=My%20Store
    API-->>ClientSDK (Go/Java/JS): ListStoresResponse (filtered)
    ClientSDK (Go/Java/JS)-->>User: Filtered list of stores
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Oscmage Oscmage marked this pull request as ready for review August 8, 2025 20:51
@Oscmage Oscmage requested a review from a team as a code owner August 8, 2025 20:51
Copy link
Contributor

@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.

Actionable comments posted: 2

🧹 Nitpick comments (9)
config/clients/java/template/src/main/api/configuration/ClientListStoresOptions.java.mustache (1)

40-47: Optional: add brief Javadoc for name filter semantics

A one-liner noting whether matching is exact/prefix/substring (per API behavior) will help users.

config/clients/go/template/example/example1/example1.go (1)

71-80: LGTM; minor consistency nit on field access

To match earlier usage (Line 50) and avoid mixing styles, prefer GetStores() when printing the count.

-	fmt.Printf("Stores with name filter Count: %d\n", len(storesWithFilter.Stores))
+	fmt.Printf("Stores with name filter Count: %d\n", len(storesWithFilter.GetStores()))
config/clients/java/template/src/test/api/OpenFgaApiTest.java.mustache (1)

101-123: Good addition; please also cover URL-encoding and mixed query params

This verifies name=... works. Consider:

  • Add a case where name contains spaces/special chars to ensure proper encoding.
  • Add a case combining pageSize, continuationToken, and name to verify query construction (and a stable param order if the mock requires exact string matching).

Example (encoding-focused) snippet you could add:

@Test
public void listStoresTest_withNameFilter_specialChars() throws Exception {
    String storeName = "team work+demo";
    String encoded = java.net.URLEncoder.encode(storeName, java.nio.charset.StandardCharsets.UTF_8);
    String responseBody = String.format("{\"stores\":[{\"id\":\"%s\",\"name\":\"%s\"}]}", DEFAULT_STORE_ID, storeName);
    mockHttpClient.onGet("https://api.fga.example/stores?name=" + encoded).doReturn(200, responseBody);

    var response = fga.listStores(null, null, storeName).get();

    mockHttpClient.verify().get("https://api.fga.example/stores?name=" + encoded).called(1);
    assertEquals(storeName, response.getData().getStores().get(0).getName());
}
config/clients/java/template/src/test/api/client/OpenFgaClientTest.java.mustache (1)

288-308: Solid coverage for name filter; add mixed-params and encoding cases

  • Add a test combining name with page_size and continuation_token (ensures the client merges all query params correctly).
  • Add an encoding test (e.g., spaces, plus, slash) to ensure URL encoding matches expectations.

Note: if the mock requires exact query order, ensure the client uses a deterministic order or adjust assertions accordingly.

Makefile (1)

247-250: CI: shellcheck target failing (acknowledged as unrelated in PR)

Non-blocking here, but if you want, I can help by running shellcheck locally and proposing fixes or suppressions in a follow-up PR.

config/clients/go/template/client/client_test.mustache (1)

210-256: Good test for name filter; consider combo and encoding edge cases

  • Add a combined options test to ensure name + page_size + continuation_token are all sent.
  • Add an encoding test (e.g., “Team A+B/Trial”) and assert req.URL.Query().Get("name") matches the expected literal decoded value (httpmock compares decoded query params) and that page_size/continuation_token are present.

Example outline:

t.Run("ListStoresWithNameAndOptions", func(t *testing.T) {
    filtered := "Team A+B/Trial"
    test := TestDefinition{ /* ... */ }
    var expectedResponse openfga.ListStoresResponse
    _ = json.Unmarshal([]byte(test.JsonResponse), &expectedResponse)

    httpmock.Activate()
    defer httpmock.DeactivateAndReset()
    httpmock.RegisterResponder(test.Method, fmt.Sprintf("%s/stores", fgaClient.GetConfig().ApiUrl),
        func(req *http.Request) (*http.Response, error) {
            q := req.URL.Query()
            if q.Get("name") != filtered {
                t.Fatalf("expected name=%q, got %q", filtered, q.Get("name"))
            }
            if q.Get("page_size") != "5" || q.Get("continuation_token") != "ctok" {
                t.Fatalf("missing/invalid page_size or continuation_token")
            }
            return httpmock.NewJsonResponse(test.ResponseStatus, expectedResponse)
        })

    opts := ClientListStoresOptions{
        Name: openfga.PtrString(filtered),
        PageSize: openfga.PtrInt32(5),
        ContinuationToken: openfga.PtrString("ctok"),
    }
    _, err := fgaClient.ListStores(context.Background()).Options(opts).Execute()
    if err != nil { t.Fatalf("%v", err) }
})
config/clients/js/template/tests/helpers/nocks.ts.mustache (1)

59-66: Support query params robustly by stripping undefined keys before matching

If any callers pass { name: undefined } (or similar), nock’s strict .query(obj) will fail. Filter keys first to avoid brittle tests.

Apply within this hunk:

-  ) => {
-    const mock = nock(basePath).get("/stores");
-    if (queryParams) {
-      mock.query(queryParams);
-    }
-    return mock.reply(responseCode, response);
-  },
+  ) => {
+    const mock = nock(basePath).get("/stores");
+    if (queryParams) {
+      const qp = Object.fromEntries(
+        Object.entries(queryParams).filter(([, v]) => v !== undefined)
+      );
+      if (Object.keys(qp).length) {
+        mock.query(qp);
+      }
+    }
+    return mock.reply(responseCode, response);
+  },
config/clients/js/template/client.mustache (1)

119-119: Avoid leaking endpoint-specific fields into a shared PaginationOptions

Adding name to the globally reused PaginationOptions couples unrelated endpoints to a ListStores-specific filter. Prefer a dedicated type to keep semantics clean.

Example:

-export type PaginationOptions = { pageSize?: number, continuationToken?: string, name?: string; };
+export type PaginationOptions = { pageSize?: number, continuationToken?: string };
+export type ListStoresOptions = ClientRequestOpts & PaginationOptions & { name?: string };

And update the signature accordingly:

-async listStores(options: ClientRequestOptsWithAuthZModelId & PaginationOptions = {}): PromiseResult<ListStoresResponse> {
-  return this.api.listStores(options.pageSize, options.continuationToken, options.name, options);
+async listStores(options: ListStoresOptions = {}): PromiseResult<ListStoresResponse> {
+  return this.api.listStores(options.pageSize, options.continuationToken, options.name, options);
}
config/clients/go/template/client/client.mustache (1)

607-618: Wires pagination and name filters correctly into the request builder

Conditional application of PageSize, ContinuationToken, and Name is correct and idiomatic for the generated request pattern.

Optional: for stylistic consistency with other methods using pagination helpers, you could reuse ClientPaginationOptions and existing getters to reduce duplicate patterns, but not required.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a3946d3 and 1906d5c.

📒 Files selected for processing (13)
  • Makefile (1 hunks)
  • config/clients/go/template/README_calling_api.mustache (1 hunks)
  • config/clients/go/template/client/client.mustache (3 hunks)
  • config/clients/go/template/client/client_test.mustache (2 hunks)
  • config/clients/go/template/example/example1/example1.go (1 hunks)
  • config/clients/java/template/src/main/api/client/OpenFgaClient.java.mustache (2 hunks)
  • config/clients/java/template/src/main/api/configuration/ClientListStoresOptions.java.mustache (2 hunks)
  • config/clients/java/template/src/test-integration/api/OpenFgaApiIntegrationTest.java.mustache (2 hunks)
  • config/clients/java/template/src/test/api/OpenFgaApiTest.java.mustache (5 hunks)
  • config/clients/java/template/src/test/api/client/OpenFgaClientTest.java.mustache (1 hunks)
  • config/clients/js/template/client.mustache (2 hunks)
  • config/clients/js/template/tests/client.test.ts.mustache (1 hunks)
  • config/clients/js/template/tests/helpers/nocks.ts.mustache (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Run Tests
Makefile

[error] Makefile target 'shellcheck' failed with exit code 1.

🔇 Additional comments (13)
config/clients/java/template/src/main/api/configuration/ClientListStoresOptions.java.mustache (1)

10-10: Add name filter option: LGTM

Field and fluent setter/getter align with the new API filter and existing style in this class. No concerns.

Also applies to: 40-47

config/clients/java/template/src/test-integration/api/OpenFgaApiIntegrationTest.java.mustache (1)

78-78: Test signature update for listStores: LGTM

Passing null for the new optional name param maintains previous behavior and keeps tests backward compatible.

Also applies to: 109-109

config/clients/js/template/tests/client.test.ts.mustache (1)

103-121: Add test for name filter on ListStores: LGTM

Covers query param propagation and response handling. Scope assertions ensure the filter was applied.

config/clients/java/template/src/test/api/OpenFgaApiTest.java.mustache (2)

89-89: Signature update LGTM

Passing null as the third arg (name) aligns with the updated method signature and preserves the no-filter path.


135-136: Error-path tests updated for the new signature

Using the third null parameter keeps these cases consistent with the new API.

Also applies to: 158-159, 180-181

Makefile (1)

3-3: OpenAPI ref bumped; ‘name’ query parameter for GET /stores is confirmed present

Verified that the OpenAPI spec at commit e53c69cc55317404d02a6d8e418d626268f28a59 includes an optional name query parameter for the GET /stores endpoint:

  • Check returned true.
  • Parameter schema:
{
  "name": "name",
  "description": "The name parameter instructs the API to only include results that match that name. Multiple results may be returned. Only exact matches will be returned; substring matches and regexes will not be evaluated",
  "in": "query",
  "required": false,
  "type": "string"
}

No further changes required.

config/clients/go/template/client/client_test.mustache (1)

15-15: Import alias for root package is clear

Using the openfga alias improves readability and avoids symbol conflicts with the client package.

config/clients/js/template/client.mustache (2)

303-303: JSDoc addition for name filter looks good

Docstring clearly describes the new name filter.


311-311: Parameter order confirmed in client.mustache

The call

return this.api.listStores(
  options.pageSize,
  options.continuationToken,
  options.name,
  options
);

matches the generated OpenAPI signature (pageSize, continuationToken, name, options). No inconsistencies were found in the template or accompanying examples/tests.

config/clients/java/template/src/main/api/client/OpenFgaClient.java.mustache (2)

86-89: Correctly threads name filter through to the API

options.getName() is inserted before overrides, matching the new signature and preserving headers handling.


75-78: Ignore the override‐parameter suggestion for the no‐arg listStores

The no-arg listStores() method intentionally invokes the three-argument overload
api.listStores(null, null, null), which matches the generated OpenFgaApi#listStores(pageSize, continuationToken, name) signature (as confirmed by the existing raw‐API tests). Configuration overrides are only applied when options are provided. No changes are required.

Likely an incorrect or invalid review comment.

config/clients/go/template/client/client.mustache (2)

169-174: Continuation token helper is fine

No behavior change; helper remains consistent with the page size accessor.


580-584: Add Name to ClientListStoresOptions: LGTM

Optional Name with json:"name,omitempty" is correct and matches query param usage.

@Oscmage Oscmage requested a review from rhamzeh August 18, 2025 13:09
Copy link
Member

@rhamzeh rhamzeh left a comment

Choose a reason for hiding this comment

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

Thanks @Oscmage ❤️

@rhamzeh rhamzeh enabled auto-merge September 4, 2025 17:29
@rhamzeh rhamzeh added this pull request to the merge queue Sep 4, 2025
Merged via the queue into openfga:main with commit 6442485 Sep 4, 2025
20 of 21 checks passed
@Oscmage Oscmage deleted the passing-name-filter-list-stores branch September 5, 2025 21:16
@dyeam0 dyeam0 linked an issue Oct 30, 2025 that may be closed by this pull request
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support List Stores name filter

2 participants