-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
52 lines (47 loc) · 1.67 KB
/
main.js
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
import express from 'express';
import axios from 'axios';
import { createObjectCsvWriter } from 'csv-writer';
import path from 'path';
const app= express();
const PORT= 3000;
app.get("/generate-csv", async(req,res)=> {
try {
const [userResponses, postsResponse, commentResponse] = await Promise.all([
axios.get('https://jsonplaceholder.typicode.com/users'),
axios.get('https://jsonplaceholder.typicode.com/posts'),
axios.get('https://jsonplaceholder.typicode.com/comments'),
]);
const users= userResponses.data;
const posts= postsResponse.data;
const comments= commentResponse.data;
const data= users.map(user=> {
const post= posts.find(p=> p.id===user.id);
const comment= comments.find(c=> c.id===user.id);
return {
id: user.id,
name: user.name,
title: post.title,
body: comment.body,
};
});
const csvWriter= createObjectCsvWriter({
path: 'result.csv',
header: [
{id: 'name', title: 'Name'},
{id: 'title', title: 'Title'},
{id: 'body', title: 'Body'},
],
});
await csvWriter.writeRecords(data);
res.json({ filePath: path.resolve('result.csv') });
} catch(error) {
console.error('Error generating CSV:', error.message);
res.status(500).json({
error: 'Failed to generate CSV file',
details: error.message,
});
}
});
app.listen(PORT, ()=>{
console.log(`Server is running on:${PORT}`);
});