]> git.r.bdr.sh - rbdr/blog/blob - bin/blog.js
18443aa9b84f3dc363a4f5a3b1956fcd713fdd45
[rbdr/blog] / bin / blog.js
1 #!/usr/bin/env node
2 'use strict';
3
4 const Config = require('../config/config');
5 const Blog = require('..');
6 const Minimist = require('minimist');
7
8 const internals = {
9 blog: new Blog(Config),
10 expectedKeys: ['add', 'update', 'publish'],
11
12 // Application entry point. Reads arguments and calls the
13 // corresponding method from the blog lib
14
15 async main() {
16
17 try {
18 const parsedArguments = this._parseArguments();
19
20 for (const argument in parsedArguments) {
21 if (parsedArguments.hasOwnProperty(argument)) {
22
23 const value = parsedArguments[argument];
24
25 if (argument === 'add') {
26 await internals.blog.add(value);
27 return;
28 }
29
30 if (argument === 'update') {
31 await internals.blog.update(value);
32 return;
33 }
34
35 if (argument === 'publish') {
36 await internals.blog.publish(value);
37 return;
38 }
39 }
40 }
41
42 console.log('Not yet implemented');
43 }
44 catch (err) {
45 console.error(err.message || err);
46 this._printUsage();
47 process.exit(1);
48 }
49 },
50
51 // Parses arguments and returns them if valid. otherwise Throws
52
53 _parseArguments() {
54
55 const parsedArguments = Minimist(process.argv.slice(2));
56
57 if (!this._areArgumentsValid(parsedArguments)) {
58 throw new Error(internals.strings.invalidArguments);
59 }
60
61 return parsedArguments;
62 },
63
64 // Checks if the arguments are valid, returns a boolean value.
65
66 _areArgumentsValid(parsedArguments) {
67
68 const argumentKeys = Object.keys(parsedArguments);
69
70 return argumentKeys.some((key) => internals.expectedKeys.indexOf(key) >= 0);
71 },
72
73 // Prints the usage to stderr
74
75 _printUsage() {
76
77 console.error('\nUsage:\n');
78 console.error('blog --add path/to/blog_post\t\t(creates new blog post)');
79 console.error('blog --update path/to/blog_post\t(updates latest blog post)');
80 console.error('blog --publish \t\t\t(publishes the blog)');
81 }
82 };
83
84 // Add the strings, added after declaration so they can consume the
85 // internals object.
86
87 internals.strings = {
88 invalidArguments: `Invalid Arguments, expecting one of: ${internals.expectedKeys.join(', ')}`
89 };
90
91
92
93 internals.main();