-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.js
102 lines (83 loc) · 3.03 KB
/
api.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
98
99
100
101
102
var pg = require('pg');
var fs = require('fs');
var Mark = require("markup-js");
var React = require("react");
var ReactDOMServer = require('react-dom/server');
var SqlDoc = require("sqldoc");
var api = {};
var InternalError = function (err, response){
console.log(err);
response.status(500).send({
status: 'error',
message: 'Internal Error',
});
}
var RunQuery = function(response, query, params, callback){
pg.connect(process.env.SQLSHARE_DB, function(err, client, done) {
if (err) {
return InternalError(err, response);
}
client.query(query, params, function(err, result){
done();
if (err){
return InternalError(err, response);
}
callback(result);
});
});
}
/**
/* Input: Expects a POST request with a JSON body to be saved as a document
* Output: JSON with OK status and a document id
* Error: JSON with error status and message
*/
api.share = function(req, response){
pg.connect(process.env.SQLSHARE_DB, function(err, client, done) {
if (err) {
return InternalError(err, response);
}
RunQuery(response, 'SELECT o_guid FROM sqlshare.create_doc($1)', [req.body], function(result){
return response.status(200).send({
status: 'OK',
result: result.rows[0].o_guid,
});
});
});
}
var _doc_template = fs.readFileSync(__dirname+'/html/document.html', {encoding: 'utf8'});
var _404_template = fs.readFileSync(__dirname+'/html/document-404.html', {encoding: 'utf8'});
api.render = function(req, response){
RunQuery(response, 'SELECT o_guid docid, o_doc doc, o_created created FROM sqlshare.get_doc($1)', [req.params.docid], function(result){
if (result.rows[0].docid == null){
var doc_html = _404_template;
} else {
if (req.query.hasOwnProperty('echo') && req.query.echo == 'true'){
var echo = true;
} else {
var echo = false;
}
var doc_data = result.rows[0].doc;
var created = result.rows[0].created;
var sqldoc = React.createElement(SqlDoc, {data: doc_data, buttonBar: false, showQuery: echo, eventKey: 0});
var sqldoc_html = ReactDOMServer.renderToString(sqldoc);
doc = {
doc: sqldoc_html,
created: created,
}
var doc_html = Mark.up(_doc_template, doc);
}
return response.send(doc_html);
});
}
api.jsonDoc = function(req, response){
RunQuery(response, 'SELECT o_guid docid, o_doc doc, o_created created FROM sqlshare.get_doc($1)', [req.params.docid], function(result){
response.json(result.rows[0].doc);
});
}
api.list = function(req, response){
response.send('OK');
//RunQuery(response, 'SELECT o_guid docid, o_doc doc FROM sqlshare.get_doc($1)', [req.params.docid], function(result){
//
//});
}
module.exports = api;