Skip to content

Commit

Permalink
refactor(app-router): fix show to owner
Browse files Browse the repository at this point in the history
  • Loading branch information
divyenduz committed Apr 19, 2024
1 parent f58a5ad commit a0ede54
Show file tree
Hide file tree
Showing 12 changed files with 76 additions and 130 deletions.
9 changes: 0 additions & 9 deletions packages/next-js-app/app/actions/actions.ts
Original file line number Diff line number Diff line change
@@ -1,9 +0,0 @@
export class FormValidationFailedError extends Error {
message: string = 'Form validation failed'
constructor(message?: string) {
super()
if (message) {
this.message = message
}
}
}
22 changes: 1 addition & 21 deletions packages/next-js-app/app/actions/deletePost.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,10 @@
'use server'

import { Post, sql } from '@trackfootball/database'
import { revalidatePath } from 'next/cache'
import { MESSAGE_UNAUTHORIZED } from 'packages/auth/utils'
import { auth } from 'utils/auth'
import { z } from 'zod'

import { FormValidationFailedError } from './actions'

const schema = z.object({
postId: z.number().nonnegative(),
})

export async function deletePost(formData: FormData) {
const validatedFields = schema.safeParse({
postId: formData.get('postId'),
})

if (!validatedFields.success) {
throw new FormValidationFailedError(
JSON.stringify(validatedFields.error.flatten().fieldErrors)
)
}

const { postId } = validatedFields.data

export async function deletePost(postId: number) {
const user = await auth()

const post = (
Expand Down
17 changes: 1 addition & 16 deletions packages/next-js-app/app/actions/disconnectStrava.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,8 @@

import { sql } from '@trackfootball/database'
import { auth } from 'utils/auth'
import { z } from 'zod'

import { FormValidationFailedError } from './actions'

const schema = z.object({})

export async function disconnectStrava(formData: FormData) {
const validatedFields = schema.safeParse({})

if (!validatedFields.success) {
throw new FormValidationFailedError(
JSON.stringify(validatedFields.error.flatten().fieldErrors)
)
}

const {} = validatedFields.data

export async function disconnectStrava() {
const user = await auth()

const stravaLogin = user.socialLogin.find((sl) => sl.platform === 'STRAVA')
Expand Down
22 changes: 1 addition & 21 deletions packages/next-js-app/app/actions/refreshPost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,12 @@
import { Post, PostStatus, User, sql } from '@trackfootball/database'
import { Core } from '@trackfootball/sprint-detection'
import { durationToSeconds } from '@trackfootball/utils'
import { revalidatePath } from 'next/cache'
import { MESSAGE_UNAUTHORIZED } from 'packages/auth/utils'
import { postAddField } from 'packages/services/post/addField'
import { fetchStravaActivityGeoJson } from 'repository/strava'
import { auth } from 'utils/auth'
import { z } from 'zod'

import { FormValidationFailedError } from './actions'

const schema = z.object({
postId: z.number().nonnegative(),
})

export async function refreshPost(formData: FormData) {
const validatedFields = schema.safeParse({
postId: formData.get('postId'),
})

if (!validatedFields.success) {
throw new FormValidationFailedError(
JSON.stringify(validatedFields.error.flatten().fieldErrors)
)
}

const { postId } = validatedFields.data

export async function refreshPost(postId: number) {
const user = await auth()

const post = (
Expand Down
16 changes: 13 additions & 3 deletions packages/next-js-app/app/athlete/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
Typography,
} from '@mui/material'
import { AwaitedUser } from 'app/layout'
import { Metadata, ResolvingMetadata } from 'next'
import { Metadata } from 'next'
import Image from 'next/image'
import { notFound } from 'next/navigation'
import { checkStravaAccessToken } from 'repository/strava'
Expand Down Expand Up @@ -72,7 +72,13 @@ async function checkStravaToken(user: AwaitedUser) {
.exhaustive()
}

export default async function Profile() {
interface Props {
params: {
id: string
}
}

export default async function Profile({ params }: Props) {
let user = null
try {
user = await auth()
Expand Down Expand Up @@ -117,7 +123,11 @@ export default async function Profile() {
<CardContent>
<div style={{ marginBottom: 30 }}></div>

<ShowToOwner ownerId={user.id} userId={user.id}>
<ShowToOwner
ownerId={user.id}
userId={user.id}
userIsAdmin={user.type === 'ADMIN'}
>
<Card>
<Space direction="vertical">
<CardHeader title="Integrations"></CardHeader>
Expand Down
17 changes: 17 additions & 0 deletions packages/next-js-app/app/error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use client'

const BaseError = ({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) => {
console.log({
error,
reset,
})
return <>Something went wrong: {error.message}</>
}

export default BaseError
2 changes: 1 addition & 1 deletion packages/next-js-app/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ height="0" width="0" style="display:none;visibility:hidden"></iframe>`,
<AppBar pageName={'TrackFootball'} user={user}></AppBar>
</div>

<div className="flex items-center justify-center">
<div className="flex items-center justify-center min-h-[600px]">
<div
className={`flex flex-col items-center justify-center w-full mt-24`}
>
Expand Down
19 changes: 0 additions & 19 deletions packages/next-js-app/components/context/UserContext.tsx

This file was deleted.

34 changes: 23 additions & 11 deletions packages/next-js-app/components/organisms/Activity/ActivityItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,11 @@ import { metersToKilometers, mpsToKmph } from '@trackfootball/utils'
import { refreshPost } from 'app/actions/refreshPost'
import { AwaitedUser } from 'app/layout'
import { formatDistance } from 'date-fns'
import { useFlags } from 'launchdarkly-react-client-sdk'
import Image from 'next/image'
import Link from 'next/link'
import React, { useEffect, useState } from 'react'
import { getPost } from 'repository/post'
import { match } from 'ts-pattern'
import { auth } from 'utils/auth'

import Button from '../../../components/atoms/Button'
import { getBoundsForPoints } from '../../../packages/utils/map'
Expand Down Expand Up @@ -167,8 +165,13 @@ const ActivityItem: React.FC<Props> = ({ post, user }) => {
<div className="md:w-full">
<ActivityItemAdminActions
postId={post.id}
userIsAdmin={user?.type === 'ADMIN'}
></ActivityItemAdminActions>
<ShowToOwner ownerId={post.userId} userId={user?.id || -1}>
<ShowToOwner
ownerId={post.userId}
userId={user?.id || -1}
userIsAdmin={user?.type === 'ADMIN'}
>
<FeedItemAction postId={post.id} />
</ShowToOwner>
</div>
Expand Down Expand Up @@ -259,8 +262,13 @@ const ActivityItem: React.FC<Props> = ({ post, user }) => {
<div className="flex space-x-2 md:w-full">
<ActivityItemAdminActions
postId={post.id}
userIsAdmin={user?.type === 'ADMIN'}
></ActivityItemAdminActions>
<ShowToOwner ownerId={post.userId} userId={user?.id || -1}>
<ShowToOwner
ownerId={post.userId}
userId={user?.id || -1}
userIsAdmin={user?.type === 'ADMIN'}
>
<FeedItemAction postId={post.id} />
</ShowToOwner>
</div>
Expand All @@ -279,6 +287,7 @@ const ActivityItem: React.FC<Props> = ({ post, user }) => {
className={classes.paper}
ownerId={post.userId}
userId={user?.id || -1}
userIsAdmin={user?.type === 'ADMIN'}
>
<div className={classes.title}>❤️ Max Heart Rate</div>
<div className={classes.value}>{post.maxHeartRate}</div>
Expand All @@ -288,6 +297,7 @@ const ActivityItem: React.FC<Props> = ({ post, user }) => {
className={classes.paper}
ownerId={post.userId}
userId={user?.id || -1}
userIsAdmin={user?.type === 'ADMIN'}
>
<div className={classes.title}>❤️ Average Heart Rate</div>
<div className={classes.value}>{post.averageHeartRate}</div>
Expand Down Expand Up @@ -432,10 +442,14 @@ const ActivityItem: React.FC<Props> = ({ post, user }) => {
)
}

const ActivityItemAdminActions = ({ postId }: { postId: number }) => {
const flags = useFlags()

if (!flags.showToAdmin) {
const ActivityItemAdminActions = ({
postId,
userIsAdmin,
}: {
postId: number
userIsAdmin: boolean
}) => {
if (!userIsAdmin) {
return null
}

Expand All @@ -448,9 +462,7 @@ const ActivityItemAdminActions = ({ postId }: { postId: number }) => {
'Are you sure that you want to refresh the statistics of this post?'
)
if (r) {
const formData = new FormData()
formData.append('postId', postId.toString())
await refreshPost(formData)
await refreshPost(postId)
}
}}
>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"use client"
'use client'

import { deletePost } from 'app/actions/deletePost'
import { useRouter } from 'next/navigation'
import React from 'react'

import { Space } from '../../../components/atoms/Space'
import { Button } from '../../atoms/Button'
import { deletePost } from 'app/actions/deletePost'
import { useRouter } from 'next/navigation'

interface FeedItemActionProps {
postId: number
Expand All @@ -25,15 +25,12 @@ export const FeedItemAction = ({ postId }: FeedItemActionProps) => {
return
}
try {
const formData = new FormData()
formData.append('postId', postId.toString())
const r = await deletePost(formData)
const r = await deletePost(postId)
router.replace('/dashboard')
} catch (e) {
console.error(e)
alert(
`Something went wrong, please contact [email protected]` +
e
`Something went wrong, please contact [email protected]` + e
)
}
}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
'use client'

import { Button, Card, CardContent, CardHeader } from '@mui/material'
import { disconnectStrava } from 'app/actions/disconnectStrava'
import { CheckStravaState } from 'app/athlete/[id]/page'
import { match } from 'ts-pattern'

import { Space } from '../../../components/atoms/Space'
import ConnectWithStrava from '../../../components/atoms/brand/strava/ConnectWithStrava'
import { CheckStravaState } from 'app/athlete/[id]/page'
import { disconnectStrava } from 'app/actions/disconnectStrava'

interface Props {
redirectTo: 'dashboard' | 'athlete'
backendApiUrl: string
checkStravaState: CheckStravaState
}



export const ConnectWithStravaWidget: React.FC<Props> = ({ redirectTo, backendApiUrl, checkStravaState }) => {
export const ConnectWithStravaWidget: React.FC<Props> = ({
redirectTo,
backendApiUrl,
checkStravaState,
}) => {
return (
<Card>
<Space direction="vertical">
Expand All @@ -28,7 +30,7 @@ export const ConnectWithStravaWidget: React.FC<Props> = ({ redirectTo, backendAp
variant="contained"
color="secondary"
onClick={async () => {
await disconnectStrava(new FormData())
await disconnectStrava()
}}
>
Disconnect Strava
Expand Down
Loading

0 comments on commit a0ede54

Please sign in to comment.