From: Ben Beltran Date: Mon, 1 Jun 2020 20:44:39 +0000 (+0200) Subject: Add metadata writing functionality X-Git-Tag: 5.0.0~28^2~6 X-Git-Url: https://git.r.bdr.sh/rbdr/blog/commitdiff_plain/6f72ad0f8b1d147a3d2e27db539a0e17ca2ac917 Add metadata writing functionality --- diff --git a/lib/blog.js b/lib/blog.js index 9024a00..6b3397f 100644 --- a/lib/blog.js +++ b/lib/blog.js @@ -22,7 +22,7 @@ const internals = { kIndexName: 'index.html', kFileNotFoundError: 'ENOENT', kMarkdownRe: /\.md$/i, - kRemoveCommand: 'rm -rf', + kMetadataFilename: 'metadata.json', // Strings @@ -59,6 +59,7 @@ module.exports = class Blog { */ async add(postLocation) { + await this._ensurePostsDirectoryExists(); await this._shift(); await this.update(postLocation); } @@ -75,7 +76,11 @@ module.exports = class Blog { */ async update(postLocation) { + const metadata = await this._getMetadata(); + await this._ensurePostsDirectoryExists(); await this._copyPost(postLocation); + await this._writeMetadata(metadata); + await this._generate(); } @@ -148,18 +153,17 @@ module.exports = class Blog { async _shift() { - await this._ensurePostsDirectoryExists(); - for (let i = this.maxPosts - 1; i > 0; --i) { + for (let i = this.maxPosts - 1; i >= 0; --i) { const targetPath = join(this.postsDirectory, `${i}`); const sourcePath = join(this.postsDirectory, `${i - 1}`); try { - await access(sourcePath); - internals.debuglog(`Removing ${targetPath}`); await rmdir(targetPath, { recursive: true }); + await access(sourcePath); // check the source path + internals.debuglog(`Shifting blog post ${sourcePath} to ${targetPath}`); await internals.ncp(sourcePath, targetPath); } @@ -174,12 +178,42 @@ module.exports = class Blog { } } + // Attempts to read existing metadata. Otherwise generates new set. + + async _getMetadata() { + + const metadataTarget = join(this.postsDirectory, '0', internals.kMetadataFilename); + + try { + internals.debuglog(`Looking for metadata at ${metadataTarget}`); + return await readFile(metadataTarget); + } + catch (e) { + internals.debuglog(`Metadata not found or unreadable. Generating new set.`); + const createdOn = Date.now(); + const metadata = { + id: String(createdOn), + createdOn + }; + + return JSON.stringify(metadata, null, 2); + } + } + + // Writes metadata. Assumes post 0 since it only gets written + // on create + + async _writeMetadata(metadata) { + + const metadataTarget = join(this.postsDirectory, '0', internals.kMetadataFilename); + internals.debuglog(`Writing ${metadataTarget}`); + await writeFile(metadataTarget, metadata); + } + // Copies a post directory to the latest slot. async _copyPost(postLocation) { - await this._ensurePostsDirectoryExists(); - const targetPath = join(this.postsDirectory, '0'); internals.debuglog(`Removing ${targetPath}`);