Skip to content

Commit

Permalink
feat: refactoring of code and addition of new e2e test suite for inst…
Browse files Browse the repository at this point in the history
…agram posts
  • Loading branch information
tomashco committed Jul 1, 2024
1 parent 7f8bb0c commit 58a6fbd
Show file tree
Hide file tree
Showing 20 changed files with 379 additions and 227 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ dev/pnpm-lock.yaml

.vscode

# Testing
test-results

# Created by https://www.gitignore.io/api/node,macos,windows,webstorm,sublimetext,visualstudiocode

### macOS ###
Expand Down Expand Up @@ -100,7 +103,6 @@ typings/
# dotenv environment variables file
.env


### SublimeText ###
# cache files for sublime text
*.tmlanguage.cache
Expand Down
3 changes: 3 additions & 0 deletions dev/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { withPayload } from '@payloadcms/next/withPayload'
import dotenv from 'dotenv'

dotenv.config({ path: '../.env' })

/** @type {import('next').NextConfig} */
const nextConfig = {
Expand Down
14 changes: 13 additions & 1 deletion dev/src/payload.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default buildConfig({
},
plugins: [instagramPlugin({ enabled: true })],
db: mongooseAdapter({
url: process.env.DATABASE_URI || '',
url: 'mongodb://127.0.0.1/payloadtests',
}),
sharp,
onInit: async payload => {
Expand All @@ -38,5 +38,17 @@ export default buildConfig({
password: devUser.password,
},
})
if (process.env.USE_ACCESS_TOKEN)
await payload.updateGlobal({
slug: 'apikeys',
data: {
refreshToken: process.env.USE_ACCESS_TOKEN,
updatedAt: new Date().toISOString(),
createdAt: new Date().toISOString(),
},
context: {
bypass: true,
},
})
},
})
2 changes: 1 addition & 1 deletion dev/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
],
"@payload-config": [
"./src/payload.config.ts"
]
],
},
"baseUrl": ".",
"lib": [
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"Instagram"
],
"scripts": {
"dev": "cd dev && cross-env NODE_OPTIONS=--no-deprecation next dev --turbo",
"dev": "cd dev && cross-env NODE_OPTIONS=--no-deprecation PAYLOAD_DROP_DATABASE='true' next dev --turbo",
"build": "tsc",
"test": "cd test && jest --config=./jest.config.js",
"test:e2e": "cross-env NODE_OPTIONS=--no-deprecation NODE_NO_WARNINGS=1 tsx ./test/runE2E.ts",
Expand Down Expand Up @@ -52,7 +52,7 @@
"@typescript-eslint/parser": "5.12.1",
"comment-json": "^4.2.3",
"cross-env": "^7.0.3",
"dotenv": "^8.2.0",
"dotenv": "^8.6.0",
"eslint": "^8.19.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-config-prettier": "^8.5.0",
Expand Down
2 changes: 1 addition & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 37 additions & 0 deletions src/api/hooks/useInstagramCollection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { QueryClient, useMutation, useQuery } from '@tanstack/react-query'
import { instagramCollectionEndpoint } from '../../plugin'
import { PostType } from '../../types'

type UseInstagramCollectionType = {
queryClient: QueryClient
}

const useInstagramCollection = ({ queryClient }: UseInstagramCollectionType) => {
const { data: instagramCollection } = useQuery<{ docs: PostType[] }>({
queryKey: [instagramCollectionEndpoint],
queryFn: () => fetch(instagramCollectionEndpoint).then(res => res.json()),
})

const { mutate: mutateInstagramCollection } = useMutation({
mutationFn: (post: PostType) =>
fetch(instagramCollectionEndpoint, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify(post),
credentials: 'include',
}).then(res => {
return res.json()
}),
onSuccess: res => {
queryClient.invalidateQueries({ queryKey: [instagramCollectionEndpoint] })
alert(`Status: ${res?.message}`)
},
})

return { instagramCollection, mutateInstagramCollection }
}

export default useInstagramCollection
40 changes: 40 additions & 0 deletions src/api/hooks/useInstagramPosts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useQuery } from '@tanstack/react-query'
import { PostType } from '../../types'

type UseInstagramPostsType = {
endpoint: string
}

type UseInstagramResponseType = {
isPending: boolean
error: Error | null
isFetching: boolean
isLoading: boolean
response: {
data: PostType[]
paging: { before: string; after: string }
}
}

const useInstagramPosts = ({ endpoint }: UseInstagramPostsType): UseInstagramResponseType => {
const {
isPending,
error,
data: response,
isFetching,
isLoading,
} = useQuery({
queryKey: [endpoint],
queryFn: () =>
fetch(endpoint).then(res => {
if (!res.ok) throw new Error(res.status.toString())
return res.json()
}),
staleTime: 1000 * 60 * 5,
refetchOnMount: false,
refetchOnWindowFocus: false,
})
return { isPending, error, response, isFetching, isLoading }
}

export default useInstagramPosts
35 changes: 35 additions & 0 deletions src/api/hooks/useToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { QueryClient, useMutation } from '@tanstack/react-query'
import { addAccessTokenEndpoint } from '../../plugin'

type UseTokenType = {
endpoint: string
queryClient: QueryClient
setToken: React.Dispatch<React.SetStateAction<string>>
}

const useToken = ({ endpoint, queryClient, setToken }: UseTokenType) => {
const { mutate: addAccessToken } = useMutation({
mutationFn: (body: { accessToken: string }) =>
fetch(addAccessTokenEndpoint, {
body: JSON.stringify(body),
method: 'POST',
credentials: 'include',
}).then(res => {
if (!res.ok) throw new Error(res.status.toString())
return res.json()
}),
onSuccess: _res => {
queryClient.invalidateQueries({ queryKey: [endpoint] })
alert('Status: token successfully added!')
setToken('')
},
onError: _res => {
alert('Status: the token provided is not correct, try again')
setToken('')
},
})

return { addAccessToken }
}

export default useToken
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CollectionConfig } from 'payload/types'
import { childrenEndpoint, mediaEndpoint } from './plugin'
import { childrenEndpoint, mediaEndpoint } from '../plugin'

// Example Collection - For reference only, this must be added to payload.config.ts to be used.
const InstagramPosts: CollectionConfig = {
Expand Down
Loading

0 comments on commit 58a6fbd

Please sign in to comment.