AWS: API-Gateway: dispatching requests with one Lambda

Sometimes it is more convinient to use one lambda that handles many endpoints from API-Gateway.

We can achive this by:

  • setting the mapping in GET method in

aws-api-gateway-handle-many-endpoints-with-one-lambda

  • next, we need to handle the incomming JSON object that is defined above and dispatch the request on the ‘path’ variable
public class DispatchRequest {

    private String path;
    private String token;

    public DispatchRequest(String path, String token) {
        this.path = path;
        this.token = token;
    }

}
  • and a piece of code that does the dispatch:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestStreamHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vavr.API;
import io.vavr.control.Try;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.InputStream;
import java.io.OutputStream;

@SuppressWarnings("unused")
public class Lambda implements RequestStreamHandler {

    private static final Logger log = LogManager.getLogger(Lambda.class);
    private static final String apiVersion = "api-v1";

    @Override
    public void handleRequest(InputStream is, OutputStream os, Context context) {
        log.info("Triggered lambda");

        final ObjectMapper om = new ObjectMapper();
        final DispatchRequest apiRequest = om.readValue(is, DispatchRequest.class);

        final String path = apiRequest.getPath();
        final String token = apiRequest.getToken();

        API.Match(path).of(
            //@formatter:off
            API.Case(API.$("/" + apiVersion + "/some-resource"),               () -> runSomeCode() ),
            API.Case(API.$("/" + apiVersion + "/other-resource/sub-resource"), () -> authorize(token).andThenTry(() -> runOtherCode())),
            API.Case(API.$(), () -> Try.failure(new UnsupportedEndpointException(path)))
            //@formatter:on
        );

        log.info("Lambda finished.");
    }

}

 

Advertisements