Created
April 18, 2023 14:06
-
-
Save MikeIbberson/660f7ed97ac76080bcfcbeea61872ce4 to your computer and use it in GitHub Desktop.
How to migrate email templates from the local file system to the database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @NOTE | |
* Before v3, all Mailgun email templates belonged to a separate folder in the codebase. | |
* The templates were then compiled into HTML and uploaded via Mailgun's API. This made version control a pain in production. | |
* It also made previewing templates difficult. | |
* | |
* Later versions of Q3 offer an in-app email editor. | |
* To use this feature, you'll need to migrate your email templates from the file system to the database. | |
* You can write a script to accomplish this task. | |
* | |
* Remember: you'll need to setup permissions for the email collection and/or specify the collection name using the EMAIL_TEMPLATES_COLLECTION environment variable. | |
*/ | |
// depends on your env | |
process.env.WEB_CONCURRENCY = 1; | |
const fs = require('fs'); | |
const path = require('path'); | |
const mongoose = require('mongoose'); | |
const cluster = require('cluster'); | |
const config = require('../lib/config'); | |
// most common location for v2 | |
const RELATIVE_PATH_TO_TEMPLATES = '../../.mailgun/templates'; | |
// typically null, since v2 did not support multitenancy | |
const TENANT = null; | |
(async function moveTemplatesToDatabase() { | |
if (!cluster.isMaster) return; | |
await config.connect(); | |
const data = []; | |
const dir = path.resolve(__dirname, RELATIVE_PATH_TO_TEMPLATES); | |
await new Promise((resolve) => { | |
fs.readdir(dir, (err, files = []) => { | |
files.forEach((file) => { | |
const name = file.split('.')[0]; | |
const filePath = path.resolve(dir, file); | |
const mjml = fs.readFileSync(filePath, 'utf8').replace(/\.mjml/g, ''); | |
data.push({ | |
active: true, | |
tenant: TENANT, | |
name, | |
mjml, | |
}); | |
}); | |
resolve(); | |
}); | |
}); | |
const res = await mongoose.models.emails.create(data); | |
console.log(`Migrated ${res.length} template(s)`); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment