register api
This commit is contained in:
12
src/main/java/io/spring/RealworldApplication.java
Normal file
12
src/main/java/io/spring/RealworldApplication.java
Normal file
@@ -0,0 +1,12 @@
|
||||
package io.spring;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class RealworldApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(RealworldApplication.class, args);
|
||||
}
|
||||
}
|
||||
73
src/main/java/io/spring/api/UsersApi.java
Normal file
73
src/main/java/io/spring/api/UsersApi.java
Normal file
@@ -0,0 +1,73 @@
|
||||
package io.spring.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
import io.spring.api.exception.InvalidRequestException;
|
||||
import io.spring.application.user.UserQueryService;
|
||||
import io.spring.core.user.User;
|
||||
import io.spring.core.user.UserRepository;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.hibernate.validator.constraints.Email;
|
||||
import org.hibernate.validator.constraints.NotBlank;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/users")
|
||||
public class UsersApi {
|
||||
private UserRepository userRepository;
|
||||
private UserQueryService userQueryService;
|
||||
private String defaultImage;
|
||||
|
||||
@Autowired
|
||||
public UsersApi(UserRepository userRepository, UserQueryService userQueryService, @Value("${image.default}") String defaultImage) {
|
||||
this.userRepository = userRepository;
|
||||
this.userQueryService = userQueryService;
|
||||
this.defaultImage = defaultImage;
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.POST)
|
||||
public ResponseEntity creeteUser(@Valid @RequestBody RegisterParam registerParam, BindingResult bindingResult) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
throw new InvalidRequestException(bindingResult);
|
||||
}
|
||||
if (userRepository.findByUsername(registerParam.getUsername()).isPresent()) {
|
||||
bindingResult.rejectValue("username", "DUPLICATED", "duplicated username");
|
||||
throw new InvalidRequestException(bindingResult);
|
||||
}
|
||||
|
||||
if (userRepository.findByEmail(registerParam.getEmail()).isPresent()) {
|
||||
bindingResult.rejectValue("email", "DUPLICATED", "duplicated email");
|
||||
throw new InvalidRequestException(bindingResult);
|
||||
}
|
||||
User user = new User(
|
||||
registerParam.getEmail(),
|
||||
registerParam.getUsername(),
|
||||
registerParam.getPassword(),
|
||||
"",
|
||||
defaultImage);
|
||||
userRepository.save(user);
|
||||
return ResponseEntity.status(201).body(userQueryService.fetchCreatedUser(user.getUsername()));
|
||||
}
|
||||
}
|
||||
|
||||
@Getter
|
||||
@JsonRootName("user")
|
||||
@NoArgsConstructor
|
||||
class RegisterParam {
|
||||
@NotBlank(message = "can't be empty")
|
||||
@Email(message = "should be an email")
|
||||
private String email;
|
||||
@NotBlank(message = "can't be empty")
|
||||
private String username;
|
||||
@NotBlank(message = "can't be empty")
|
||||
private String password;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package io.spring.api.exception;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class CustomizeExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
@ExceptionHandler({InvalidRequestException.class})
|
||||
public ResponseEntity<Object> handleInvalidRequest(RuntimeException e, WebRequest request) {
|
||||
InvalidRequestException ire = (InvalidRequestException) e;
|
||||
|
||||
List<FieldErrorResource> errorResources = ire.getErrors().getFieldErrors().stream().map(fieldError ->
|
||||
new FieldErrorResource(
|
||||
fieldError.getObjectName(),
|
||||
fieldError.getField(),
|
||||
fieldError.getCode(),
|
||||
fieldError.getDefaultMessage())).collect(Collectors.toList());
|
||||
|
||||
ErrorResource error = new ErrorResource(errorResources);
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
return handleExceptionInternal(e, error, headers, UNPROCESSABLE_ENTITY, request);
|
||||
}
|
||||
}
|
||||
22
src/main/java/io/spring/api/exception/ErrorResource.java
Normal file
22
src/main/java/io/spring/api/exception/ErrorResource.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package io.spring.api.exception;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@JsonSerialize(using = ErrorResourceSerializer.class)
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@lombok.Getter
|
||||
@JsonRootName("errors")
|
||||
public class ErrorResource {
|
||||
private List<FieldErrorResource> fieldErrors;
|
||||
|
||||
public ErrorResource(List<FieldErrorResource> fieldErrorResources) {
|
||||
this.fieldErrors = fieldErrorResources;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package io.spring.api.exception;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ErrorResourceSerializer extends JsonSerializer<ErrorResource> {
|
||||
@Override
|
||||
public void serialize(ErrorResource value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
|
||||
Map<String, List<String>> json = new HashMap<>();
|
||||
for (FieldErrorResource fieldErrorResource : value.getFieldErrors()) {
|
||||
if (!json.containsKey(fieldErrorResource.getField())) {
|
||||
json.put(fieldErrorResource.getField(), new ArrayList<String>());
|
||||
}
|
||||
json.get(fieldErrorResource.getField()).add(fieldErrorResource.getMessage());
|
||||
}
|
||||
gen.writeStartObject();
|
||||
for (Map.Entry<String, List<String>> pair : json.entrySet()) {
|
||||
gen.writeArrayFieldStart(pair.getKey());
|
||||
pair.getValue().forEach(content -> {
|
||||
try {
|
||||
gen.writeString(content);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
gen.writeEndArray();
|
||||
}
|
||||
gen.writeEndObject();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.spring.api.exception;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Getter;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@Getter
|
||||
public class FieldErrorResource {
|
||||
private String resource;
|
||||
private String field;
|
||||
private String code;
|
||||
private String message;
|
||||
|
||||
public FieldErrorResource(String resource, String field, String code, String message) {
|
||||
|
||||
this.resource = resource;
|
||||
this.field = field;
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package io.spring.api.exception;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.validation.Errors;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
@JsonRootName("errors")
|
||||
public class InvalidRequestException extends RuntimeException {
|
||||
private final Errors errors;
|
||||
|
||||
public InvalidRequestException(Errors errors) {
|
||||
super("");
|
||||
this.errors = errors;
|
||||
}
|
||||
|
||||
public Errors getErrors() {
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
7
src/main/java/io/spring/application/JwtService.java
Normal file
7
src/main/java/io/spring/application/JwtService.java
Normal file
@@ -0,0 +1,7 @@
|
||||
package io.spring.application;
|
||||
|
||||
import io.spring.application.user.UserData;
|
||||
|
||||
public interface JwtService {
|
||||
String toToken(UserData userData);
|
||||
}
|
||||
22
src/main/java/io/spring/application/user/UserData.java
Normal file
22
src/main/java/io/spring/application/user/UserData.java
Normal file
@@ -0,0 +1,22 @@
|
||||
package io.spring.application.user;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Entity
|
||||
@JsonRootName("user")
|
||||
public class UserData {
|
||||
private String email;
|
||||
@Id
|
||||
private String username;
|
||||
private String bio;
|
||||
private String image;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package io.spring.application.user;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonRootName;
|
||||
import io.spring.application.JwtService;
|
||||
import lombok.Getter;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class UserQueryService {
|
||||
private UserReadService userReadService;
|
||||
private JwtService jwtService;
|
||||
|
||||
public UserQueryService(UserReadService userReadService, JwtService jwtService) {
|
||||
this.userReadService = userReadService;
|
||||
this.jwtService = jwtService;
|
||||
}
|
||||
|
||||
public UserWithToken fetchCreatedUser(String username) {
|
||||
UserData userData = userReadService.findOne(username);
|
||||
return new UserWithToken(userData, jwtService.toToken(userData));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@JsonRootName("user")
|
||||
@Getter
|
||||
class UserWithToken {
|
||||
private String email;
|
||||
private String username;
|
||||
private String bio;
|
||||
private String image;
|
||||
private String token;
|
||||
|
||||
public UserWithToken(UserData userData, String token) {
|
||||
this.email = userData.getEmail();
|
||||
this.username = userData.getUsername();
|
||||
this.bio = userData.getBio();
|
||||
this.image = userData.getImage();
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package io.spring.application.user;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
public interface UserReadService extends CrudRepository<UserData, String> {
|
||||
|
||||
}
|
||||
|
||||
25
src/main/java/io/spring/core/user/User.java
Normal file
25
src/main/java/io/spring/core/user/User.java
Normal file
@@ -0,0 +1,25 @@
|
||||
package io.spring.core.user;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(of = {"username"})
|
||||
public class User {
|
||||
private String email;
|
||||
private String username;
|
||||
private String password;
|
||||
private String bio;
|
||||
private String image;
|
||||
|
||||
public User(String email, String username, String password, String bio, String image) {
|
||||
this.email = email;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.bio = bio;
|
||||
this.image = image;
|
||||
}
|
||||
}
|
||||
14
src/main/java/io/spring/core/user/UserRepository.java
Normal file
14
src/main/java/io/spring/core/user/UserRepository.java
Normal file
@@ -0,0 +1,14 @@
|
||||
package io.spring.core.user;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface UserRepository {
|
||||
void save(User user);
|
||||
|
||||
Optional<User> findByUsername(String username);
|
||||
|
||||
Optional<User> findByEmail(String email);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.spring.infrastructure.user;
|
||||
|
||||
import io.spring.core.user.User;
|
||||
import io.spring.core.user.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public class MyBatisUserRepository implements UserRepository {
|
||||
private final UserMapper userMapper;
|
||||
|
||||
@Autowired
|
||||
public MyBatisUserRepository(UserMapper userMapper) {
|
||||
this.userMapper = userMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(User user) {
|
||||
userMapper.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByUsername(String username) {
|
||||
return Optional.ofNullable(userMapper.findByUsername(username));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<User> findByEmail(String email) {
|
||||
return Optional.ofNullable(userMapper.findByEmail(email));
|
||||
}
|
||||
}
|
||||
15
src/main/java/io/spring/infrastructure/user/UserMapper.java
Normal file
15
src/main/java/io/spring/infrastructure/user/UserMapper.java
Normal file
@@ -0,0 +1,15 @@
|
||||
package io.spring.infrastructure.user;
|
||||
|
||||
import io.spring.core.user.User;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Mapper
|
||||
public interface UserMapper {
|
||||
void save(@Param("user") User user);
|
||||
|
||||
User findByUsername(@Param("username") String username);
|
||||
User findByEmail(@Param("email") String email);
|
||||
}
|
||||
6
src/main/resources/application.properties
Normal file
6
src/main/resources/application.properties
Normal file
@@ -0,0 +1,6 @@
|
||||
spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true
|
||||
spring.jackson.serialization.WRAP_ROOT_VALUE=true
|
||||
image.default=https://static.productionready.io/images/smiley-cyrus.jpg
|
||||
|
||||
mybatis.config-location=mybatis-config.xml
|
||||
mybatis.mapper-locations=mapper/*Mapper.xml
|
||||
7
src/main/resources/db/migration/V1__create_tables.sql
Normal file
7
src/main/resources/db/migration/V1__create_tables.sql
Normal file
@@ -0,0 +1,7 @@
|
||||
create table users (
|
||||
username varchar(255) primary key,
|
||||
password varchar(255),
|
||||
email varchar(255) UNIQUE,
|
||||
bio text,
|
||||
image varchar(511)
|
||||
);
|
||||
27
src/main/resources/mapper/UserMapper.xml
Normal file
27
src/main/resources/mapper/UserMapper.xml
Normal file
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
|
||||
<mapper namespace="io.spring.infrastructure.user.UserMapper">
|
||||
<insert id="save">
|
||||
insert into users (username, email, password, bio, image) values(
|
||||
#{user.username},
|
||||
#{user.email},
|
||||
#{user.password},
|
||||
#{user.bio},
|
||||
#{user.image}
|
||||
)
|
||||
</insert>
|
||||
<select id="findByUsername" resultMap="user">
|
||||
select * from users where username = #{username}
|
||||
</select>
|
||||
<select id="findByEmail" resultMap="user">
|
||||
select username, email, password, bio, image from users where email = #{email}
|
||||
</select>
|
||||
|
||||
<resultMap id="user" type="io.spring.core.user.User" >
|
||||
<id column="username" property="username"/>
|
||||
<result column="email" property="email"/>
|
||||
<result column="password" property="password"/>
|
||||
<result column="bio" property="bio"/>
|
||||
<result column="image" property="image"/>
|
||||
</resultMap>
|
||||
</mapper>
|
||||
22
src/main/resources/mybatis-config.xml
Normal file
22
src/main/resources/mybatis-config.xml
Normal file
@@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE configuration
|
||||
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-3-config.dtd">
|
||||
<configuration>
|
||||
|
||||
<settings>
|
||||
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
|
||||
<setting name="cacheEnabled" value="true"/>
|
||||
<!-- Sets the number of seconds the driver will wait for a response from the database -->
|
||||
<setting name="defaultStatementTimeout" value="3000"/>
|
||||
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
|
||||
<setting name="mapUnderscoreToCamelCase" value="true"/>
|
||||
<!-- Allows JDBC support for generated keys. A compatible driver is required.
|
||||
This setting forces generated keys to be used if set to true,
|
||||
as some drivers deny compatibility but still work -->
|
||||
<setting name="useGeneratedKeys" value="true"/>
|
||||
</settings>
|
||||
|
||||
<!-- Continue going here -->
|
||||
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user