changelog-server/index.js

108 lines
2.2 KiB
JavaScript

/*
*
*
2020-05-15T20:28:14.357Z
PUT /changelog
{
"mappings": {
"properties": {
"author": { "type": "keyword" },
"content": { "type": "text" },
"created_at": { "type": "date","format": "basic_date_time" }
}
}
}
*
*/
/* global process */
"use strict"
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'));
const port = process.env.APP_PORT || 3000;
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", "sort":"created_at:desc"}).then( (results,err) => {
res.render('index', { title: 'changelog', error: err, data: JSON.stringify( results) });
});
},
search: (req, res) => {
const query = req.query.q;
client.search({index:"changelog",body:{query:{multi_match:{query:query}}}}).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}`);
});