const { parse } = require("path")
const get = require("lodash.get")
const { addedFileContents, modifiedFileContents } = event
const fileArticleMappings = get($checkpoint, 'fileArticleMappings', {})
for (const file of addedFileContents) {
const { contents, path } = file
const { name } = parse(path)
title = name.replace(/[-_]/g, " ")
const { id } = await createArticle(contents, title)
console.log(`Created new article tied to file ${path}`)
fileArticleMappings[path] = id
}
for (const file of modifiedFileContents) {
const { path, contents } = file
const { name } = parse(path)
title = name.replace(/[-_]/g, " ")
if (!(path in fileArticleMappings)) {
console.log(`Updated file ${path} not tracked in dev.to. Creating new article!`)
const { id } = await createArticle(contents, title)
fileArticleMappings[path] = id
continue
}
console.log(`Updating article tied to file ${path}`)
await updateArticle(fileArticleMappings[path], contents, title)
}
$checkpoint = {
...$checkpoint,
fileArticleMappings,
}
async function createArticle(body_markdown, title) {
return await require("@pipedreamhq/platform").axios(this, {
method: "POST",
url: `https://dev.to/api/articles`,
headers: {
"api-key": `${auths.dev_to.api_key}`,
"Content-Type": "application/json"
},
data: {
article: {
body_markdown,
title,
}
}
})
}
async function updateArticle(id, body_markdown, title) {
return await require("@pipedreamhq/platform").axios(this, {
method: "PUT",
url: `https://dev.to/api/articles/${id}`,
headers: {
"api-key": `${auths.dev_to.api_key}`,
"Content-Type": "application/json"
},
data: {
article: {
body_markdown,
title,
}
}
})
}