changelog-server/index.js

136 lines
3.0 KiB
JavaScript

/*
*
*
2020-05-15T20:28:14.357Z
curl -X PUT 'http://localhost:9200/changelog' -d '
{
"mappings": {
"properties": {
"author": { "type": "keyword" },
"content": { "type": "text" },
"created_at": { "type": "date","format": "date_optional_time" }
}
}
}' -H "Content-Type: application/json"
*
*/
/* global process */
"use strict"
const authorizationToken = process.env.AUTH_TOKEN || "hello";
const port = process.env.APP_PORT || 3000;
function requireAuthentication( req, res, next ){
const userAuth = req.get("AuthorizationToken") || req.query.authorizationToken;
console.log( "userAuth : "+userAuth)
if( userAuth && userAuth === authorizationToken ) next();
else res.end("Auth required");
}
const elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: process.env.ES_CONNECT,
// log: 'trace',
apiVersion: '7.7'
});
const express = require('express');
const app = express();
app.set('view engine', 'pug');
app.use(express.static('public'));
app.all('*', requireAuthentication)
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.use(bodyParser.text({ type : "text/*" }));
app.disable('x-powered-by');
const routes = {
main: (req, res) => {
client.search({index:"changelog", "size":100,"sort":"created_at:desc"}).then( (results,err) => {
res.render('index', {
title: 'changelog',
error: err,
data: JSON.stringify( results),
authorizationToken: authorizationToken
});
});
},
search: (req, res) => {
const query = req.query.q;
const search = {
index:"changelog",
size:100,
body:{
query:{
multi_match:{
query: query
}
}
},
sort:"_score,created_at:desc"
};
client.search(search).then( (results,err) => {
res.json(results );
}, (err) => {
res.status(404);
res.json({data: {} });
});
},
health: (req, res) => {
// Do an ES request
client.ping({ requestTimeout: 100}).then(
() => {
res.json({"health":100,"msg":"OK"});
}, () => {
res.json({"health":0,"msg":"Lost connection to ES"});
});
},
add: (req, res) => {
const body = req.body;
body.created_at = new Date().toISOString();
client.index({
index: 'changelog',
body: body
}).then( (e) => {
res.end("ok");
}, (e) => {
res.status(400);
res.end("error");
});
}
};
app.get('/health', routes.health);
app.get('/search', routes.search);
app.post('/*', routes.add);
app.get('/*', routes.main);
app.patch('/*', routes.main);
app.put('/*', routes.main);
app.delete('/*', routes.main);
app.listen(port, () => {
console.log(`Express.js listening on port: ${port}`);
});