This directory contains a csv-exporter.js file where the method to export the orders as CSV is declared.
The json2csv package allows you to format the data exported. It can be useful in particular when you have fields of the type JSON that you may want to unwind. You can take a look at the json2csv documentation here.
csv-exporter.js
const { parse } =require('json2csv');functionexportCustomerOrdersAsCSV(response, data) {// set the response header to tell the browser to expect a csvresponse.setHeader('Content-Type','text/csv');response.setHeader('Content-Disposition',`attachment; filename=cust-${data[0].customerIdKey}-orders.csv`);response.setHeader('Access-Control-Expose-Headers','Content-Disposition');// list the fields of the orders that you want to display as columns of the csvconstfields= ['ref','shippingStatus','createdAt','UpdatedAt','beingProcessedAt','readyForShippingAt','inTransitAt','shippedAt', ];// convert the array of records into a csvtry {constcsv=parse(data, { fields });returnresponse.send(csv); } catch (err) {returnresponse.status(500).json({ err }); }}module.exports= exportCustomerOrdersAsCSV;
Directory: /routes
This directory contains the customers.js file where the logic of the smart action is implemented.
customers.js
constexpress=require('express');const { PermissionMiddlewareCreator } =require('forest-express-sequelize');const { orders } =require('../models');constexportCustomerOrdersAsCSV=require('../utils/csv-exporter');constrouter=express.Router();constpermissionMiddlewareCreator=newPermissionMiddlewareCreator('customers');router.post('/actions/export-orders-as-csv',permissionMiddlewareCreator.smartAction(),async (req, res) => {// Get the current record idconstrecordId=req.body.data.attributes.ids[0];// get an array of records that are the orders of the customer and export themreturnorders.findAll({ where: { customerIdKey: recordId } }).then((data) =>exportCustomerOrdersAsCSV(res, data));});module.exports= router;