|
| 1 | +/* |
| 2 | + * Copyright (c) 2015 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you |
| 5 | + * may not use this file except in compliance with the License. You may |
| 6 | + * obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 13 | + * implied. See the License for the specific language governing |
| 14 | + * permissions and limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.appengine.sparkdemo; |
| 18 | + |
| 19 | +import static spark.Spark.after; |
| 20 | +import static spark.Spark.delete; |
| 21 | +import static spark.Spark.exception; |
| 22 | +import static spark.Spark.get; |
| 23 | +import static spark.Spark.post; |
| 24 | +import static spark.Spark.put; |
| 25 | + |
| 26 | +import com.google.gson.Gson; |
| 27 | + |
| 28 | +import spark.ResponseTransformer; |
| 29 | +import spark.Spark; |
| 30 | + |
| 31 | +public class UserController { |
| 32 | + |
| 33 | + public UserController(final UserService userService) { |
| 34 | + Spark.staticFileLocation("/public"); |
| 35 | + |
| 36 | + get("/api/users", (req, res) -> userService.getAllUsers(), UserController::toJson); |
| 37 | + |
| 38 | + post("/api/users", |
| 39 | + (req, res) -> userService.createUser(req.queryParams("name"), req.queryParams("email")), |
| 40 | + json()); |
| 41 | + |
| 42 | + put("/api/users/:id", (req, res) -> userService.updateUser( |
| 43 | + req.params(":id"), |
| 44 | + req.queryParams("name"), |
| 45 | + req.queryParams("email") |
| 46 | + ), json()); |
| 47 | + |
| 48 | + delete("/api/users/:id", (req, res) -> userService.deleteUser(req.params(":id")), json()); |
| 49 | + |
| 50 | + after((req, res) -> { |
| 51 | + res.type("application/json"); |
| 52 | + }); |
| 53 | + |
| 54 | + exception(IllegalArgumentException.class, (e, req, res) -> { |
| 55 | + res.status(400); |
| 56 | + res.body(toJson(new ResponseError(e))); |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + private static String toJson(Object object) { |
| 61 | + return new Gson().toJson(object); |
| 62 | + } |
| 63 | + |
| 64 | + private static ResponseTransformer json() { |
| 65 | + return UserController::toJson; |
| 66 | + } |
| 67 | +} |
0 commit comments