require('dotenv').config(); const axios = require('axios'); //connect database //development const mongoose = require('mongoose'); const WorkTicketVisits = require('../models/workticketvisit'); mongoose.connect('mongodb://127.0.0.1:27017/test') .then(() => { console.log("Connection Open") }) .catch(err => { console.log("ERROR") console.log(err) }); const db = mongoose.connection; db.on("error", console.error.bind(console, "connection error")); db.once("open", () => { console.log("Database connected"); }); const seedDB = async () => { await WorkTicketVisits.deleteMany({}); try { const { ASPIRE_API_CLIENT_ID, ASPIRE_TOKEN } = process.env; const apiUrl = `https://cloud-api.youraspire.com/WorkTicketVisits?%24select=WorkTicketVisitID%2CWorkTicketID%2CRouteName%2CScheduledDate&%24filter=ScheduledDate%20gt%202024-01-29`; const headers = { 'Authorization': `Bearer ${ASPIRE_TOKEN}`, 'Client-ID': ASPIRE_API_CLIENT_ID, 'Content-Type': 'application/json', }; const response = await axios.get(apiUrl, { headers }); const workticketvisitsArray = response.data //save to database before going to client // therefore logic to have databse filter logic beofre going to client // await workticketvisits.save(); // Save each work ticket visit to the database for (const workticketvisit of workticketvisitsArray) { const visit = new WorkTicketVisits({ WorkTicketVisitID: workticketvisit.WorkTicketVisitID, WorkTicketID: workticketvisit.WorkTicketID, ScheduledDate: workticketvisit.ScheduledDate, RouteName: workticketvisit.RouteName }); await visit.save(); } console.log('Seeding completed successfully'); } catch (error) { console.error('Seeding error:', error.message); } finally { // Close the database connection after seeding mongoose.connection.close(); } }; seedDB();