카테고리 없음

Bank.java [Spring] --> REST API --> React UI

로그앤 2023. 6. 22. 13:18
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/bank")
public class BankController {
    private Map<Integer, User> users;
    private Map<Integer, Account> accounts;
    private List<Card> cards;
    private int lastUserId;
    private int lastAccountId;
    private int lastCardId;

    public BankController() {
        this.users = new HashMap<>();
        this.accounts = new HashMap<>();
        this.cards = new ArrayList<>();
        this.lastUserId = 0;
        this.lastAccountId = 0;
        this.lastCardId = 0;
    }

    @PostMapping("/users")
    public ResponseEntity<Integer> registerUser(@RequestBody User user) {
        lastUserId++;
        users.put(lastUserId, user);
        return new ResponseEntity<>(lastUserId, HttpStatus.CREATED);
    }

    @PostMapping("/accounts/{userId}")
    public ResponseEntity<Integer> openAccount(@PathVariable int userId) {
        lastAccountId++;
        Account account = new Account(lastAccountId);
        accounts.put(lastAccountId, account);
        return new ResponseEntity<>(lastAccountId, HttpStatus.CREATED);
    }

    @PostMapping("/cards/{accountId}/{cardType}")
    public ResponseEntity<Integer> issueCard(@PathVariable int accountId, @PathVariable String cardType) {
        lastCardId++;
        Card card = new Card(lastCardId, accountId, cardType);
        cards.add(card);
        return new ResponseEntity<>(lastCardId, HttpStatus.CREATED);
    }

    @GetMapping("/cards/{cardId}")
    public ResponseEntity<Card> getCard(@PathVariable int cardId) {
        for (Card card : cards) {
            if (card.getCardId() == cardId) {
                return new ResponseEntity<>(card, HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @GetMapping("/users/{userId}")
    public ResponseEntity<User> getUser(@PathVariable int userId) {
        User user = users.get(userId);
        if (user != null) {
            return new ResponseEntity<>(user, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @GetMapping("/accounts/{accountId}")
    public ResponseEntity<Account> getAccount(@PathVariable int accountId) {
        Account account = accounts.get(accountId);
        if (account != null) {
            return new ResponseEntity<>(account, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

To connect the Bank class with a sample bank REST API, you would need to 

create appropriate endpoints for the desired operations such as registering a user, 

opening an account, issuing a card, and retrieving user/account/card information. 

You would also need to configure the API routes and handle the HTTP requests and responses. 

 

In this example, the BankController class is a Spring RestController 

that handles the bank operations as API endpoints. 

Each endpoint is annotated with the appropriate HTTP method and route. 

 

 

function BankApp() {
  const [userId, setUserId] = useState('');
  const [user, setUser] = useState(null);
  const [accountId, setAccountId] = useState('');
  const [account, setAccount] = useState(null);
  const [cardId, setCardId] = useState('');
  const [card, setCard] = useState(null);

  const fetchUser = async () => {
    try {
      const response = await axios.get(`/api/bank/users/${userId}`);
      setUser(response.data);
    } catch (error) {
      console.error(error);
    }
  };

  const fetchAccount = async () => {
    try {
      const response = await axios.get(`/api/bank/accounts/${accountId}`);
      setAccount(response.data);
    } catch (error) {
      console.error(error);
    }
  };

  const fetchCard = async () => {
    try {
      const response = await axios.get(`/api/bank/cards/${cardId}`);
      setCard(response.data);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    if (userId) {
      fetchUser();
    }
  }, [userId]);

  useEffect(() => {
    if (accountId) {
      fetchAccount();
    }
  }, [accountId]);

  useEffect(() => {
    if (cardId) {
      fetchCard();
    }
  }, [cardId]);

  return (
    <div>
      <h1>Bank App</h1>

      <div>
        <h2>User</h2>
        <label>
          User ID:
          <input type="number" value={userId} onChange={(e) => setUserId(e.target.value)} />
        </label>
        <button onClick={fetchUser}>Fetch User</button>
        {user && (
          <div>
            <p>Name: {user.name}</p>
            <p>Address: {user.address}</p>
            <p>Phone Number: {user.phoneNumber}</p>
            {/* Render other user details */}
          </div>
        )}
      </div>

      <div>
        <h2>Account</h2>
        <label>
          Account ID:
          <input type="number" value={accountId} onChange={(e) => setAccountId(e.target.value)} />
        </label>
        <button onClick={fetchAccount}>Fetch Account</button>
        {account && (
          <div>
            <p>Account Number: {account.accountNumber}</p>
            {/* Render other account details */}
          </div>
        )}
      </div>

      <div>
        <h2>Card</h2>
        <label>
          Card ID:
          <input type="number" value={cardId} onChange={(e) => setCardId(e.target.value)} />
        </label>
        <button onClick={fetchCard}>Fetch Card</button>
        {card && (
          <div>
            <p>Card Type: {card.cardType}</p>
            {/* Render other card details */}
          </div>
        )}
      </div>
    </div>
  );
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

@PostMapping("/cards/{accountId}/{cardType}")
public ResponseEntity<Integer> issueCard(@PathVariable int accountId, @PathVariable String cardType) {
    lastCardId++;
    Card card = new Card(lastCardId, accountId, cardType);
    cards.add(card);
    return new ResponseEntity<>(lastCardId, HttpStatus.CREATED);
}

1. @PostMapping("/cards/{accountId}/{cardType}")

is an annotation that indicates this method handles HTTP POST requests to the

/api/bank/cards/{accountId}/{cardType} endpoint.

The {accountId} and {cardType} parts of the URL are path variables that will be extracted from the URL.

 

2. public ResponseEntity<Integer> issueCard(@PathVariable int accountId, @PathVariable String cardType)

is the method signature that specifies two path variables: accountId (int) and cardType (String).

The return type of the method is ResponseEntity<Integer>, indicating that the response will contain an integer value.

 

3. return new ResponseEntity<>(lastCardId, HttpStatus.CREATED)

constructs a ResponseEntity object, which represents the HTTP response sent back to the client. In this case, it contains the lastCardId as the response body and HttpStatus.CREATED (HTTP status code 201) indicating that the card was successfully created.

 

So, when a POST request is made to the /api/bank/cards/{accountId}/{cardType} endpoint, 

it generates a new Card object, adds it to the cards list, and returns a ResponseEntity containing the ID of the newly issued card.

 

Fetch vs Axios 

  // AXIOS 
  
  const fetchCard = async () => {
    try {
      const response = await axios.get(`/api/bank/cards/${cardId}`);
      setCard(response.data);
    } catch (error) {
      console.error(error);
    }
  };
  
  
  
  // FETCH 
  const fetchCard = async () => {
  try {
    const response = await fetch(`/api/bank/cards/${cardId}`);
    if (!response.ok) {
      throw new Error('Failed to fetch card');
    }
    const cardData = await response.json();
    setCard(cardData);
  } catch (error) {
    console.error(error);
  }
};