Edits history of script submission #9462 for ' List Live Collection Items (webflow)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    type Webflow = {
    	token: string
    }
    
    export async function main(
    	auth: Webflow,
    	collection_id: string,
    	cmsLocaleId: string | undefined,
    	offset: string | undefined,
    	limit: string | undefined,
    	name: string | undefined,
    	slug: string | undefined,
    	lastPublished: any,
    	sortBy: 'lastPublished' | 'name' | 'slug' | undefined,
    	sortOrder: 'asc' | 'desc' | undefined
    ) {
    	const url = new URL(`https://api.webflow.com/v2/collections/${collection_id}/items/live`)
    
    	for (const [k, v] of [
    		['cmsLocaleId', cmsLocaleId],
    		['offset', offset],
    		['limit', limit],
    		['name', name],
    		['slug', slug],
    		['sortBy', sortBy],
    		['sortOrder', sortOrder]
    	]) {
    		if (v !== undefined && v !== '' && k !== undefined) {
    			url.searchParams.append(k, v)
    		}
    	}
    
    	encodeParams({ lastPublished }).forEach((v, k) => {
    		if (v !== undefined && v !== '') {
    			url.searchParams.append(k, v)
    		}
    	})
    
    	const response = await fetch(url, {
    		method: 'GET',
    		headers: {
    			Authorization: 'Bearer ' + auth.token
    		},
    		body: undefined
    	})
    
    	if (!response.ok) {
    		const text = await response.text()
    		throw new Error(`${response.status} ${text}`)
    	}
    
    	return await response.json()
    }
    
    function encodeParams(o: any) {
    	function iter(o: any, path: string) {
    		if (Array.isArray(o)) {
    			o.forEach(function (a) {
    				iter(a, path + '[]')
    			})
    			return
    		}
    
    		if (o !== null && typeof o === 'object') {
    			Object.keys(o).forEach(function (k) {
    				iter(o[k], path + '[' + k + ']')
    			})
    			return
    		}
    
    		data.push(path + '=' + o)
    	}
    
    	const data: string[] = []
    
    	Object.keys(o).forEach(function (k) {
    		if (o[k] !== undefined) {
    			iter(o[k], k)
    		}
    	})
    
    	return new URLSearchParams(data.join('&'))
    }
    

    Submitted by hugo697 564 days ago