Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
3
Indexable
Never
// Step 1: Install the required dependencies
const { createApolloFetch } = require('apollo-fetch');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const axios = require('axios');

// Step 2: Define the GraphQL queries
const query1 = `
  query {
    users {
      id
      name
      email
    }
  }
`;

const query2 = `
  query {
    orders {
      id
      date
      total
    }
  }
`;

// Step 3: Use axios to make a POST request to the GraphQL API endpoint
axios.post('https://example.com/graphql', {
  query: `
    ${query1}
    ${query2}
  `
}).then(response => {
  // Step 4: Process the response data and transform it into a CSV format
  const users = response.data.data.users;
  const orders = response.data.data.orders;

  const data = [];

  users.forEach(user => {
    data.push({
      id: user.id,
      name: user.name,
      email: user.email,
      type: 'User'
    });
  });

  orders.forEach(order => {
    data.push({
      id: order.id,
      name: `Order #${order.id}`,
      email: '',
      type: 'Order'
    });
  });

  // Step 5: Use csv-writer to create and write the data to a CSV file
  const csvWriter = createCsvWriter({
    path: 'data.csv',
    header: [
      { id: 'id', title: 'ID' },
      { id: 'name', title: 'Name' },
      { id: 'email', title: 'Email' },
      { id: 'type', title: 'Type' },
    ]
  });

  csvWriter.writeRecords(data)
    .then(() => console.log('Data exported successfully.'));
}).catch(error => {
  console.error(error);
});