Skip to content

Instantly share code, notes, and snippets.

@angheloko
Created January 28, 2021 06:13
Show Gist options
  • Save angheloko/7bbfff17c2b74e7b61d3cb048c4ccf6b to your computer and use it in GitHub Desktop.
Save angheloko/7bbfff17c2b74e7b61d3cb048c4ccf6b to your computer and use it in GitHub Desktop.
Download data from Cloud Firestore and store locally to be used for Nuxt Content
const fs = require('fs')
const admin = require('firebase-admin')
const TurndownService = require('turndown')
const turndownService = new TurndownService({
codeBlockStyle: 'fenced'
})
const serviceAccount = require('./path/to/serviceAccountKey.json')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
const db = admin.firestore()
function convertToMarkdown(value) {
return turndownService.turndown(value)
}
function escapeQuotes(value) {
return value.replace(/"/gi, '\\"')
}
function buildFrontMatter(data) {
const createdAt = data.created.toDate().toISOString()
const updatedAt = data.changed.toDate().toISOString()
let tags = '';
if (data.tags.length === 0) {
tags = '[]'
} else {
for (const tag of data.tags) {
tags += `\n - ${tag}`
}
}
return `title: "${escapeQuotes(data.title)}"
subtitle: "${escapeQuotes(data.teaser)}"
lead: "${escapeQuotes(data.lead)}"
description: "${escapeQuotes(data.description)}"
createdAt: ${createdAt}
updatedAt: ${updatedAt}
cover:
image: "${data.imageUrl}"
alt: "${escapeQuotes(data.title)} cover image"
caption: "${escapeQuotes(data.imageCaption)}"
thumb: "${data.teaserImageUrl}"
tags: ${tags}`
}
async function main() {
const blogsRef = db.collection('blogs')
const snapshot = await blogsRef
.where('published', '==', true)
.orderBy('created')
.get()
for (const doc of snapshot.docs) {
console.log(`Exporting ${doc.id}`)
const data = {
... {
lead: '',
imageCaption: '',
description: ''
},
...doc.data()
}
console.log(doc.data())
let markdown = `---
${buildFrontMatter(data)}
---
${convertToMarkdown(data.body)}`
try {
fs.writeFileSync(`/path/to/app/content/blog/${doc.id}.md`, markdown)
} catch (err) {
console.error(err)
}
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment