ens-proxy/api/profile.ts

73 lines
1.7 KiB
TypeScript
Raw Permalink Normal View History

2022-08-22 14:42:40 +02:00
import type { VercelRequest, VercelResponse } from '@vercel/node'
2022-08-18 15:51:38 +02:00
import { getEnsName } from './name'
import { getEnsTextRecords } from './text'
interface ProfileLink {
key: string
value: string
}
interface Profile {
name: string
url?: string
avatar?: string
description?: string
links?: ProfileLink[]
}
function getEnsAvatar(ensName: string): string {
return ensName
? `https://metadata.ens.domains/mainnet/avatar/${ensName}`
2022-08-22 15:03:45 +02:00
: 'null'
2022-08-18 15:51:38 +02:00
}
export async function getEnsProfile(accountId: string): Promise<Profile> {
2022-08-22 14:09:50 +02:00
const name = await getEnsName(accountId)
if (!name) return { name: 'null' }
2022-08-18 15:51:38 +02:00
const records = await getEnsTextRecords(name)
if (!records) return { name }
const avatar = records.filter((record) => record.key === 'avatar')[0]?.value
const description = records.filter(
(record) => record.key === 'description'
)[0]?.value
// filter out what we need from the fetched text records
const linkKeys = [
'url',
'com.twitter',
'com.github',
'org.telegram',
'com.discord',
'com.reddit'
]
const links: ProfileLink[] = records.filter((record) =>
linkKeys.includes(record.key)
)
const profile: Profile = {
name,
...(avatar && { avatar: getEnsAvatar(name) }),
...(description && { description }),
...(links.length > 0 && { links })
}
return profile
}
2022-08-18 16:09:42 +02:00
export default async function EnsProfileApi(
2022-08-22 14:42:40 +02:00
request: VercelRequest,
response: VercelResponse
2022-08-18 16:09:42 +02:00
) {
try {
const accountId = String(request.query.address)
const profile = await getEnsProfile(accountId)
2022-08-22 12:57:25 +02:00
response.setHeader('Cache-Control', 'max-age=0, s-maxage=86400')
2022-08-24 15:49:17 +02:00
response.status(200).send({ profile })
2022-08-18 16:09:42 +02:00
} catch (error) {
2022-08-24 15:49:17 +02:00
response.send({ error })
2022-08-18 16:09:42 +02:00
}
}