본문 바로가기

Vue/bookStore

6. postBook - 도서등록 2

들어가기 이전


 

1. 카카오 책 검색 API 사용

API를 사용하면 키워드를 따로 등록해야 하고, 정보도 전체정보가 아닌 일부 정보만 제공했기 때문에

책API를 사용하지 않고 책을 하나하나 등록하려고 했었다.

직접 하나하나 등록하다가 보니 너무 막노동이라 카카오API를 통해 제공하는 정보는 넣고 

추가로 넣어줘야 하는 정보는 직접 검색해서 넣어주기로 했다.

 

2. 추가되는 컬럼

 벌써 4~5번이나 추가되고 삭제하는 것 같은데..

isbn은 String으로 바꿔주었고 책 소개 / 목차 / 서평 컬럼이 추가되었다. 그리고 전체적으로 컬럼 명이 바뀌었다.

 

 

3. 다양한 에러

그리고 컬럼이 추가되고 API를 사용하여 적용하는 도중 많은 에러가 떴었고 그 중 기억에 남는 에러는

400, 500에러와 데이터 타입에러 그리고 데이터 크기때문에 에러가 났었다.

특히 400 BadRequest 때문에 시간을 엄~~~청 날렸는데.. 알고보니 예약어를 컬럼명으로 사용해서

일어나는 에러였다.

CREATE TABLE `book` (
  `bid` bigint(20) NOT NULL COMMENT '책id',
  `mid` bigint(20) NOT NULL COMMENT 'member id',
  `b_title` varchar(300) NOT NULL COMMENT '책제목',
  `b_subTitle` varchar(200) NOT NULL COMMENT '부제목',
  `b_author` varchar(200) NOT NULL COMMENT '저자',
  `b_translator` varchar(200) COMMENT '번역가',
  `b_content` varchar(4000) not null COMMENT '책 소개',
  `b_index` varchar(4000) COMMENT '목차',
  `b_preview` varchar(4000) COMMENT '서평',
  `b_page` int(20) not null comment '책 페이지',
  `b_isbn` varchar(1000) not null comment 'isbn',
  `b_price` int(11)  NOT NULL COMMENT '가격',
  `b_salePrice` int(11)  NOT NULL COMMENT '판매 가격',
  `b_size` varchar(200)  NOT NULL COMMENT '크기/무게',
  `b_thumb` varchar(200)  NOT NULL COMMENT '썸네일',
  `b_publisher` varchar(200) NOT NULL COMMENT '출판사',
  `b_publishedDate` date NOT NULL COMMENT '출판일',
  `b_tag` varchar(200) NOT NULL COMMENT '태그',
  `b_detailTag` varchar(200) NOT NULL COMMENT '디테일 태그',
  `b_keyword` varchar(1000) COMMENT '키워드',
  `isDel` enum('Y','N') not null default 'N',
  PRIMARY KEY (`bid`)
)

컬럼명을 다 바꿔주었고 여기까지 오니 등록이 잘 되었다.

 

 

 

 

 

책 등록 동작


 

1. Vue - bookPost에서 isbn을 검색하면 

 

 

2. 카카오APi 에서 제공하는 책 정보는 다 자동으로 입력된다.

아래는 카카오 책 검색API를 사용하여 얻은 결과값

아래 url로 들어가면 해당 책의 상세정보가 적혀있는 책검색 페이지로 이동된다.

 

 

나머지는 다 직접 입력해야한다...

태그를 고르면 세부태그를 등록할수 있다. 키워드는 하나하나 직접 등록

 

 

책 등록 Vue


