forked from cubesky/SoulPosion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
97 lines (86 loc) · 2.83 KB
/
index.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
95
96
97
const Hapi = require('hapi');
const Boom = require('boom');
const config = require('config');
const launchServer = async function() {
const dbOpts = {
url: config.get('dbUrl'),
settings: {
poolSize: 10
},
decorate: true
};
const server = Hapi.server({ host: config.get('listenHost'), port: config.get('listenPort'), routes: { cors: true, jsonp: 'callback' } });
await server.register({
plugin: require('hapi-mongodb'),
options: dbOpts
});
server.ext('onPreResponse', function(request, reply) {
if (request.url.pathname === '/write') {
request.response.header('Content-Type', 'application/javascript');
} else if (request.url.pathname === '/json') {
request.response.header('Allow-Control-Allow-Origin', '*');
} else if (request.url.pathname === '/text') {
request.response.header('Allow-Control-Allow-Origin', '*');
}
return reply.continue
});
server.route( {
method: 'GET',
path: '/',
handler: async function(request,reply) {
return 'Welcome to Soul Posion'
}
});
server.route( {
method: 'GET',
path: '/text',
config: {
cors: true
},
handler: async function(request,reply) {
const db = request.mongo.db;
try {
const result = await db.collection('soulposion').aggregate([{ $sample: { size: 1 } }]).toArray()
return result[0].content;
} catch (err) {
throw Boom.internal('Internal MongoDB error', err);
}
}
});
server.route( {
method: 'GET',
path: '/write',
handler: async function(request,reply) {
const db = request.mongo.db;
try {
const result = await db.collection('soulposion').aggregate([{ $sample: { size: 1 } }]).toArray()
return 'document.write(\'' + result[0].content + '\')';
} catch (err) {
throw Boom.internal('Internal MongoDB error', err);
}
}
});
server.route( {
method: 'GET',
path: '/json',
config: {
cors: true
},
handler: async function(request,reply) {
const db = request.mongo.db;
try {
var result = (await db.collection('soulposion').aggregate([{ $sample: { size: 1 } }]).toArray())[0]
delete result._id
return result;
} catch (err) {
throw Boom.internal('Internal MongoDB error', err);
}
}
});
await server.start();
console.log(`Server started at ${server.info.uri}`);
};
launchServer().catch((err) => {
console.error(err);
process.exit(1);
});