forked from BroadleafCommerce/BroadleafCommerce
-
Notifications
You must be signed in to change notification settings - Fork 0
Add GraphQL support: foundation and catalog query resolvers #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
devin-ai-integration
wants to merge
7
commits into
develop-7.0.x
Choose a base branch
from
devin/1776896218-graphql-catalog-foundation
base: develop-7.0.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ac78b9b
Add GraphQL support: foundation and catalog resolvers
devin-ai-integration[bot] ebf832b
Address Devin Review: bind WebRequest to BRC; stop leaking internal e…
devin-ai-integration[bot] 8504ee2
Address Devin Review: nest customer under blRuleMap; nullable Integer…
devin-ai-integration[bot] 2f17031
Address Devin Review: ensure anonymous fallback + strict Long validation
devin-ai-integration[bot] fe6ac6f
Address Devin Review: propagate search errors to GraphQL exception re…
devin-ai-integration[bot] ea2e0a9
Address Devin Review: guard null WebRequest and reject non-page-align…
devin-ai-integration[bot] 8caca98
Address Devin Review: check additionalProperties in ensureCustomerCon…
devin-ai-integration[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
236 changes: 236 additions & 0 deletions
236
...k-web/src/main/java/org/broadleafcommerce/core/web/graphql/GraphQLContextInterceptor.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,236 @@ | ||
| /*- | ||
| * #%L | ||
| * BroadleafCommerce Framework Web | ||
| * %% | ||
| * Copyright (C) 2009 - 2026 Broadleaf Commerce | ||
| * %% | ||
| * Licensed under the Broadleaf Fair Use License Agreement, Version 1.0 | ||
| * (the "Fair Use License" located at http://license.broadleafcommerce.org/fair_use_license-1.0.txt) | ||
| * unless the restrictions on use therein are violated and require payment to Broadleaf in which case | ||
| * the Broadleaf End User License Agreement (EULA), Version 1.1 | ||
| * (the "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt) | ||
| * shall apply. | ||
| * | ||
| * Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the "Custom License") | ||
| * between you and Broadleaf Commerce. You may not use this file except in compliance with the applicable license. | ||
| * #L% | ||
| */ | ||
| package org.broadleafcommerce.core.web.graphql; | ||
|
|
||
| import org.apache.commons.logging.Log; | ||
| import org.apache.commons.logging.LogFactory; | ||
| import org.broadleafcommerce.common.util.StringUtil; | ||
| import org.broadleafcommerce.common.web.BroadleafRequestContext; | ||
| import org.broadleafcommerce.profile.core.domain.Customer; | ||
| import org.broadleafcommerce.profile.core.service.CustomerService; | ||
| import org.broadleafcommerce.profile.web.core.CustomerState; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.beans.factory.annotation.Qualifier; | ||
| import org.springframework.graphql.server.WebGraphQlInterceptor; | ||
| import org.springframework.graphql.server.WebGraphQlRequest; | ||
| import org.springframework.graphql.server.WebGraphQlResponse; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.context.request.RequestContextHolder; | ||
| import org.springframework.web.context.request.ServletRequestAttributes; | ||
| import org.springframework.web.context.request.ServletWebRequest; | ||
| import org.springframework.web.context.request.WebRequest; | ||
| import reactor.core.publisher.Mono; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| * A {@link WebGraphQlInterceptor} that populates Broadleaf customer context for incoming | ||
| * GraphQL requests. It mirrors the identity resolution pattern used by | ||
| * {@link org.broadleafcommerce.profile.web.core.security.RestApiCustomerStateFilter}: | ||
| * look for a {@code customerId} header or query parameter, load the customer when numeric, | ||
| * and populate {@link CustomerState}. When no customer can be resolved, an anonymous | ||
| * customer is created so downstream resolvers always see a valid customer context. | ||
| */ | ||
| @Component("blGraphQLContextInterceptor") | ||
| public class GraphQLContextInterceptor implements WebGraphQlInterceptor { | ||
|
|
||
| public static final String CUSTOMER_ID_ATTRIBUTE = "customerId"; | ||
| public static final String BLC_RULE_MAP_PARAM = "blRuleMap"; | ||
|
|
||
| protected static final Log LOG = LogFactory.getLog(GraphQLContextInterceptor.class); | ||
|
|
||
| @Autowired | ||
| @Qualifier("blCustomerService") | ||
| protected CustomerService customerService; | ||
|
|
||
| @Override | ||
| public Mono<WebGraphQlResponse> intercept(WebGraphQlRequest request, Chain chain) { | ||
| try { | ||
| populateCustomerContext(request); | ||
| } catch (Exception ex) { | ||
| LOG.warn("Failed to populate customer context for GraphQL request", ex); | ||
| } | ||
| ensureCustomerContext(); | ||
| return chain.next(request); | ||
| } | ||
|
|
||
| protected void populateCustomerContext(WebGraphQlRequest request) { | ||
| ensureBroadleafRequestContext(); | ||
|
|
||
| if (CustomerState.getCustomer() != null) { | ||
| return; | ||
| } | ||
|
|
||
| String customerId = resolveCustomerId(request); | ||
| if (customerId == null || customerId.trim().isEmpty()) { | ||
| return; | ||
| } | ||
| if (!isValidLong(customerId)) { | ||
| LOG.warn(String.format("The customer id passed in '%s' was not a number", | ||
| StringUtil.sanitize(customerId))); | ||
| return; | ||
| } | ||
| Customer customer = customerService.readCustomerById(Long.valueOf(customerId)); | ||
| if (customer != null) { | ||
| applyCustomer(customer); | ||
| } | ||
| } | ||
|
|
||
| protected void ensureCustomerContext() { | ||
| if (hasResolvedCustomer()) { | ||
| return; | ||
| } | ||
| try { | ||
| ensureBroadleafRequestContext(); | ||
| Customer anonymousCustomer = customerService.createCustomer(); | ||
| applyCustomer(anonymousCustomer); | ||
| } catch (Exception ex) { | ||
| LOG.warn("Failed to create anonymous customer for GraphQL request", ex); | ||
| } | ||
| } | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
|
||
|
|
||
| /** | ||
| * Returns {@code true} when a customer has already been attached to the current request, | ||
| * either via {@link CustomerState} (servlet transport) or via {@link BroadleafRequestContext} | ||
| * {@code additionalProperties} (non-servlet transports such as WebSocket GraphQL). | ||
| */ | ||
| protected boolean hasResolvedCustomer() { | ||
| if (CustomerState.getCustomer() != null) { | ||
| return true; | ||
| } | ||
| BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext(); | ||
| if (brc == null) { | ||
| return false; | ||
| } | ||
| Map<String, Object> additional = brc.getAdditionalProperties(); | ||
| return additional != null && additional.get("customer") != null; | ||
| } | ||
|
|
||
| /** | ||
| * Binds the customer to the current request context. {@link CustomerState#setCustomer(Customer)} | ||
| * requires a {@link WebRequest} on the {@link BroadleafRequestContext}; for transports where no | ||
| * servlet request is bound (e.g., WebSocket GraphQL), we fall back to storing the customer directly | ||
| * in {@code additionalProperties} so downstream resolvers can still retrieve it via | ||
| * {@link BroadleafRequestContext}. | ||
| */ | ||
| protected void applyCustomer(Customer customer) { | ||
| BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext(); | ||
| if (brc != null && brc.getWebRequest() != null) { | ||
| CustomerState.setCustomer(customer); | ||
| } else { | ||
| if (brc == null) { | ||
| brc = new BroadleafRequestContext(); | ||
| BroadleafRequestContext.setBroadleafRequestContext(brc); | ||
| } | ||
| Map<String, Object> additional = brc.getAdditionalProperties(); | ||
| if (additional == null) { | ||
| additional = new HashMap<>(); | ||
| brc.setAdditionalProperties(additional); | ||
| } | ||
| additional.put("customer", customer); | ||
| LOG.debug("No WebRequest bound to BroadleafRequestContext; " | ||
| + "customer stored in additionalProperties for GraphQL request"); | ||
| } | ||
| setupCustomerForRuleProcessing(customer); | ||
| } | ||
|
|
||
| protected boolean isValidLong(String value) { | ||
| if (value == null) { | ||
| return false; | ||
| } | ||
| try { | ||
| Long.parseLong(value); | ||
| return true; | ||
| } catch (NumberFormatException ex) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| protected String resolveCustomerId(WebGraphQlRequest request) { | ||
| String customerId = request.getHeaders().getFirst(CUSTOMER_ID_ATTRIBUTE); | ||
| if (customerId != null) { | ||
| return customerId; | ||
| } | ||
| String query = request.getUri() != null ? request.getUri().getQuery() : null; | ||
| if (query == null) { | ||
| return null; | ||
| } | ||
| for (String pair : query.split("&")) { | ||
| int idx = pair.indexOf('='); | ||
| if (idx > 0 && CUSTOMER_ID_ATTRIBUTE.equals(pair.substring(0, idx))) { | ||
| return pair.substring(idx + 1); | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| protected void ensureBroadleafRequestContext() { | ||
| BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext(); | ||
| if (brc == null) { | ||
| brc = new BroadleafRequestContext(); | ||
| BroadleafRequestContext.setBroadleafRequestContext(brc); | ||
| } | ||
| if (brc.getWebRequest() == null) { | ||
| WebRequest webRequest = resolveWebRequest(); | ||
| if (webRequest != null) { | ||
| brc.setWebRequest(webRequest); | ||
| } | ||
| } | ||
| } | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
|
||
|
|
||
| protected WebRequest resolveWebRequest() { | ||
| try { | ||
| if (RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attrs) { | ||
| return new ServletWebRequest(attrs.getRequest(), attrs.getResponse()); | ||
| } | ||
| } catch (IllegalStateException ignored) { | ||
| // No servlet request bound to this thread; fall through | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| protected void setupCustomerForRuleProcessing(Customer customer) { | ||
| BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext(); | ||
| if (brc == null) { | ||
| return; | ||
| } | ||
| if (brc.getRequest() != null) { | ||
| Map<String, Object> ruleMap = (Map<String, Object>) brc.getRequest() | ||
| .getAttribute(BLC_RULE_MAP_PARAM); | ||
| if (ruleMap == null) { | ||
| ruleMap = new HashMap<>(); | ||
| } | ||
| ruleMap.put("customer", customer); | ||
| brc.getRequest().setAttribute(BLC_RULE_MAP_PARAM, ruleMap); | ||
| return; | ||
| } | ||
| Map<String, Object> additional = brc.getAdditionalProperties(); | ||
| if (additional == null) { | ||
| additional = new HashMap<>(); | ||
| brc.setAdditionalProperties(additional); | ||
| } | ||
| Map<String, Object> ruleMap = (Map<String, Object>) additional.get(BLC_RULE_MAP_PARAM); | ||
| if (ruleMap == null) { | ||
| ruleMap = new HashMap<>(); | ||
| additional.put(BLC_RULE_MAP_PARAM, ruleMap); | ||
| } | ||
| ruleMap.put("customer", customer); | ||
| } | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
|
||
| } | ||
85 changes: 85 additions & 0 deletions
85
...rk-web/src/main/java/org/broadleafcommerce/core/web/graphql/GraphQLExceptionResolver.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| /*- | ||
| * #%L | ||
| * BroadleafCommerce Framework Web | ||
| * %% | ||
| * Copyright (C) 2009 - 2026 Broadleaf Commerce | ||
| * %% | ||
| * Licensed under the Broadleaf Fair Use License Agreement, Version 1.0 | ||
| * (the "Fair Use License" located at http://license.broadleafcommerce.org/fair_use_license-1.0.txt) | ||
| * unless the restrictions on use therein are violated and require payment to Broadleaf in which case | ||
| * the Broadleaf End User License Agreement (EULA), Version 1.1 | ||
| * (the "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt) | ||
| * shall apply. | ||
| * | ||
| * Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the "Custom License") | ||
| * between you and Broadleaf Commerce. You may not use this file except in compliance with the applicable license. | ||
| * #L% | ||
| */ | ||
| package org.broadleafcommerce.core.web.graphql; | ||
|
|
||
| import graphql.GraphQLError; | ||
| import graphql.GraphqlErrorBuilder; | ||
| import graphql.schema.DataFetchingEnvironment; | ||
| import org.broadleafcommerce.core.offer.service.exception.OfferMaxUseExceededException; | ||
| import org.broadleafcommerce.core.order.service.exception.AddToCartException; | ||
| import org.broadleafcommerce.core.order.service.exception.IllegalCartOperationException; | ||
| import org.broadleafcommerce.core.order.service.exception.RemoveFromCartException; | ||
| import org.broadleafcommerce.core.order.service.exception.UpdateCartException; | ||
| import org.broadleafcommerce.core.pricing.service.exception.PricingException; | ||
| import org.springframework.graphql.execution.DataFetcherExceptionResolverAdapter; | ||
| import org.springframework.graphql.execution.ErrorType; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| * Maps Broadleaf domain exceptions to GraphQL errors with stable error codes in the | ||
| * {@code extensions} map. Unrecognized exceptions are mapped to {@code INTERNAL_ERROR}. | ||
| */ | ||
| @Component("blGraphQLExceptionResolver") | ||
| public class GraphQLExceptionResolver extends DataFetcherExceptionResolverAdapter { | ||
|
|
||
| public static final String ERROR_CODE_KEY = "errorCode"; | ||
| public static final String CLASSIFICATION_KEY = "classification"; | ||
|
|
||
| @Override | ||
| protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) { | ||
| String errorCode; | ||
| ErrorType errorType = ErrorType.INTERNAL_ERROR; | ||
|
|
||
| if (ex instanceof AddToCartException) { | ||
| errorCode = "ADD_TO_CART_ERROR"; | ||
| errorType = ErrorType.BAD_REQUEST; | ||
| } else if (ex instanceof PricingException) { | ||
| errorCode = "PRICING_ERROR"; | ||
| } else if (ex instanceof OfferMaxUseExceededException) { | ||
| errorCode = "OFFER_MAX_USE_EXCEEDED"; | ||
| errorType = ErrorType.BAD_REQUEST; | ||
| } else if (ex instanceof IllegalCartOperationException) { | ||
| errorCode = "ILLEGAL_CART_OPERATION"; | ||
| errorType = ErrorType.BAD_REQUEST; | ||
| } else if (ex instanceof RemoveFromCartException) { | ||
| errorCode = "REMOVE_FROM_CART_ERROR"; | ||
| errorType = ErrorType.BAD_REQUEST; | ||
| } else if (ex instanceof UpdateCartException) { | ||
| errorCode = "UPDATE_CART_ERROR"; | ||
| errorType = ErrorType.BAD_REQUEST; | ||
| } else { | ||
| errorCode = "INTERNAL_ERROR"; | ||
| } | ||
|
|
||
| Map<String, Object> extensions = new HashMap<>(); | ||
| extensions.put(ERROR_CODE_KEY, errorCode); | ||
| extensions.put(CLASSIFICATION_KEY, errorType.name()); | ||
|
|
||
| boolean safeToExposeMessage = errorType != ErrorType.INTERNAL_ERROR && ex.getMessage() != null; | ||
| String message = safeToExposeMessage ? ex.getMessage() : errorCode; | ||
|
|
||
| return GraphqlErrorBuilder.newError(env) | ||
| .errorType(errorType) | ||
| .message(message) | ||
| .extensions(extensions) | ||
| .build(); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.