Added Elasticsearch proxy example (#1398)
Co-authored-by: István Zoltán Szabó <istvan.szabo@elastic.co>
This commit is contained in:
committed by
delvedor
parent
7448cd3d24
commit
176d823593
76
docs/examples/proxy/api/index.js
Normal file
76
docs/examples/proxy/api/index.js
Normal file
@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Licensed to Elasticsearch B.V. under one or more contributor
|
||||
* license agreements. See the NOTICE file distributed with
|
||||
* this work for additional information regarding copyright
|
||||
* ownership. Elasticsearch B.V. licenses this file to you under
|
||||
* the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
// IMPORTANT: this is not a production ready code & purely for demonstration purposes,
|
||||
// we make no guarantees on it's security and stability
|
||||
|
||||
// NOTE: to make this endpoint work, you should create an ApiKey with 'write' permissions
|
||||
|
||||
'use strict'
|
||||
|
||||
const { Client } = require('@elastic/elasticsearch')
|
||||
const authorize = require('../utils/authorize')
|
||||
|
||||
const INDEX = '<index-name>'
|
||||
const client = new Client({
|
||||
cloud: {
|
||||
id: process.env.ELASTIC_CLOUD_ID
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = async (req, res) => {
|
||||
const [err, token] = authorize(req)
|
||||
if (err) {
|
||||
res.status(401)
|
||||
res.json(err)
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof req.body !== 'object') {
|
||||
res.status(400)
|
||||
res.json({
|
||||
error: 'Bad Request',
|
||||
message: 'The document should be an object',
|
||||
statusCode: 400
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await client.index({
|
||||
index: INDEX,
|
||||
id: req.query.id,
|
||||
body: req.body
|
||||
}, {
|
||||
headers: {
|
||||
Authorization: `ApiKey ${token}`
|
||||
}
|
||||
})
|
||||
|
||||
res.status(response.statusCode)
|
||||
res.json(response.body)
|
||||
} catch (err) {
|
||||
res.status(err.statusCode || 500)
|
||||
res.json({
|
||||
error: err.name,
|
||||
message: err.message,
|
||||
statusCode: err.statusCode || 500
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user