gitlab4j-api icon indicating copy to clipboard operation
gitlab4j-api copied to clipboard

Use generics in globalsearch

Open exaV opened this issue 1 year ago • 2 comments

globalSearch currently returns a wildcard which always requires a cast afterwards, even though the return type is known for each SearchScope.

List<?> projects = gitLabApi.getSearchApi().globalSearch(SearchScope.PROJECTS, "text-to-search-for");

Ideally we would have a generic return type, based on SearchScope:

List<Project> projects = gitLabApi.getSearchApi().globalSearch(SearchScope.PROJECTS, "text-to-search-for")

SearchScope is currently defined as an enum which makes it impossible to use generics. We could convert it to class with static members to be able to use the same syntax and profit from generics.

   // with this definition the above usage of globalSearch compiles:

    public <T> Pager<T> globalSearch(SearchScope<T> scope, String search, int itemsPerPage) {
        // ...
        switch (scope) {
            case BLOBS:
                return (new Pager<>(this, scope.getResultType(), itemsPerPage, formData.asMap(), "search"));
         // ...
       }
    }

    public static class SearchScope<T> {
        private SearchScope(Class<T> resultType, String jsonName) {
        }
        
        public static final SearchScope<Project> PROJECTS = new SearchScope<>(Project.class, "projects");
        public static final SearchScope<SearchBlob> BLOBS = new SearchScope<>(SearchBlob.class, "blobs");
        
       // JsonCreator, JsonValue and ToString can be implemented using the `jsonName` field
    }

This would be a breaking change because code will have to be recompiled, although there should be no changes necessary on the users side.

exaV avatar Jun 25 '24 10:06 exaV

Let me know if you'd like a PR for that

exaV avatar Jun 25 '24 13:06 exaV

I think the change is a good idea.

About the breaking change, if this works for you, maybe we do this only on the 6.x branch.

jmini avatar Jul 01 '24 13:07 jmini