diff --git a/src/services/postWellItem.js b/src/services/postWellItem.js index c9bc30b..43deea4 100644 --- a/src/services/postWellItem.js +++ b/src/services/postWellItem.js @@ -1,7 +1,12 @@ -import { decodeHashId, encodeHashId } from '@frolog/common-utils'; +import { decodeHashId, encodeHashId, SSC_TOKEN } from '@frolog/common-utils'; import { handleSqlError } from '@frolog/express-api-server'; -import { FetchError } from '@frolog/frolog-api'; +import { FetchError, GrantInitialStoreItem } from '@frolog/frolog-api'; import { Well, WellItem } from '@frolog/models'; +import getUserWellItemCount from './getUserWellItemCount.js'; + +const grantInitialStoreItem = new GrantInitialStoreItem({ + accessToken: SSC_TOKEN, +}); /** * 우물 아이템 작성. @@ -36,6 +41,7 @@ export default async function postWellItem(reqDto, user) { }; } + // (3) 기존 우물 아이템 조회 또는 새로 생성 let existing = true; let wellItem = await WellItem.findOne({ where: { @@ -46,10 +52,7 @@ export default async function postWellItem(reqDto, user) { if (!wellItem) { existing = false; - // 새로운 order 연산 - // Note: 여기서 count를 쓰지 않고 findOne을 쓰는 이유는, - // 비정상 동작으로 정합적이지 않은 order가 생기는 경우에도 - // 정상 동작할 수 있게 하기 위함임. + // (3-1) 마지막 order 기준으로 새 order 설정 const lastItem = await WellItem.findOne({ where: { well_id: wellId }, order: [['order', 'DESC']], @@ -57,6 +60,7 @@ export default async function postWellItem(reqDto, user) { let newOrder = 0; if (lastItem) newOrder = lastItem.order + 1; + // (3-2) 새로운 우물 아이템 생성 wellItem = await WellItem.create({ well_id: wellId, book_isbn: reqDto.isbn, @@ -65,9 +69,25 @@ export default async function postWellItem(reqDto, user) { }).catch(handleSqlError); } + // (4) 아이템 ID 인코딩 const itemId = wellItem.item_id; const itemHashId = encodeHashId(itemId); + // (5) 현재 유저의 등록된 책 개수 조회 + const { total } = await getUserWellItemCount({ id: user.id }, user).catch( + handleSqlError, + ); + + // (6) 책 2권 이상이면 초기 개구리 지급 + if (total >= 2) { + await grantInitialStoreItem + .fetch({ + id: user.id, + count: total, + }) + .catch(handleSqlError); + } + return { result: true, id: itemHashId,