DEV Community

Jesse Phillips
Jesse Phillips

Posted on

Hobby Project: Save Dev Articles

I was able to put together a basic save of dev articles. The main focus here is defining what the data storage will look like, and it still isn't final.

Since the intent is to allow article creation, the stored data should match what creation wants. However the data is pulled in with a different structure specification. This has resulted in me defining three structures and a need to transition between them.

Interestingly this has some relevance to an improvement proposal I'm working on.

auto structureArticles(Range)(Range articles) if (isInputRange!Range
                                            && is(ElementType!Range == ArticleMe)) {
    return!(x => Article(ArticleMeta(x), x.body_markdown));
Enter fullscreen mode Exit fullscreen mode

Since I want to keep meta data separate, I want to extract the markdown body but keep it with the meta data.

With this defined internal representation I can turn to using it to write out the data.

void saveArticles(Range)(Range articles, string folder) if(is(ElementType!Range == Article))
in(folder.exists, "Create direcorty before calling to save articles.")
    void saveArticle(Article article) {
        import std.file;
        import std.path;

        auto filename = article.meta.title;
        assert(isValidFilename(filename), "Article Name Conflicts with valid file name.");

        write(folder.buildPath(filename.setExtension("md")), article.content);
        write(folder.buildPath(filename.setExtension("json")), article.meta.serializeToPrettyJson);

Enter fullscreen mode Exit fullscreen mode

I broke this up into two methods, the outer method is just applying the inner method to each article. A lambda could have been used, I just felt this had a little more structure.

I decided for this first attempt I would just use the article title for the file name. This will be a big issue for Windows, so sanitizing will be needed.

in(folder.exists, "Create direcorty before calling to save articles.")
Enter fullscreen mode Exit fullscreen mode

This method is not going to manage folders, so I'm setting an expectation the directory will already exist.

I did build this out by first writing the method signature then a unittest. I removed the test for writing the files because it was not testing anything and I hate filesystem dependency.

Top comments (0)