I have a blog type site that I've been working on, which is almost complete. I've used Eleventy and now I've hooked up Netlify CMS which required me to restructure some data.
Netlify CMS requires me to have separate files for the relation widget data, in this case authors. So I have an authors directory, which presently has 3 json files: jbloggs.json, etc, each object is flat, an example of one being:
./src/_data/authors/jbloggs.json
{
"key": "jbloggs",
"name": "Joe Bloggs",
// ... Removed for brevity
}
I initially created an array of objects and everything was working great:
./src/authors.json
[
{
"key": "jbloggs",
"name": "Joe Bloggs",
// ... Removed for brevity
},
{
"key": "user2",
"name": "User Two",
// ... Removed for brevity
}
]
What I need to do, is grab however many files are in my authors directory and add the objects from within each file to the array in my authors.json file. I've tried using json-concat, to no avail. I have fs and json-concat required in my eleventy file:
const files = [];
const {resolve} = require('path');
const source = resolve('./src/_data/authors');
const target = resolve('./src/authors.json');
fs.readdirSync(source).forEach((file) => {
files.push(file);
})
jsonConcat({ src: files, dest: target }, function (json) {
console.log(files); // returns an array of the correct filenames
console.log(target); // returns the path to the target file /Users/darrenlee/Desktop/WebApp/src/authors.json
console.log(json); // returns null
});
In my terminal I also get: [11ty] File changed: src/authors.json, but the file hasn't changed, I still only have 2 authors in there and the aim is to have all of the authors (currently 3) from the authors directory files.
Any help would be greatly appreciated.
Thank you
It turns out I was over-complicating things and I didn't need to add to the authors.json file at all.
In fact, I have now deleted that files as I just created a new collection:
eleventyConfig.addCollection("contributors", author => Object.values(author.items[0].data.contributors));
And now instead of calling my authors
global data, I simply call collections.contributors
in my Nunjucks templates. As always, there's probably a much cleaner way, but I have existing filters to show all guides by a chosen author and their bio on their posts etc.
It's working well, so for now it ships, maybe I'll try to replicate this without creating the extra collection at a later date, if I ever figure it out.