0

[Recommended] Trigger a new pipeline

by
Published Dec 20, 2024

Trigger a pipeline given a pipeline definition ID. Supports all integrations except GitLab.

Script circleci Verified

The script

Submitted by hugo697 Bun
Verified 536 days ago
1
//native
2
type Circleci = {
3
	token: string
4
}
5
/**
6
 * [Recommended] Trigger a new pipeline
7
 * Trigger a pipeline given a pipeline definition ID. Supports all integrations except GitLab.
8
 */
9
export async function main(
10
	auth: Circleci,
11
	provider: 'github' | 'gh' | 'bitbucket' | 'bb' | 'circleci',
12
	organization: string,
13
	project: string,
14
	body: {
15
		definition_id?: string
16
		config?: { branch?: string; tag?: string }
17
		checkout?: { branch?: string; tag?: string }
18
		parameters?: {}
19
	}
20
) {
21
	const url = new URL(
22
		`https://circleci.com/api/v2/project/${provider}/${organization}/${project}/pipeline/run`
23
	)
24

25
	const response = await fetch(url, {
26
		method: 'POST',
27
		headers: {
28
			'Content-Type': 'application/json',
29
			'Circle-Token': auth.token
30
		},
31
		body: JSON.stringify(body)
32
	})
33
	if (!response.ok) {
34
		const text = await response.text()
35
		throw new Error(`${response.status} ${text}`)
36
	}
37
	return await response.json()
38
}
39