Skip to content

Commit

Permalink
Add logging
Browse files Browse the repository at this point in the history
  • Loading branch information
grantfitzsimmons committed Oct 30, 2024
1 parent 3e1d786 commit ab24dbd
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions app/pages/api/databases/[name]/clone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export default async function handler(
request: NextApiRequest,
res: NextApiResponse
) {
console.log('Received request to clone database.');

const user = await getUser(request, res);
if (typeof user === 'undefined') return;

Expand All @@ -24,24 +26,30 @@ export default async function handler(
const existingDatabaseName = request.query.name as string | undefined;

if (!existingDatabaseName) {
console.error('Existing database name is required.');
return res.status(400).json({ error: 'Existing database name is required' });
}

// Validate that the existing database name is valid
if (existingDatabaseName.match(/^\w+$/) === null) {
console.error('Existing database name is invalid.');
return res.status(400).json({ error: 'Existing database name is invalid' });
}

try {
// Generate a new database name with timestamp
console.log(`Cloning database: ${existingDatabaseName}`);

const now = new Date();
const timestamp = `${now.getFullYear()}_${String(now.getMonth() + 1).padStart(2, '0')}_${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}_${String(now.getMinutes()).padStart(2, '0')}`;
const newDatabaseName = `${existingDatabaseName}_${timestamp}`;

console.log(`New database name will be: ${newDatabaseName}`);

// Create the new database
await connection.execute(`DROP DATABASE IF EXISTS \`${newDatabaseName}\``);
await connection.execute(`CREATE DATABASE \`${newDatabaseName}\``);
console.log(`Database ${newDatabaseName} created successfully.`);

// Clone the existing database into the new database
const cloneChild = spawn(
Expand Down Expand Up @@ -81,11 +89,17 @@ export default async function handler(
throw new Error(`Failed to clone database from ${existingDatabaseName} to ${newDatabaseName}`);
});

importChild.stderr.on('data', (error) => {
console.error('Error importing database:', error.toString());
});

await new Promise((resolve, reject) => {
importChild.on('exit', (code) => {
if (code !== 0) {
console.error(`Failed to import data into database: ${newDatabaseName}`);
return reject(new Error(`Failed to import data into database: ${newDatabaseName}`));
}
console.log(`Data imported successfully into database: ${newDatabaseName}`);
resolve(null);
});
});
Expand All @@ -94,6 +108,7 @@ export default async function handler(
message: `Database cloned successfully: ${newDatabaseName}`,
});
} catch (error: any) {
console.error('Error during cloning process:', error.toString());
res.status(500).json({ error: error.toString() });
}
}

0 comments on commit ab24dbd

Please sign in to comment.