|
| 1 | +import 'dotenv/config'; |
| 2 | + |
| 3 | +import mongoose from 'mongoose'; |
| 4 | + |
| 5 | +import { Community, Module, ModuleNames } from '@togethercrew.dev/db'; |
| 6 | + |
| 7 | +import config from '../../config'; |
| 8 | +import logger from '../../config/logger'; |
| 9 | + |
| 10 | +async function connectToMongoDB() { |
| 11 | + try { |
| 12 | + await mongoose.connect(config.mongoose.serverURL); |
| 13 | + logger.info('Connected to MongoDB!'); |
| 14 | + } catch (error) { |
| 15 | + logger.fatal('Failed to connect to MongoDB!'); |
| 16 | + throw error; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +export const up = async () => { |
| 21 | + await connectToMongoDB(); |
| 22 | + |
| 23 | + try { |
| 24 | + const communities = await Community.find({}).exec(); |
| 25 | + logger.info(`Found ${communities.length} communities.`); |
| 26 | + |
| 27 | + const newModuleNames = [ModuleNames.Announcements, ModuleNames.CommunityHealth, ModuleNames.CommunityInsights]; |
| 28 | + |
| 29 | + for (const community of communities) { |
| 30 | + for (const moduleName of newModuleNames) { |
| 31 | + const newModule = new Module({ |
| 32 | + name: moduleName, |
| 33 | + community: community._id, |
| 34 | + activated: true, |
| 35 | + options: { platforms: [] }, |
| 36 | + }); |
| 37 | + await newModule.save(); |
| 38 | + logger.info(`Created module "${moduleName}" for community ${community._id}`); |
| 39 | + } |
| 40 | + } |
| 41 | + } catch (error) { |
| 42 | + logger.error('Error during migration up:', error); |
| 43 | + throw error; |
| 44 | + } finally { |
| 45 | + await mongoose.connection.close(); |
| 46 | + logger.info('MongoDB connection closed.'); |
| 47 | + } |
| 48 | +}; |
| 49 | + |
| 50 | +export const down = async () => { |
| 51 | + await connectToMongoDB(); |
| 52 | + |
| 53 | + try { |
| 54 | + const moduleNamesToDelete = [ModuleNames.Announcements, ModuleNames.CommunityHealth, ModuleNames.CommunityInsights]; |
| 55 | + const result = await Module.deleteMany({ name: { $in: moduleNamesToDelete } }); |
| 56 | + logger.info(`Migration down: deleted ${result.deletedCount} modules.`); |
| 57 | + } catch (error) { |
| 58 | + logger.error('Error during migration down:', error); |
| 59 | + throw error; |
| 60 | + } finally { |
| 61 | + await mongoose.connection.close(); |
| 62 | + logger.info('MongoDB connection closed.'); |
| 63 | + } |
| 64 | +}; |
0 commit comments