-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
52 lines (44 loc) · 1.42 KB
/
server.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
const http = require('http');
// Load the Cloudant library.
const Cloudant = require('@cloudant/cloudant');
// Test variables
console.log(process.env);
// Get account details from environment variables
const catsdb = process.env.CLOUDANTNOSQLDB_URL || "";
const apikey = process.env.CLOUDANTNOSQLDB_APIKEY || "";
http.createServer((request, response) => {
const { method, url, headers } = request
if (method === "GET" && url === "/") {
// Initialize the library with url and credentials.
const cloudant = Cloudant({ url: catsdb, plugins: { iamauth: { iamApiKey: apikey } } });
async function asyncCall() {
return cloudant.use('cats').get('12345');
}
asyncCall().then((data) => {
console.log(data);
response.statusCode = 200
response.setHeader('Content-Type', 'application/json')
const responseBody = {
headers,
method,
url,
body: data
}
response.write(JSON.stringify(responseBody.body))
response.end()
}).catch((err) => {
console.log(err);
response.statusCode = 500
response.setHeader('Content-Type', 'application/json')
const responseBody = {
headers,
method,
url,
body: { 'error': 'Couldn\'t find cat in database' }
}
response.write(JSON.stringify(responseBody.body))
response.end()
});
}
}).listen(8080);
console.log('Server running at http://0.0.0.0:8080/');