-
Notifications
You must be signed in to change notification settings - Fork 639
fix: added image fetching from das #1068
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
Open
C0mberry
wants to merge
11
commits into
solana-foundation:master
Choose a base branch
from
hoodieshq:fix/hoo-571-token-image-missing-on-token-page
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+314
−76
Open
Changes from 5 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
84979f7
added image from das
C0mberry 920f332
error handling, tests, asking for image in case there is no image
C0mberry 2c62036
more cases handle
C0mberry ddcdad8
resolve comments
C0mberry 02bd684
build fix
C0mberry 76785e0
fixed security
C0mberry e20f846
debugging
C0mberry f719cae
more loggs
C0mberry b07b48b
schema type update
C0mberry 54e6b61
validation update
C0mberry 5e6f281
null support
C0mberry File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
111 changes: 111 additions & 0 deletions
111
app/api/token-image/[mintAddress]/__tests__/route.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { GET } from '../route'; | ||
|
|
||
| vi.mock('@/app/entities/digital-asset/server', () => ({ | ||
| getAssetBatch: vi.fn(), | ||
| })); | ||
|
|
||
| const VALID_MINT = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA'; | ||
| const BASE_URL = `http://localhost:3000/api/token-image/${VALID_MINT}`; | ||
|
|
||
| function makeRequest(url = BASE_URL) { | ||
| return new Request(url); | ||
| } | ||
|
|
||
| function makeParams(mintAddress = VALID_MINT) { | ||
| return { params: Promise.resolve({ mintAddress }) }; | ||
| } | ||
|
|
||
| describe('GET /api/token-image/[mintAddress]', () => { | ||
| let getAssetBatch: ReturnType<typeof vi.fn>; | ||
|
|
||
| beforeEach(async () => { | ||
| vi.clearAllMocks(); | ||
| const mod = await import('@/app/entities/digital-asset/server'); | ||
| getAssetBatch = vi.mocked(mod.getAssetBatch); | ||
| }); | ||
|
|
||
| describe('validation', () => { | ||
| it('should return 400 for an invalid mint address', async () => { | ||
| const response = await GET(makeRequest(), makeParams('not-a-pubkey')); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| const data = await response.json(); | ||
| expect(data.error).toBe('Invalid mint address'); | ||
| }); | ||
|
|
||
| it('should return 400 for an invalid cluster slug', async () => { | ||
| const response = await GET(makeRequest(`${BASE_URL}?cluster=unknown-cluster`), makeParams()); | ||
|
|
||
| expect(response.status).toBe(400); | ||
| const data = await response.json(); | ||
| expect(data.error).toBe('Invalid cluster'); | ||
| }); | ||
|
|
||
| it('should not cache invalid mint address 400 errors', async () => { | ||
| const response = await GET(makeRequest(), makeParams('not-a-pubkey')); | ||
|
|
||
| expect(response.headers.get('Cache-Control')).toBe('no-store, max-age=0'); | ||
| }); | ||
|
|
||
| it('should not cache invalid cluster 400 errors', async () => { | ||
| const response = await GET(makeRequest(`${BASE_URL}?cluster=unknown-cluster`), makeParams()); | ||
|
|
||
| expect(response.headers.get('Cache-Control')).toBe('no-store, max-age=0'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('successful requests', () => { | ||
| it('should return the image URL when the asset has one', async () => { | ||
| getAssetBatch.mockResolvedValueOnce([ | ||
| { content: { links: { image: 'https://example.com/image.png' } }, id: VALID_MINT }, | ||
| ]); | ||
|
|
||
| const response = await GET(makeRequest(), makeParams()); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| const data = await response.json(); | ||
| expect(data.image).toBe('https://example.com/image.png'); | ||
| }); | ||
|
|
||
| it('should return undefined image when asset has no image link', async () => { | ||
| getAssetBatch.mockResolvedValueOnce([{ content: { links: {} }, id: VALID_MINT }]); | ||
|
|
||
| const response = await GET(makeRequest(), makeParams()); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| const data = await response.json(); | ||
| expect(data.image).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('should return no-store headers when no assets are returned', async () => { | ||
| getAssetBatch.mockResolvedValueOnce(null); | ||
|
|
||
| const response = await GET(makeRequest(), makeParams()); | ||
|
|
||
| expect(response.status).toBe(200); | ||
| expect(response.headers.get('Cache-Control')).toBe('no-store, max-age=0'); | ||
| }); | ||
|
|
||
| it('should return cache headers on a successful image response', async () => { | ||
| getAssetBatch.mockResolvedValueOnce([ | ||
| { content: { links: { image: 'https://example.com/image.png' } }, id: VALID_MINT }, | ||
| ]); | ||
|
|
||
| const response = await GET(makeRequest(), makeParams()); | ||
|
|
||
| expect(response.headers.get('Cache-Control')).toBe( | ||
| 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=3600', | ||
| ); | ||
| }); | ||
|
|
||
| it('should call getAssetBatch with the mint address', async () => { | ||
| getAssetBatch.mockResolvedValueOnce([{ content: { links: {} }, id: VALID_MINT }]); | ||
|
|
||
| await GET(makeRequest(), makeParams()); | ||
|
|
||
| expect(getAssetBatch).toHaveBeenCalledWith([VALID_MINT], expect.any(String)); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import { isAddress } from '@solana/kit'; | ||
| import { NextResponse } from 'next/server'; | ||
|
|
||
| import { getAssetBatch } from '@/app/entities/digital-asset/server'; | ||
| import { NO_STORE_HEADERS } from '@/app/shared/lib/http-utils'; | ||
| import { Cluster, clusterFromSlug, clusterSlug, serverClusterUrl } from '@/app/utils/cluster'; | ||
|
|
||
| const IMAGE_CACHE_HEADERS = { | ||
| 'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=3600', | ||
| }; | ||
|
|
||
| type Params = { | ||
| params: Promise<{ | ||
| mintAddress: string; | ||
| }>; | ||
| }; | ||
|
|
||
| export async function GET(request: Request, props: Params) { | ||
| const { mintAddress } = await props.params; | ||
|
|
||
| if (!isAddress(mintAddress)) { | ||
| return NextResponse.json({ error: 'Invalid mint address' }, { headers: NO_STORE_HEADERS, status: 400 }); | ||
| } | ||
|
|
||
| const { searchParams } = new URL(request.url); | ||
| const clusterParam = searchParams.get('cluster') ?? clusterSlug(Cluster.MainnetBeta); | ||
| const customUrl = searchParams.get('customUrl') ?? ''; | ||
|
|
||
| const cluster = clusterFromSlug(clusterParam); | ||
| if (cluster === null) { | ||
| return NextResponse.json({ error: 'Invalid cluster' }, { headers: NO_STORE_HEADERS, status: 400 }); | ||
| } | ||
|
|
||
| const rpcUrl = serverClusterUrl(cluster, customUrl); | ||
| const assets = await getAssetBatch([mintAddress], rpcUrl); | ||
|
C0mberry marked this conversation as resolved.
Outdated
|
||
|
|
||
| if (!assets) { | ||
| return NextResponse.json({ image: undefined }, { headers: NO_STORE_HEADERS }); | ||
| } | ||
|
|
||
| const asset = assets.find(a => a.id === mintAddress); | ||
| const image = asset?.content.links?.image; | ||
| return NextResponse.json({ image }, { headers: IMAGE_CACHE_HEADERS }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { useDasImage } from './model/use-das-image'; |
66 changes: 66 additions & 0 deletions
66
app/entities/digital-asset/model/__tests__/use-das-image.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { renderHook } from '@testing-library/react'; | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { Cluster, clusterSlug } from '@/app/utils/cluster'; | ||
|
|
||
| vi.mock('@/app/providers/cluster', () => ({ useCluster: vi.fn() })); | ||
| vi.mock('swr', () => ({ default: vi.fn() })); | ||
|
|
||
| import useSWR from 'swr'; | ||
|
|
||
| import { useCluster } from '@/app/providers/cluster'; | ||
|
|
||
| import { useDasImage } from '../use-das-image'; | ||
|
|
||
| describe('useDasImage', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.mocked(useCluster).mockReturnValue({ cluster: Cluster.MainnetBeta, customUrl: '' } as ReturnType< | ||
| typeof useCluster | ||
| >); | ||
| vi.mocked(useSWR).mockReturnValue({ data: undefined } as ReturnType<typeof useSWR>); | ||
| }); | ||
|
|
||
| it('should return undefined when no mintAddress', () => { | ||
| const { result } = renderHook(() => useDasImage(undefined)); | ||
| expect(result.current).toBeUndefined(); | ||
| expect(useSWR).toHaveBeenCalledWith(undefined, expect.any(Function), expect.any(Object)); | ||
| }); | ||
|
|
||
| it('should return the image URL from SWR data', () => { | ||
| vi.mocked(useSWR).mockReturnValue({ data: 'https://example.com/image.png' } as ReturnType<typeof useSWR>); | ||
|
|
||
| const { result } = renderHook(() => useDasImage('SomeMintAddress')); | ||
| expect(result.current).toBe('https://example.com/image.png'); | ||
| }); | ||
|
|
||
| it('should return undefined when SWR has no data', () => { | ||
| const { result } = renderHook(() => useDasImage('SomeMintAddress')); | ||
| expect(result.current).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('should pass correct SWR key including cluster slug and customUrl', () => { | ||
| vi.mocked(useCluster).mockReturnValue({ | ||
| cluster: Cluster.Devnet, | ||
| customUrl: 'https://custom.rpc', | ||
| } as ReturnType<typeof useCluster>); | ||
|
|
||
| renderHook(() => useDasImage('SomeMintAddress')); | ||
|
|
||
| expect(useSWR).toHaveBeenCalledWith( | ||
| ['das-image', 'SomeMintAddress', clusterSlug(Cluster.Devnet), 'https://custom.rpc'], | ||
| expect.any(Function), | ||
| expect.any(Object), | ||
| ); | ||
| }); | ||
|
|
||
| it('should pass correct SWR config', () => { | ||
| renderHook(() => useDasImage('SomeMintAddress')); | ||
|
|
||
| expect(useSWR).toHaveBeenCalledWith(expect.any(Array), expect.any(Function), { | ||
| dedupingInterval: 5 * 60 * 1000, | ||
| revalidateOnFocus: false, | ||
| revalidateOnReconnect: false, | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| import useSWR from 'swr'; | ||
|
|
||
| import { useCluster } from '@/app/providers/cluster'; | ||
| import { Cluster, clusterSlug } from '@/app/utils/cluster'; | ||
|
|
||
| type DasImageKey = ['das-image', string, string, string]; | ||
|
|
||
| function getDasImageKey(cluster: Cluster, mintAddress: string, customUrl: string): DasImageKey { | ||
| return ['das-image', mintAddress, clusterSlug(cluster), customUrl]; | ||
| } | ||
|
|
||
| async function fetchDasImage([, mintAddress, cluster, customUrl]: DasImageKey): Promise<string | undefined> { | ||
| try { | ||
| const params = new URLSearchParams({ cluster }); | ||
| if (customUrl) params.set('customUrl', customUrl); | ||
| const response = await fetch(`/api/token-image/${mintAddress}?${params}`); | ||
| if (!response.ok) return undefined; | ||
| const data = await response.json(); | ||
| return typeof data.image === 'string' ? data.image : undefined; | ||
| } catch { | ||
| return undefined; | ||
| } | ||
| } | ||
|
|
||
| const DAS_IMAGE_SWR_CONFIG = { | ||
| dedupingInterval: 5 * 60 * 1000, | ||
| revalidateOnFocus: false, | ||
| revalidateOnReconnect: false, | ||
| }; | ||
|
|
||
| export function useDasImage(mintAddress?: string): string | undefined { | ||
| const { cluster, customUrl } = useCluster(); | ||
| const swrKey = mintAddress ? getDasImageKey(cluster, mintAddress, customUrl) : undefined; | ||
| const { data } = useSWR(swrKey, fetchDasImage, DAS_IMAGE_SWR_CONFIG); | ||
| return data; | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.