1 | |
2 | type Pinterest = { |
3 | token: string; |
4 | }; |
5 | |
6 | * Get catalogs items |
7 | * Get the items of the catalog owned by the "operation user_account". |
8 | */ |
9 | export async function main( |
10 | auth: Pinterest, |
11 | ad_account_id: string | undefined, |
12 | country: string | undefined, |
13 | language: string | undefined, |
14 | item_ids: string | undefined, |
15 | filters: any, |
16 | ) { |
17 | const url = new URL(`https://api.pinterest.com/v5/catalogs/items`); |
18 | for (const [k, v] of [ |
19 | ["ad_account_id", ad_account_id], |
20 | ["country", country], |
21 | ["language", language], |
22 | ["item_ids", item_ids], |
23 | ]) { |
24 | if (v !== undefined && v !== "" && k !== undefined) { |
25 | url.searchParams.append(k, v); |
26 | } |
27 | } |
28 | encodeParams({ filters }).forEach((v, k) => { |
29 | if (v !== undefined && v !== "") { |
30 | url.searchParams.append(k, v); |
31 | } |
32 | }); |
33 | const response = await fetch(url, { |
34 | method: "GET", |
35 | headers: { |
36 | Authorization: "Bearer " + auth.token, |
37 | }, |
38 | body: undefined, |
39 | }); |
40 | if (!response.ok) { |
41 | const text = await response.text(); |
42 | throw new Error(`${response.status} ${text}`); |
43 | } |
44 | return await response.json(); |
45 | } |
46 |
|
47 | function encodeParams(o: any) { |
48 | function iter(o: any, path: string) { |
49 | if (Array.isArray(o)) { |
50 | o.forEach(function (a) { |
51 | iter(a, path + "[]"); |
52 | }); |
53 | return; |
54 | } |
55 | if (o !== null && typeof o === "object") { |
56 | Object.keys(o).forEach(function (k) { |
57 | iter(o[k], path + "[" + k + "]"); |
58 | }); |
59 | return; |
60 | } |
61 | data.push(path + "=" + o); |
62 | } |
63 | const data: string[] = []; |
64 | Object.keys(o).forEach(function (k) { |
65 | if (o[k] !== undefined) { |
66 | iter(o[k], k); |
67 | } |
68 | }); |
69 | return new URLSearchParams(data.join("&")); |
70 | } |
71 |
|