|
| 1 | +import { postDetailModel, getLoggedInUserInfo, removepost } from "./postDetailModel.js" |
| 2 | +import { buildpostDetailView, buildRemovepostButton } from "./postDetailView.js" |
| 3 | + |
| 4 | +export const postDetailController = async (postContainer, postId) => { |
| 5 | + |
| 6 | + const showRemovepostButton = (postId) => { |
| 7 | + const removeButton = buildRemovepostButton() |
| 8 | + postContainer.appendChild(removeButton) |
| 9 | + |
| 10 | + removeButton.addEventListener("click", async () => { |
| 11 | + if (confirm("Are you sure about deleting the post?")) { |
| 12 | + try { |
| 13 | + await removepost(postId) |
| 14 | + |
| 15 | + dispatchEventWithMessage('post-success', { |
| 16 | + message: "Post successfully deleted.", |
| 17 | + type: 'success' |
| 18 | + }) |
| 19 | + |
| 20 | + setTimeout(() => window.location = '/', 2000) |
| 21 | + |
| 22 | + } catch (error) { |
| 23 | + dispatchEventWithMessage('post-error', error.message) |
| 24 | + } |
| 25 | + } |
| 26 | + }) |
| 27 | + } |
| 28 | + |
| 29 | + try { |
| 30 | + const postDetail = await postDetailModel(postId) |
| 31 | + |
| 32 | + postContainer.innerHTML = buildpostDetailView(postDetail) |
| 33 | + |
| 34 | + try { |
| 35 | + const user = await getLoggedInUserInfo() |
| 36 | + if (user?.id === postDetail?.userId) { |
| 37 | + showRemovepostButton(postId) |
| 38 | + } |
| 39 | + } catch (error) { |
| 40 | + dispatchEventWithMessage('post-error', error.message) |
| 41 | + } |
| 42 | + |
| 43 | + } catch (error) { |
| 44 | + dispatchEventWithMessage('post-error', error.message) |
| 45 | + } |
| 46 | + |
| 47 | + function dispatchEventWithMessage(eventType, message) { |
| 48 | + const event = new CustomEvent(eventType, { |
| 49 | + detail: message |
| 50 | + }) |
| 51 | + setTimeout(() => window.location = '/', 2000) |
| 52 | + document.dispatchEvent(event) |
| 53 | + } |
| 54 | + |
| 55 | +} |
0 commit comments