Files
back_end_oudelaa/scripts/sync-feed-indexes.js

30 lines
1.3 KiB
JavaScript

// Add only the named feed indexes. Never drops or rebuilds unrelated indexes.
const mongoose = require('mongoose');
const { PostSchema } = require('../dist/legacy/src/modules/posts/schemas/post.schema');
async function main() {
const indexes = PostSchema.indexes()
.filter(([, options]) => ['feed_trending_order_v1', 'feed_popular_order_v1', 'feed_recent_order_v1'].includes(options.name))
.map(([key, options]) => ({ key, ...options }));
if (indexes.length !== 3) throw new Error('Build the latest code before synchronizing feed indexes');
if (process.argv.includes('--dry-run')) {
console.log(JSON.stringify(indexes, null, 2));
return;
}
if (!process.env.MONGODB_URI) throw new Error('Set MONGODB_URI explicitly for the intended database');
const connection = mongoose.createConnection(process.env.MONGODB_URI, { autoIndex: false });
try {
await connection.asPromise();
const names = await connection.collection('posts').createIndexes(indexes);
console.log(JSON.stringify({ createdOrExistingIndexes: names }));
} finally {
await connection.close();
}
}
main().catch((error) => {
// Connection errors may contain credentials; do not print the URI or raw errors.
console.error(`Feed index synchronization failed (${error.name || 'Error'}). Verify the build and database configuration.`);
process.exitCode = 1;
});