Skip to content

Built for people who want to own their automations. Join the waitlist for an invite.

Package listing

@kody/discord

src/get-me.ts

43 lines · 1.5 KB · TypeScript
import { discordBotRequest } from './bot.ts'
import { discordOauthRequest } from './oauth.ts'
import { inputRecord, requiredLane, type InputRecord } from './validation.ts'

type DiscordUser = {
	id?: string
	username?: string
	global_name?: string | null
	discriminator?: string
	bot?: boolean
	flags?: number
}

function projectUser(lane: 'bot' | 'oauth', user: DiscordUser) {
	return {
		lane,
		id: typeof user.id === 'string' ? user.id : null,
		username: typeof user.username === 'string' ? user.username : null,
		globalName: typeof user.global_name === 'string' ? user.global_name : null,
		discriminator: typeof user.discriminator === 'string' ? user.discriminator : null,
		bot: user.bot === true,
	}
}

/**
 * Read the authenticated Discord identity from GET /users/@me.
 *
 * @param params.lane - `bot` (default) uses `secretName`; `oauth` uses `integration`.
 * @param params.secretName - Bot-token secret; default `discordBotToken`.
 * @param params.integration - OAuth integration name; default `discord`.
 */
export default async function getMe(params: Record<string, unknown> = {}) {
	const input: InputRecord = inputRecord(params)
	const lane = requiredLane(input, 'bot')
	if (lane === 'oauth') {
		return projectUser(lane, (await discordOauthRequest('/users/@me', input)) as DiscordUser)
	}
	if (lane === 'bot') {
		return projectUser(lane, (await discordBotRequest('/users/@me', input)) as DiscordUser)
	}
	const exhaustive: never = lane
	throw new Error('Unsupported Discord lane: ' + String(exhaustive))
}