|
| 1 | +"use strict"; |
| 2 | +const env = require("../services/env.service"); |
| 3 | +const db = require("../services/database.service"); |
| 4 | + |
| 5 | +const fs = require("fs").promises; |
| 6 | +const path = require("path"); |
| 7 | +const templatesDirPath = path.join(__dirname, "../assets/email/marketingEmail/"); |
| 8 | + |
| 9 | +const EmailTemplate = require("../models/emailTemplate.model"); |
| 10 | + |
| 11 | +// load env |
| 12 | +const envLoadResult = env.load(path.join(__dirname, "../.env")); |
| 13 | +if (envLoadResult.error) { |
| 14 | + console.error(envLoadResult.error); |
| 15 | +} |
| 16 | + |
| 17 | +// connect to db |
| 18 | +db.connect(undefined, () => { |
| 19 | + onConnected() |
| 20 | + .catch((reason) => { |
| 21 | + console.error(reason); |
| 22 | + process.exit(1); |
| 23 | + }) |
| 24 | + .then(() => { |
| 25 | + process.exit(0); |
| 26 | + }); |
| 27 | +}); |
| 28 | + |
| 29 | +/** |
| 30 | + * Called when the db is connected. |
| 31 | + */ |
| 32 | +async function onConnected() { |
| 33 | + await migrateAll(); |
| 34 | + console.log("Finished migrating."); |
| 35 | +} |
| 36 | + |
| 37 | +/** |
| 38 | + * Inserts all email templates in assets to the db. |
| 39 | + */ |
| 40 | +async function migrateAll() { |
| 41 | + const filenames = await fs.readdir(templatesDirPath); |
| 42 | + for (const filename of filenames) { |
| 43 | + const filepath = path.join(templatesDirPath, filename); |
| 44 | + const data = await fs.readFile(filepath, 'utf-8'); |
| 45 | + const emailTemplateDoc = new EmailTemplate( |
| 46 | + { |
| 47 | + name: filename, |
| 48 | + content: data |
| 49 | + } |
| 50 | + ); |
| 51 | + await insertOne(emailTemplateDoc); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | + |
| 56 | +/** |
| 57 | + * Inserts an EmailTemplate document to the db. Prevents duplicate name. |
| 58 | + * @param {EmailTemplate} emailTemplateDoc |
| 59 | + */ |
| 60 | +async function insertOne(emailTemplateDoc) { |
| 61 | + const dup = await EmailTemplate.collection.findOne({ name: emailTemplateDoc.name }); |
| 62 | + if (!dup) { |
| 63 | + await EmailTemplate.collection.insertOne(emailTemplateDoc); |
| 64 | + console.log(`${emailTemplateDoc.name} is migrated.`); |
| 65 | + } else { |
| 66 | + console.error(`${emailTemplateDoc.name} already in database.`); |
| 67 | + } |
| 68 | +} |
0 commit comments