bookManagement/populate_locations.js

54 lines
2.0 KiB
JavaScript

import { sequelize, Location } from './models.js';
const locationsToCreate = [];
// Cubes 1-10
for (let i = 1; i <= 10; i++) {
locationsToCreate.push({ name: 'Cube', shelf: i.toString() });
}
// Office Shelves 1-6
for (let i = 1; i <= 6; i++) {
locationsToCreate.push({ name: 'Office Shelf', shelf: i.toString() });
}
// Miscellaneous placements
locationsToCreate.push({ name: 'Upstairs', shelf: 'Misc' });
locationsToCreate.push({ name: 'Downstairs', shelf: 'Misc' });
async function populateLocations() {
try {
// Optional: Sync database to ensure tables are created
await sequelize.sync(); // Often done in your main app setup
// Check if locations already exist to avoid duplicates if script is run multiple times
// This is a simple check; more robust checks might be needed for production
const existingLocations = await Location.findAll();
const newLocations = locationsToCreate.filter(ltc =>
!existingLocations.some(el => el.name === ltc.name && el.shelf === ltc.shelf)
);
if (newLocations.length > 0) {
await Location.bulkCreate(newLocations);
console.log(`${newLocations.length} locations have been successfully added.`);
} else {
console.log('All specified locations already exist in the database. No new locations added.');
}
// Select all locations from the database
const [locationsFromQuery] = await sequelize.query('SELECT * FROM locations'); // sequelize.query returns [results, metadata]
console.log('All locations:', locationsFromQuery);
} catch (error) {
console.error('Error populating locations:', error);
} finally {
// Close the database connection if the script is standalone and not part of a larger app run
if (sequelize && typeof sequelize.close === 'function') {
await sequelize.close();
console.log('Database connection closed.');
}
}
}
populateLocations();