Completed
Push — master ( 2ee302...fe5957 )
by Mathias
01:41 queued 38s
created

index.js ➔ ???   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 6
c 4
b 0
f 0
nc 2
dl 0
loc 34
rs 8.439
nop 2
1
'use strict';
2
3
import * as Buffer from 'buffer';
4
import * as fs from 'fs';
5
import * as http from 'http';
6
import * as url from 'url';
7
8
import Botlang from '../Botlang';
9
import Styles from './../Cli/Styles';
10
11
const options = new Map()
12
        .set('port', 8080)
13
        .set('quite', false),
14
      /**
15
       * @param  {Object} request - https://nodejs.org/api/http.html#http_class_http_incomingmessage
16
       * @param  {Object} response
17
       * @return {void}
18
       */
19
      requestHandler = (request, response) => {
20
        request.url = url.parse(request.url, true);
21
22
        const brain = request.headers.hasOwnProperty('x-brain')
23
                && fs.existsSync(`${__dirname}/../../example/${request.headers['x-brain']}.bot`)
24
                ? request.headers['x-brain']
25
                : 'eliza',
26
              isText = request.headers.hasOwnProperty('content-type')
27
                && 'text/plain' === request.headers['content-type'],
28
              say = request.url.query.say
29
                ? request.url.query.say
30
                : null,
31
              sourceCode = fs.readFileSync(`${__dirname}/../../example/${brain}.bot`, {
32
                encoding : 'utf8',
33
                flag     : 'r'
34
              }),
35
              bot = new Botlang(sourceCode),
36
              now = new Date().toISOString().substring(0, 19).replace(/(T|Z)/g, ' '),
37
              reply = bot.reply(say),
38
              body = isText ? reply : JSON.stringify({
39
                reply
40
              });
41
42
        write(`${Styles.yellow.open}${now} [SRV]:${Styles.yellow.close} Brain: "${brain}" loaded.`);
43
        write(`${Styles.green.open}${now} [USR]:${Styles.green.close} ${say}`);
44
        write(`${Styles.green.open}${now} [BOT]:${Styles.green.close} ${reply}`);
45
46
        response.writeHead(200, {
47
          'Content-Length' : Buffer.Buffer.byteLength(body, 'utf8'),
48
          'Content-Type'   : isText ? 'text/plain' : 'application/json'
49
        });
50
51
        response.end(body);
52
      },
53
      server = http.createServer(requestHandler),
54
      /**
55
       * @param  {*} args
56
       * @return {void}
57
       */
58
      write = (...args) => {
59
        if (0 !== args.length && !options.get('quite')) process.stdout.write(`${args}\n`);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
60
      };
61
62
// Set options
63
process.argv.forEach((arg) => {
64
  if ('--quite=' === arg.substr(0, 8)) {
65
    options.set('quite', 'true' === arg.substr(8));
66
  }
67
});
68
69
// Start listening
70
server.listen(options.get('port'), (err) => {
71
  if (err) throw new Error(err);
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
72
73
  write(`${Styles.red.open}`);
74
  write('# -----------------------------------------------------------------------------');
75
  write(`# Web server with botlang#${Botlang.version()} listening on "http://127.0.0.1:${options.get('port')}".`);
76
  write('# -----------------------------------------------------------------------------');
77
  write('# This web server was designed to aid application development. It may also be');
78
  write('# useful for testing purposes or for application demonstrations that are run in');
79
  write('# controlled environments. It is not intended to be a full-featured web server.');
80
  write('# It should not be used on a public network.');
81
  write('# -----------------------------------------------------------------------------');
82
  write(`${Styles.red.close}`);
83
});
84