-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
112 lines (91 loc) · 2.84 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { writeCSV } from "https://deno.land/x/[email protected]/mod.ts";
import { ensureFile } from "https://deno.land/[email protected]/fs/mod.ts";
const [baseApiUrl, apiKey, apiSecret] = Deno.args;
const AUTH_URL = `${baseApiUrl}/api/oauth/token`;
const API_URL = `${baseApiUrl}/api/search/product`;
const profile = {
mappings: [
{
fileColumn: 'product_number',
entityPath: 'productNumber',
},
{
fileColumn: 'name',
entityPath: 'name',
},
{
fileColumn: 'stock',
entityPath: 'stock',
},
],
}
async function getAuthToken() {
try {
const response = await fetch(AUTH_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
grant_type: "client_credentials",
client_id: apiKey,
client_secret: apiSecret,
}),
});
if (!response.ok) {
throw new Error(`Failed to authenticate: ${response.statusText}`);
}
const data = await response.json();
return data.access_token;
} catch (error) {
console.error("Error fetching auth token:", error);
return null;
}
}
async function fetchData(token: string) {
try {
const headers = new Headers();
headers.set("Authorization", `Bearer ${token}`);
const response = await fetch(API_URL, {
method: "POST",
headers: headers,
});
if (!response.ok) {
throw new Error(`Failed to fetch data: ${response.statusText}`);
}
const data = await response.json();
return data.data;
} catch (error) {
console.error("Error fetching data:", error);
}
}
async function jsonToCSV(data: any[], filePath: string) {
await ensureFile(filePath);
const csvColumns = profile.mappings.map((mapping) => mapping.fileColumn);
const csvData = data.map((item) => {
return profile.mappings.map((mapping) => item.attributes[mapping.entityPath]);
});
const file = await Deno.open(filePath, { write: true, truncate: true });
await writeCSV(file, [csvColumns, ...csvData]);
file.close();
}
async function main() {
if (!baseApiUrl || !apiKey || !apiSecret) {
console.log("Please provide the base API URL, API key, and API secret.");
return;
}
const token = await getAuthToken();
if (!token) {
console.log("Failed to retrieve auth token.");
return;
}
const data = await fetchData(token);
if (data) {
const filePath = "./export.csv";
await jsonToCSV(data, filePath);
console.log(`Data has been written to ${filePath}`);
} else {
console.log("No data to write to CSV.");
}
}
main();