Brotherton-Aspire-App/seeds/workticketseed.js
2024-02-02 16:44:34 -08:00

65 lines
2.2 KiB
JavaScript

require('dotenv').config();
const axios = require('axios');
//connect database
//development
const mongoose = require('mongoose');
const WorkTickets = require('../models/workticket');
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 WorkTickets.deleteMany({});
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_TOKEN, ASPIRE_REFRESH_TOKEN } = process.env;
const apiUrl = `https://cloud-api.youraspire.com/WorkTickets?%24select=OpportunityID%2CPrice%2CWorkTicketID%2CBranchName%2CWorkTicketStatusName%2CScheduledStartDate&%24filter=WorkTicketStatusName%20eq%20%27Open%27`;
const headers = {
'Authorization': `Bearer ${ASPIRE_TOKEN}`,
'Client-ID': ASPIRE_API_CLIENT_ID,
'Content-Type': 'application/json',
};
const response = await axios.get(apiUrl, { headers });
const workticketArray = response.data
//save to database before going to client
// therefore logic to have databse filter logic beofre going to client
// await worktickets.save();
// Save each work ticket to the database
for (const workticket of workticketArray) {
const ticket = new WorkTickets({
WorkTicketID: workticket.WorkTicketID,
Notes: workticket.Notes,
OpportunityServiceID: workticket.OpportunityServiceID,
OpportunityID: workticket.OpportunityID,
WorkTicketStatusName: workticket.WorkTicketStatusName,
ScheduledStartDate: workticket.ScheduledStartDate
});
await ticket.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();