GQLContext.java

package net.morimekta.providence.graphql;

import net.morimekta.providence.graphql.gql.GQLOperation;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;

/**
 * The GQL context is created once per query method call, and
 * once for the whole operation for mutations. Note that
 * {@link GQLServlet} can be updated to handle queries serially
 * as mutations if need be.
 */
public abstract class GQLContext implements AutoCloseable {
    private final HttpServletRequest  request;
    private final GQLOperation operation;

    protected GQLContext(@Nonnull HttpServletRequest request,
                         @Nonnull GQLOperation operation) {
        this.request = request;
        this.operation = operation;
    }

    /**
     * @return The HTTP request that initiated the GQL operation.
     */
    public HttpServletRequest getRequest() {
        return request;
    }

    /**
     * @return The GQL operation to be handled.
     */
    public GQLOperation getOperation() {
        return operation;
    }

    /**
     * Implement if a successful request is passed, and e.g. a transaction
     * needs to be committed (instead of aborted). This method is called
     * when the last method call has passed for the context. It will be
     * called <b>before</b> close.
     *
     * @throws Exception If committing failed.
     */
    public void commit() throws Exception {
    }

    /**
     * Implement if a failed context session ends in failure, e.g. update
     * failure. This can be used to trigger transaction abort procedure
     * etc. This will also trigger if {@link #commit()} throws exception.
     *
     * @param ex The exception causing the abort.
     * @throws Exception If the abort procedure failed.
     */
    public void abort(Exception ex) throws Exception {
    }

    static class GQLContextImpl extends GQLContext {
        GQLContextImpl(@Nonnull HttpServletRequest request,
                       @Nonnull GQLOperation operation) {
            super(request, operation);
        }

        @Override
        public void close() {
        }
    }
}