List Collection Items
One script reply has been approved by the moderators Verified

List of all Items within a Collection. Required scope | CMS:read

Created by hugo697 514 days ago Picked 1 time
Submitted by hugo697 Bun
Verified 514 days ago
1
//native
2
type Webflow = {
3
	token: string
4
}
5

6
export async function main(
7
	auth: Webflow,
8
	collection_id: string,
9
	cmsLocaleId: string | undefined,
10
	offset: string | undefined,
11
	limit: string | undefined,
12
	name: string | undefined,
13
	slug: string | undefined,
14
	lastPublished: any,
15
	sortBy: 'lastPublished' | 'name' | 'slug' | undefined,
16
	sortOrder: 'asc' | 'desc' | undefined
17
) {
18
	const url = new URL(`https://api.webflow.com/v2/collections/${collection_id}/items`)
19

20
	for (const [k, v] of [
21
		['cmsLocaleId', cmsLocaleId],
22
		['offset', offset],
23
		['limit', limit],
24
		['name', name],
25
		['slug', slug],
26
		['sortBy', sortBy],
27
		['sortOrder', sortOrder]
28
	]) {
29
		if (v !== undefined && v !== '' && k !== undefined) {
30
			url.searchParams.append(k, v)
31
		}
32
	}
33

34
	encodeParams({ lastPublished }).forEach((v, k) => {
35
		if (v !== undefined && v !== '') {
36
			url.searchParams.append(k, v)
37
		}
38
	})
39

40
	const response = await fetch(url, {
41
		method: 'GET',
42
		headers: {
43
			Authorization: 'Bearer ' + auth.token
44
		},
45
		body: undefined
46
	})
47

48
	if (!response.ok) {
49
		const text = await response.text()
50
		throw new Error(`${response.status} ${text}`)
51
	}
52

53
	return await response.json()
54
}
55

56
function encodeParams(o: any) {
57
	function iter(o: any, path: string) {
58
		if (Array.isArray(o)) {
59
			o.forEach(function (a) {
60
				iter(a, path + '[]')
61
			})
62
			return
63
		}
64

65
		if (o !== null && typeof o === 'object') {
66
			Object.keys(o).forEach(function (k) {
67
				iter(o[k], path + '[' + k + ']')
68
			})
69
			return
70
		}
71

72
		data.push(path + '=' + o)
73
	}
74

75
	const data: string[] = []
76

77
	Object.keys(o).forEach(function (k) {
78
		if (o[k] !== undefined) {
79
			iter(o[k], k)
80
		}
81
	})
82

83
	return new URLSearchParams(data.join('&'))
84
}
85