api rest with ES

This commit is contained in:
ale 2019-04-07 19:38:07 +02:00
parent 5d36432ba4
commit bc4cb79f11
3 changed files with 102 additions and 8 deletions

View File

@ -1,10 +1,103 @@
'use strict'
const finalhandler = require('finalhandler'),
http = require('http'),
serveStatic = require('serve-static'),
serve = serveStatic(__dirname + '/public', { 'index': ['index.html'] }),
server = http.createServer(function onRequest(req, res) {
serve(req, res, finalhandler(req, res))
}).listen(8080, () => {
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'
}
}
}
}
}
})
})
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])
} 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)
})

View File

@ -11,6 +11,7 @@
"ace-builds": "^1.4.3",
"alpaca": "^1.5.24",
"blueimp-file-upload": "^9.28.0",
"body-parser": "^1.18.3",
"bootstrap": "^3.4.1",
"bootstrap-multiselect": "^0.9.13-1",
"ckeditor": "^4.11.3",

View File

@ -103,7 +103,7 @@ blueimp-tmpl@3.6.0:
resolved "https://registry.yarnpkg.com/blueimp-tmpl/-/blueimp-tmpl-3.6.0.tgz#a4910975d042e2bc03ba77f0e62d04f1548a524c"
integrity sha1-pJEJddBC4rwDunfw5i0E8VSKUkw=
body-parser@1.18.3:
body-parser@1.18.3, body-parser@^1.18.3:
version "1.18.3"
resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.18.3.tgz#5b292198ffdd553b3a0f20ded0592b956955c8b4"
integrity sha1-WykhmP/dVTs6DyDe0FkrlWlVyLQ=