Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Convert to TS - services charts, user, orgUploadToken, image #3440

Merged
merged 15 commits into from
Nov 7, 2024
Merged
1 change: 0 additions & 1 deletion src/services/charts/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export * from './useLegacyRepoCoverage'
export * from './useSunburstCoverage'
30 changes: 0 additions & 30 deletions src/services/charts/useLegacyRepoCoverage.js

This file was deleted.

77 changes: 0 additions & 77 deletions src/services/charts/useLegacyRepoCoverage.test.jsx

This file was deleted.

File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@ describe('useImage', () => {

describe('successful network request', () => {
beforeAll(() => {
global.Image = class {
;(global as any).Image = class {
constructor() {
setTimeout(() => {
this.onload()
;(this as any).onload()
}, 100)
}

decode() {
return new Promise((resolve) => resolve())
return new Promise<void>((resolve) => resolve())
}
}
})
Expand All @@ -44,10 +44,10 @@ describe('useImage', () => {

describe('unsuccessful network request', () => {
beforeAll(() => {
global.Image = class {
;(global as any).Image = class {
constructor() {
setTimeout(() => {
this.onload()
;(this as any).onload()
}, 100)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useEffect, useMemo, useState } from 'react'

export function imagePromiseFactory({ src }) {
export function imagePromiseFactory({ src }: { src: string }) {
return new Promise((resolveSource, rejectSource) => {
return new Promise((resolveImage, rejectImage) => {
return new Promise<void>((resolveImage, rejectImage) => {
const image = new Image()
image.src = src
image.onload = () =>
Expand All @@ -19,7 +19,7 @@ export function imagePromiseFactory({ src }) {

const imageExtCache = new Map()

export function useImage({ src }) {
export function useImage({ src }: { src: string }) {
const [, setIsLoading] = useState(true)

let imageCache = useMemo(
Expand All @@ -39,12 +39,12 @@ export function useImage({ src }) {
let unMounted = false
imageCache
.get(src)
.promise.then((src) => {
.promise.then((src: string) => {
if (unMounted) return
imageCache.set(src, { ...imageCache.get(src), cache: 'resolved', src })
setIsLoading(false)
})
.catch((error) => {
.catch((error: Error) => {
if (unMounted) return
imageCache.set(src, {
...imageCache.get(src),
Expand Down
9 changes: 5 additions & 4 deletions src/services/orgUploadToken/useOrgUploadToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'
import { z } from 'zod'

import Api from 'shared/api'
import { NetworkErrorObject, rejectNetworkError } from 'shared/api/helpers'

const RequestSchema = z.object({
owner: z
Expand Down Expand Up @@ -42,11 +43,11 @@ export const useOrgUploadToken = ({
const parsedRes = RequestSchema.safeParse(res?.data)

if (!parsedRes.success) {
return Promise.reject({
return rejectNetworkError({
status: 404,
data: null,
dev: 'Failed parse for GetOrgUploadToken',
})
data: {},
dev: 'useOrgUploadToken - 404 Failed to parse data',
} satisfies NetworkErrorObject)
}

return parsedRes?.data?.owner?.orgUploadToken ?? null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { graphql, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { MemoryRouter, Route } from 'react-router-dom'

import { PrefetchBranchFileEntryCoverage } from 'services/pathContents/utils'

import { usePrefetchBranchFileEntry } from './usePrefetchBranchFileEntry'

const server = setupServer()
Expand All @@ -21,7 +23,7 @@ const queryClient = new QueryClient({
},
})

const wrapper = ({ children }) => (
const wrapper: React.FC<React.PropsWithChildren> = ({ children }) => (
<MemoryRouter
initialEntries={['/gh/codecov/test-repo/tree/main/src/file.js']}
>
Expand Down Expand Up @@ -120,21 +122,28 @@ describe('usePrefetchBranchFileEntry', () => {

await result.current.runPrefetch()

await waitFor(() => queryClient.getQueryState().isFetching)
await waitFor(() => {
if (queryClient.isFetching()) {
throw new Error('still fetching')
}
})

const data = queryClient.getQueryCache().getAll()[0]?.state
.data as NonNullable<PrefetchBranchFileEntryCoverage>
suejung-sentry marked this conversation as resolved.
Show resolved Hide resolved

expect(queryClient.getQueryState().data.content).toBe(
expect(data.content).toBe(
mockData.owner.repository.commit.coverageAnalytics.coverageFile.content
)
expect(queryClient.getQueryState().data.coverage).toStrictEqual({
expect(data.coverage).toStrictEqual({
1: 1,
2: 1,
4: 1,
5: 1,
7: 1,
8: 1,
})
expect(queryClient.getQueryState().data.flagNames).toStrictEqual(['a', 'b'])
expect(queryClient.getQueryState().data.isCriticalFile).toBe(true)
expect(queryClient.getQueryState().data.totals).toBe(0)
expect(data.flagNames).toStrictEqual(['a', 'b'])
expect(data.isCriticalFile).toBe(true)
expect(data.totals).toBe(0)
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@ import Api from 'shared/api'

import { queryForCommitFile as query } from '../../constants'

interface URLParams {
provider: string
owner: string
repo: string
}

export function usePrefetchBranchFileEntry({
branch,
path,
flags = [],
options = {},
}: {
branch: string
path: string
flags?: string[]
}) {
const { provider, owner, repo } = useParams()
const { provider, owner, repo } = useParams<URLParams>()
const queryClient = useQueryClient()

const runPrefetch = async () =>
Expand Down
4 changes: 4 additions & 0 deletions src/services/pathContents/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,7 @@ export function extractCoverageFromResponse(
...(hashedPath && { hashedPath }),
}
}

export type PrefetchBranchFileEntryCoverage = ReturnType<
typeof extractCoverageFromResponse
>
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const queryClient = new QueryClient({
})

const wrapper =
(initialEntries = '/gh/codecov') =>
(initialEntries = '/gh/codecov'): React.FC<React.PropsWithChildren> =>
({ children }) => (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialEntries]}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useOwner } from './useOwner'

export function useIsCurrentUserAnAdmin({ owner }) {
export function useIsCurrentUserAnAdmin({ owner }: { owner: string }) {
const { data: ownerData } = useOwner({ username: owner })

return !!ownerData?.isAdmin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
const wrapper =
(initialEntries = '/gh') =>
(initialEntries = '/gh'): React.FC<React.PropsWithChildren> =>
({ children }) => (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialEntries]}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,12 @@ fragment CurrentUserFragment on Me {
}
`

export function useOnboardUser(opts) {
const { provider } = useParams()
interface URLParams {
provider: string
}

export function useOnboardUser(opts?: Record<string, unknown>) {
const { provider } = useParams<URLParams>()
const queryClient = useQueryClient()
const mutation = `
mutation OnboardUser($input: OnboardUserInput!) {
Expand All @@ -61,9 +65,9 @@ export function useOnboardUser(opts) {
`

return useMutation({
mutationFn: (input) => {
const formData = input?.formData
const selectedOrg = input?.selectedOrg
mutationFn: (input: { formData?: unknown; selectedOrg?: string }) => {
const formData = input.formData
const selectedOrg = input.selectedOrg

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll add zod schema validation in here - codecov/engineering-team#2857

return Api.graphqlMutation({
provider,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
QueryClient,
QueryClientProvider,
QueryFilters,
} from '@tanstack/react-query'
import { renderHook, waitFor } from '@testing-library/react'
import { graphql, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
Expand All @@ -10,7 +14,7 @@ const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
const wrapper =
(initialEntries = '/gh') =>
(initialEntries = '/gh'): React.FC<React.PropsWithChildren> =>
({ children }) => (
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[initialEntries]}>
Expand Down Expand Up @@ -115,9 +119,8 @@ describe('useResyncUser', () => {
await waitFor(() => expect(invalidateQueriesSpy).toHaveBeenCalledTimes(4))

// Mock returning the data returned being as large as the page size
getQueriesDataSpy.mockReturnValue([
0,
{ pages: { repos: Array.from({ length: 20 }) } },
getQueriesDataSpy.mockImplementation(({ queryKey }: QueryFilters) => [
[queryKey!, { pages: { repos: Array.from({ length: 20 }) } }],
])

vi.advanceTimersByTime(POLLING_INTERVAL)
Expand Down
Loading
Loading