Skip to content
← Public packages

@kentcdodds/spotify

Spotify playback, playlist, search, library, and device helpers.

src/exports/play-pause.ts

42 lines · 1.4 KB · TypeScript
import {
	getPlaybackState,
	hasDeviceSelector,
	pausePlayback,
	startOrResumePlayback,
} from '../lib/spotify-api.ts'
import type { PlayPauseParams } from '../lib/export-types.ts'

/**
 * Toggle Spotify playback between play and pause on the active or specified device.
 * Prefer `deviceName` when targeting a device; omit selectors for the active device.
 * All params accept an optional `account` ('personal' | 'family', default 'personal').
 * @returns Action result with ok, action (started|resumed|paused), deviceId, and status.
 * @example
 * import playPause from 'kody:@kentcdodds/spotify/play-pause'
 * const result = await playPause({ account: 'personal' })
 * // => { ok: true, action: 'resumed', deviceId: '...', status: 204 }
 */
async function playPause(params: PlayPauseParams = {}) {
	const current = await getPlaybackState(params)
	const playbackDeviceId = current.playback?.device?.id ?? undefined
	const targetedParams = hasDeviceSelector(params)
		? params
		: { ...params, deviceId: params.deviceId ?? playbackDeviceId }

	if (current.nothingPlaying) {
		return await startOrResumePlayback({
			...params,
			fallbackDeviceId: params.fallbackDeviceId,
		})
	}
	if (current.playback?.is_playing) {
		return await pausePlayback(targetedParams)
	}
	return await startOrResumePlayback({
		...targetedParams,
		fallbackDeviceId: params.fallbackDeviceId,
		forceCollection: false,
	})
}

export default playPause