Skip to content

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

Package listing

@kody/airtable

src/viewer.ts

48 lines · 1.4 KB · TypeScript
import { pickAuthInput } from './auth.ts'
import { airtableRequest } from './client.ts'
import type { AirtableAuthInput } from './types.ts'
import { requireRecord } from './types.ts'

export type AirtableViewer = {
	id: string
	scopeCount: number
	hasEmail: boolean
}

export type ViewerInput = AirtableAuthInput

/**
 * Return the authenticated Airtable user id and scope count (no email).
 * @example
 * import getViewer from 'kody:@kody/airtable/viewer'
 * const viewer = await getViewer()
 */
export async function getViewer(input: ViewerInput = {}): Promise<AirtableViewer> {
	const result = await airtableRequest<{
		id?: string
		email?: string
		scopes?: Array<string>
	}>({
		...input,
		operation: 'whoami',
		path: '/meta/whoami',
	})
	const body = result.data && typeof result.data === 'object' ? result.data : {}
	return {
		id: typeof body.id === 'string' ? body.id : '',
		scopeCount: Array.isArray(body.scopes) ? body.scopes.length : 0,
		hasEmail: typeof body.email === 'string' && body.email.length > 0,
	}
}

/**
 * Return the authenticated Airtable user id and scope count (no email).
 * @example
 * import getViewer from 'kody:@kody/airtable/viewer'
 * const viewer = await getViewer({ integrationName: 'airtable-work' })
 */
export default async function viewerEntrypoint(
	params: ViewerInput & Record<string, unknown> = {},
) {
	return getViewer(pickAuthInput(requireRecord(params, 'viewer')))
}