Skip to content

Commit 77d433a

Browse files
committed
refactor: save uploaded file only when validation is successful
1 parent fc71d91 commit 77d433a

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

opendata.swiss/ui/server/api/showcases.post.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,14 @@ export default defineEventHandler(async (event) => {
3939
const contentRoot = `${rootDir}/content`
4040
const imageRoot = `${rootDir}/public/img/uploads`
4141

42+
const uploads: Array<() => Promise<void>> = []
4243
const body = await readMultipartFormData(event) as PayloadData
4344
const showcase: Showcase = {
4445
it: empty(),
4546
de: empty(),
4647
fr: empty(),
4748
en: empty()
4849
}
49-
5050
const titleDe = body.find(field => field.name === 'title-de')?.data?.toString()
5151
showcase.slug = slugify(titleDe!, { lower: true, locale: 'de' })
5252

@@ -80,15 +80,15 @@ export default defineEventHandler(async (event) => {
8080
break
8181
case "image": {
8282
const imagePath = `${imageRoot}/${showcase.slug}-image.jpg`
83-
await fs.writeFile(imagePath, data)
83+
uploads.push(fs.writeFile.bind(null, imagePath, data))
8484
}
8585
break
8686
}
8787
}
8888

8989
return validate(event, showcase) || (async () => {
9090
// TODO: choose to save to GitHub or locally based on environment
91-
await save(showcase, contentRoot)
91+
await save(showcase, uploads, contentRoot)
9292

9393
if (process.env.NODE_ENV === 'production') {
9494
// TODO: commit and push to repo
@@ -99,17 +99,19 @@ export default defineEventHandler(async (event) => {
9999
})()
100100
});
101101

102-
function save(showcase: Showcase, contentRoot: string) {
102+
function save(showcase: Showcase, uploads: Array<() => Promise<void>>, contentRoot: string) {
103103
const { slug } = showcase
104104

105-
return Promise.all(languages.map(language => {
105+
const writeContent = languages.map(language => {
106106
const path = `${contentRoot}/showcases/${slug}.${language}.md`
107107

108108
const { body, ...meta } = showcase[language]
109109
const frontMatter = yaml.stringify(meta)
110110

111111
return fs.writeFile(path, `---\n${frontMatter}---\n${body}`)
112-
}))
112+
})
113+
114+
return Promise.all([...writeContent, ...uploads.map(upload => upload())])
113115
}
114116

115117
interface Setter {

0 commit comments

Comments
 (0)