postBook.Vue - <script> methods부분

 

 ===== script의 methods 부분 =====
 
 methods: {
    searchIsbn(isbn){
      console.log(isbn)
      if (isbn !== undefined && isbn !== "") {
        this.$axios.get("https://dapi.kakao.com/v3/search/book",{
          params : {
            query : isbn ,
            target : 'isbn'
          },
          headers: {'Authorization': '카카오 키'},
        })
            .then(response=>{
              console.log(response.data);
              let info = response.data.documents[0]
              this.title = info.title
              this.author = info.authors
              this.translator = info.translators
              this.content = info.contents
              this.price = info.price
              this.sale_price = info.sale_price
              this.thumb = info.thumbnail
              this.publisher = info.publisher
              this.date = info.datetime.substring(0,10)

              if(info.isbn.length === 24){
                this.isbn = info.isbn.substring(11,24)+('(')+info.isbn.substring(0,10)+(')')
              }else{
                this.isbn = info.isbn
              }
            })
            .catch(error =>{
              console.log(error.response);
            })
      }
    },

    commit(){
      let bookData = {}

      bookData.b_title = this.title
      bookData.b_subTitle = this.sub_title
      bookData.b_author = this.author.toString()
      bookData.b_publisher = this.publisher
      bookData.b_publishedDate = this.date
      bookData.b_translator = this.translator.toString()
      bookData.b_isbn = this.isbn
      bookData.b_page = Number(this.page)
      bookData.b_price = Number(this.price)
      bookData.b_salePrice = Number(this.sale_price)
      bookData.b_size = this.size
      bookData.b_thumb = this.thumb
      bookData.b_content = this.content
      bookData.b_index = this.index
      bookData.b_preview = this.preview
      bookData.b_tag = this.selectedTag.main
      bookData.b_detailTag = this.selectedSubTag
      bookData.b_keyword = this.keyword.toString()


      this.$axios.post('book/',JSON.stringify(bookData),{
        headers: {
          "Content-Type": `application/json`,
        },
      }).then(response=>{
        console.log(response.data)
        alert("책 등록신청을 완료하였습니다.");
        this.$router.push({path: './home'});
      }).catch(error =>{
        console.log(error.response);
      })
    },

    cancel(){
      this.$axios.get('book/')
        .then(response=>{
            console.log(response.data);
          })
        .catch(error =>{
          console.log(error.response);
        })
      },
  },
}
</script>

 

1. Vue - script

 

제목으로 서칭기능도 추가했지만 코드가 너무 길어서 isbn만 넣었다.

response data는 알맞게 가공 후 데이터에 넣어줬다.

->

isbn검색 값은 10자리 수 isbn과 13자리 isbn 두가지로 나온다 

10자리 - 2007년 이전에 주로 사용되던 값이고

13자리 - 기존의 10자리 ISBN의 가용성 향상을 위해 2007년에 만든 것이다

 

9788996991342 을 검색할때 두 가지 isbn이 나온다면

9788996991342(8996991341) 형태로 저장되게 if문을 사용했다.

 

vue data타입은 기본적으로 String타입이므로 페이지 가격 등은 int형으로 바꿔준다.

배열에 있는 정보는 toString으로 값을 빼줬다.

 

 

 

2. 카카오 API 호출할때 인증

기존 인터셉터에서 요청이 들어가면 Bearer토큰을 실어준다.

그렇게되면 자동으로 카카오 인증키는 사라지게 된다. 

if(config.url.match("kakao")){
    console.log("kakao Api Request")
    return config;
}

따라서 위와같이 인터셉터 설정 부분의 plugins.axios 파일에서 kakao가 포함된 url request가 들어가면

예외처리를 해주자.

 

 

 

3. Springboot-book Service에서 책을 등록할때도 컬럼을 추가해주자.

public ApiResponse<Book> postBook(BookDTO bookDTO) {
        long newBookBidValue = this.getNewBookBidValue(bookRepository);
        long memberId = getMemberIdByEmail(memberRepository);
        log.debug("member id : "+memberId);

        Book postData = Book.builder()
                .bid(newBookBidValue)
                .mid(memberId)
                .b_title(bookDTO.getB_title())
                .b_subTitle(bookDTO.getB_subTitle())
                .b_author(bookDTO.getB_author())
                .b_translator(bookDTO.getB_translator())
                .b_content(bookDTO.getB_content())
                .b_index(bookDTO.getB_index())
                .b_preview(bookDTO.getB_preview())
                .b_page(bookDTO.getB_page())
                .b_isbn(bookDTO.getB_isbn())
                .b_price(bookDTO.getB_price())
                .b_salePrice(bookDTO.getB_salePrice())
                .b_size(bookDTO.getB_size())
                .b_thumb(bookDTO.getB_thumb())
                .b_publisher(bookDTO.getB_publisher())
                .b_publishedDate(bookDTO.getB_publishedDate())
                .b_tag(bookDTO.getB_tag())
                .b_detailTag(bookDTO.getB_detailTag())
                .b_keyword(bookDTO.getB_keyword())
                .isDel("N")
                .build();
        bookRepository.save(postData);
        return new ApiResponse<>(true, "Registration successfully ", postData);
    }

 

 

4. 책 등록

'Vue > bookStore' 카테고리의 다른 글

8. 도서 위시리스트 (Spring boot)  (0) 2022.03.22
7. 도서 리스트 1  (0) 2022.03.14
5. bookStore 도서 등록  (0) 2022.02.19
4. bookStore - Book CRUD  (0) 2022.02.06
3. BookStore jwtToken 인증 추가  (0) 2022.02.06