iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0
Software Development

從Java進入AWS部署RESTful API的心路歷程系列 第 12

Day12-實作(四)Request類型的基本判斷

我們在前一篇描述定義完了對於Person資源的基本Events,其中部分相同類型的請求故意用同一個Lambda進行處理,本篇就針對request類型增加判斷的實作。

Path Parameters

REST針對資源處理的描述之一就是將資源ID放在Uri path之中,已明確表現目前的處理資源對象。像是目前Events定義了/person/{person_id},分別於所有method都有用到。用大括號**{}** 所描述的即是path parameters,使用上也很簡單,因為Lambda Proxy integration已經包好放在pathParameters當中了,而我們可以直接在其中進行存取。

而我習慣在RequestBean當中增加一個getPath方便取得跟判斷內容

public String getPath(String name) {
    if (pathParameters == null) return null;
    if (pathParameters.containsKey(name))
        return pathParameters.get(name);
    else return null;
}

那麼我們的queryPerson可以很簡單的判斷path內容決定該進行何種查詢

public ResponseBean queryPerson(RequestBean input, Context context) {
    context.getLogger().log("Input: " + input.getBody() + "\n");
    String person_id = input.getPath("person_id");
    if (StringUtils.isNullOrEmpty(person_id)) {
        context.getLogger().log("implement query by QueryString.\n");
        // TODO: implement query by QueryString
    }
    else {
        context.getLogger().log("implement query by person_id.\n");
        // TODO: implement query by person_id
    }
    // TODO: implement your handler
    return new ResponseBean(200);
}

(這裡StringUtils使用了 AWS framework提供的函式)

httpMethod

httpMethod的判斷就更簡單了,從input.getHttpMethod()取得後進行比對即可
所以POST, PUT, PATCH

public ResponseBean updatePerson(RequestBean input, Context context) {
    context.getLogger().log("Input: " + input.getBody() + "\n");
    String httpMethod = input.getHttpMethod();
    context.getLogger().log("httpMethod:" + httpMethod + "\n");
    String person_id = input.getPath("person_id");
    if (StringUtils.isNullOrEmpty(person_id))
        return new ResponseBean(500);
    Person person = input.getBody(Person.class);
    if ("POST".equalsIgnoreCase(httpMethod)) {
        // TODO: implement POST request
    }
    else if ("PUT".equalsIgnoreCase(httpMethod)) {
        // TODO: implement PUT request
    }
    else if ("PATCH".equalsIgnoreCase(httpMethod)) {
        // TODO: implement PATCH request
    }
    else return new ResponseBean(500);
    // TODO: implement your handler
    return new ResponseBean(200);
}

而當中我也順便加上了person_id以及Person payload的取得

其他

除此之外,當然還應需要對於Person payload內容的檢查,person_id的檢查等等,不過這就等之後我們有實際的內容時候再補上吧。

而deletePerson的部分因為目前僅對應一個event,這邊就先省略不提了。

補充:前面的code中你可能會注意到出現了使用

return new ResponseBean(200);

雖然前幾篇ResponseBean當中的建構子沒有,這是後來我增加單純以http status code產生回應的暫時方案。


上一篇
Day11-實作(三)template
下一篇
Day13-實作(五)Jackson annotation
系列文
從Java進入AWS部署RESTful API的心路歷程30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言