-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathctflDownload.js
49 lines (40 loc) · 1.64 KB
/
ctflDownload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* ==========================================================
This shortcode takes a file from a contentful media-input field and caches it locally.
The file is then written to dist/downloads using the file's id as filename.
It returns a link to the downloaded file.
Required properties:
- downloadObj -> The whole file object from contentful (not just the URL!)
Optional properties:
- title -> will be used as filename for the download HTML-attribute
- classes -> list of classes that is applied to the link
========================================================== */
const EleventyFetch = require("@11ty/eleventy-fetch");
const fs = require("fs");
async function ctflDownloadShortcode(content, ctflDownload) {
const url = "https:" + ctflDownload.downloadObj.fields.file.url;
const filetype = url.split(".").pop();
const filename = ctflDownload.downloadObj.sys.id;
const title = ctflDownload.title ? ctflDownload.title : filename;
const classes = ctflDownload.classes ? ctflDownload.classes : "";
let data = await EleventyFetch(url, {
duration: "1d",
directory: ".cache",
});
const dir = "dist/downloads";
// create new directory
try {
// first check if directory already exists
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
} catch (err) {
console.log(err);
}
fs.writeFile(`dist/downloads/${filename}.${filetype}`, data, (err) => {
// Checking for errors
if (err) throw err;
console.log("Done writing " + filename); // Success
});
return `<a class="${classes}" href="/downloads/${filename}.${filetype}" download="${title}">${content}</a>`;
}
module.exports = ctflDownloadShortcode;