105 lines
3.1 KiB
JavaScript
105 lines
3.1 KiB
JavaScript
'use strict'
|
|
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 => {
|
|
// client.indices.delete({
|
|
// index: 'forms'
|
|
// })
|
|
if (!indices.forms) {
|
|
client.indices.create({
|
|
index: 'forms',
|
|
body: {
|
|
mappings: {
|
|
form: {
|
|
dynamic: true,
|
|
numeric_detection: true,
|
|
properties: {
|
|
schema: {
|
|
type: 'object'
|
|
},
|
|
options: {
|
|
type: 'object'
|
|
},
|
|
data: {
|
|
type: 'object'
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
})
|
|
}
|
|
})
|
|
console.log(`Serving on ${server.address().address}:${server.address().port}`)
|
|
})
|
|
|
|
|
|
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]._source)
|
|
} 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)
|
|
} else res.json([])
|
|
})
|
|
.catch(next)
|
|
}) |