Skip to content

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

Package listing

@kody/fly

src/organizations.ts

56 lines · 2.0 KB · TypeScript
import { collectConnection, requestGraphql } from './fly-core.ts'
import type { FlyOrganizationInput } from './types.ts'

export async function listOrganizations(params: FlyOrganizationInput = {}) {
	const first = Math.min(Math.max(Math.floor(Number(params.first) || 100), 1), 100)
	const organizations = await collectConnection(
		async (after) => {
			const data = await requestGraphql({
				...params,
				query:
					'query($first: Int, $after: String) { organizations(first: $first, after: $after) { nodes { id name slug } pageInfo { hasNextPage endCursor } } }',
				variables: { first, after },
			})
			return data.organizations
		},
		{ maxPages: params.maxPages },
	)
	return { organizations }
}

export async function getOrganization(params: FlyOrganizationInput = {}) {
	const slug = String(params.organizationSlug || params.orgSlug || params.slug || '').trim()
	const id = String(params.organizationId || params.id || '').trim()
	if (id) {
		const data = await requestGraphql({
			...params,
			query: 'query($id: ID!) { organization(id: $id) { id name slug } }',
			variables: { id },
		})
		return data.organization
	}
	if (!slug) {
		throw new Error('organizationSlug or organizationId is required when resolving a single organization.')
	}
	const result = await listOrganizations({ ...params, first: 100 })
	return (
		result.organizations.find(
			(organization: any) => organization.slug === slug || organization.name === slug,
		) || null
	)
}

/**
 * List Fly organizations or resolve one by slug/id. Does not assume an org slug.
 * @returns `{ organizations }` or `{ organization }` when a slug/id filter is passed.
 * @example
 * import organizations from 'kody:@kody/fly/organizations'
 * const result = await organizations()
 * // => { organizations: [{ id, name, slug }, ...] }
 */
export default async function organizations(params: FlyOrganizationInput = {}) {
	if (params.organizationId || params.organizationSlug || params.orgSlug || params.slug || params.id) {
		return { organization: await getOrganization(params) }
	}
	return await listOrganizations(params)
}