-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquote.js
76 lines (63 loc) · 2.4 KB
/
quote.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
import fetch from 'node-fetch';
import express from 'express';
//const express = require('express');
const app = express();
// const path = require('path');
app.get('/api/quote', async (req, res) => {
console.log('GET /api/quote');
var quote1;
await getQuoteAsync().then((data) => quote1 = data);
console.log(quote1.content, true + " - " + quote1.author);
var quote2;
await getQuoteAsync().then((data) => quote2 = data);
console.log(quote2.content, false + " - " + quote2.author);
var outquote = splitAtRandom(quote1.content, true) + " " + splitAtRandom(quote2.content, false) + "\n - " + quote1.author + " & " + quote2.author;
console.log(outquote);
res.header("Access-Control-Allow-Origin", '*');
res.send(outquote);
});
app.get('/api/quote/json', async (req, res) => {
console.log('GET /api/quote');
var quote1;
await getQuoteAsync().then((data) => quote1 = data);
console.log(quote1.content, true + " - " + quote1.author);
var quote2;
await getQuoteAsync().then((data) => quote2 = data);
console.log(quote2.content, false + " - " + quote2.author);
var jsonOut = {
"quote": splitAtRandom(quote1.content, true) + " " + splitAtRandom(quote2.content, false),
"author1": quote1.author,
"author2": quote2.author
}
console.log(jsonOut);
res.header("Access-Control-Allow-Origin", '*');
res.json(JSON.stringify(jsonOut));
});
function getQuoteAsync() {
return fetch("https://api.quotable.io/random")
.then((response) => response.json())
.then((responseJson) => { return responseJson });
}
function splitAtRandom(quote, first) {
// Split into array of words
var words = quote.split(" ");
if(first) {
// Split somwehere between word 0 and half way through
var max = words.length / 2;
var min = 1;
var index = Math.random() * (max - min) + min;
// Join back together and return
return words.slice(0, index).join(" ");
} else {
// Split somewhere between half way through and the end
var max = words.length-1;
var min = words.length / 2;
var index = Math.random() * (max - min) + min;
// Join back together and return
return words.slice(index, words.length).join(" ");
}
}
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})