-
Notifications
You must be signed in to change notification settings - Fork 13
/
app.js
95 lines (78 loc) · 2.27 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var koa = require('koa');
var animals = require('./lib/animals');
var bodyParser = require('koa-bodyparser');
var logger = require('koa-logger');
var Analytics = require('analytics-node');
var analytics = new Analytics('e2L9GzC8gZBUv3EMch6jDjvOMaLOv98o');
/**
* App.
*/
var app = koa();
app.proxy = true; // support x-forwarded-for as ctx.ip
/**
* Exports.
*/
module.exports = app;
/**
* Middleware.
*/
app.use(bodyParser());
app.use(logger());
/**
* Load an animal at /.
*/
app.use(function *(){
var index = integer(this.query.index, 0, animals.length);
var maxWidth = integer(this.query.maxwidth, 10, 1000);
var maxHeight = integer(this.query.maxHeight, 10, 1000);
var offset = integer(this.query.offset, 0, 1000);
var reverse = this.query.reverse === 'true';
var terminal = this.query.terminal === 'true';
// select the animal
var animal = select(index, maxWidth, maxHeight);
if (reverse) animal = animals.reverse(animal);
if (offset) animal = animals.offset(animal, offset);
// output as many deletion characters as the animal
if (terminal) {
var dims = animals.dimensions(animal);
for (var i = 0; i < dims.height-1; i += 1)
animal = '\x1b[2K\r' + '\x1b[1F' + animal;
}
analytics.track({
userId: this.ip,
event: 'Requested Animal',
properties: { terminal: terminal, index: index, reverse: reverse }
});
this.type = 'text/plain; charset=utf-8';
this.body = animal;
});
/**
* Parse an input into an integer.
*/
function integer(str, min, max) {
if (str && parseInt(str) >= min && parseInt(str) < max)
return parseInt(str);
else
return null;
}
/**
* Select an animal.
* @param {Number} index Animal index to select
* @param {Number} width Max width
* @param {Number} height max height
* @return {String} Selected animal
*/
function select(index, width, height) {
if (index) return animals[index];
// if we have width or height criteria, select it
if (width || height) {
for (var i = 0; i < animals.length; i += 1) {
var animal = animals[i];
var dims = animals.dimensions(animal);
if (width && dims.width > width) continue;
if (height && dims.height > height) continue;
return animal;
}
}
return animals[Math.floor(Math.random() * animals.length)];
}