Brotherton-Aspire-App/seeds/contact.js

67 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-02-03 00:44:34 +00:00
require('dotenv').config();
const axios = require('axios');
//connect database
//development
const mongoose = require('mongoose');
const Contact = require('../models/contact');
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 Contact.deleteMany({});
try {
const { ASPIRE_API_CLIENT_ID, ASPIRE_TOKEN } = process.env;
2024-02-03 00:55:28 +00:00
//Route pullung specific data points from ASPIRE API
2024-02-03 00:44:34 +00:00
const apiUrl = `https://cloud-api.youraspire.com/Contacts?%24select=ContactID%2CCompanyName%2CContactTypeName%2CFirstName%2CLastName%2CEmail%2CMobilePhone`;
const headers = {
'Authorization': `Bearer ${ASPIRE_TOKEN}`,
'Client-ID': ASPIRE_API_CLIENT_ID,
'Content-Type': 'application/json',
};
const response = await axios.get(apiUrl, { headers });
const contactArray = response.data
//save to database before going to client
// therefore logic to have databse filter logic beofre going to client
2024-02-03 00:55:28 +00:00
2024-02-03 00:44:34 +00:00
for (const contactPerson of contactArray) {
const contact = new Contact({
ContactID: contactPerson.ContactID,
CompanyName: contactPerson.CompanyName,
ContactTypeName: contactPerson.ContactTypeName,
FirstName: contactPerson.FirstName,
LastName: contactPerson.LastName,
Email: contactPerson.Email,
MobilePhone: contactPerson.MobilePhone,
});
await contact.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();