jqab/web/index.js

103 lines
2.9 KiB
JavaScript
Raw Normal View History

2019-04-05 20:48:34 +00:00
'use strict'
2019-04-07 17:38:07 +00:00
const http = require('http'),
es = require('elasticsearch'),
express = require('express'),
bodyParser = require('body-parser'),
client = new es.Client({ host: 'http://192.168.1.130:9200' }),
app = express(),
router = express.Router(),
server = http.createServer(app).listen(8080, () => {
client.indices.get({ index: '_all' }).then(indices => {
if (indices.forms) {
client.indices.delete({
index: 'forms'
})
}
client.indices.create({
index: 'forms',
body: {
mappings: {
form: {
properties: {
schema: {
type: 'object'
},
options: {
type: 'object'
},
data: {
type: 'object'
}
}
}
}
}
})
})
2019-04-05 20:48:34 +00:00
console.log(`Serving on ${server.address().address}:${server.address().port}`)
})
2019-04-07 17:38:07 +00:00
app.use(bodyParser.json())
.use('/api', router)
.use(express.static(__dirname + '/public'))
router.param('id', (req, res, next, id) => {
if (id && typeof id === 'string') {
next()
}
else {
res.sendStatus(403)
}
})
router.get('/load/:id', (req, res, next) => {
if (req.params.id) {
client.search({
index: 'forms',
type: 'form',
body: {
query: {
term: {
_id: req.params.id
}
}
}
}).then(form => {
if (form.hits.hits.length > 0) {
res.json(form.hits.hits[0])
} else res.sendStatus(404)
})
.catch(error => {
res.json(error)
})
} else next()
})
router.post('/save/:id', (req, res, next) => {
if (req.params.id && req.body.schema && req.body.options && req.body.data) {
client.create({
index: 'forms',
type: 'form',
id: req.params.id,
body: {
schema: req.body.schema,
options: req.body.options,
data: req.body.data
}
}).then(form => res.json({ result: form.result }))
.catch(next)
} else res.sendStatus(204)
})
router.get('/all', (req, res, next) => {
client.search({
index: 'forms',
type: 'form'
}).then(forms => {
if (forms.hits.hits.length > 0) {
res.json(forms.hits.hits[0])
} else res.sendStatus(404)
})
.catch(next)
})