- Building Enterprise JavaScript Applications
- Daniel Li
- 225字
- 2021-07-23 16:31:29
Indexing documents to Elasticsearch
In src/index.js, import the Elasticsearch library and initiate a client as we did before; then, in the request handler for POST /users, use the Elasticsearch JavaScript client's index method to add the payload object into the Elasticsearch index:
import elasticsearch from 'elasticsearch';
const client = new elasticsearch.Client({
host: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOSTNAME}:${process.env.ELASTICSEARCH_PORT}`,
});
...
app.post('/users', (req, res, next) => {
...
client.index({
index: 'hobnob',
type: 'user',
body: req.body
})
}
The index method returns a promise, which should resolve to something similar to this:
{ _index: 'hobnob',
_type: 'users',
_id: 'AV7HyAlRmIBlG9P7rgWY',
_version: 1,
result: 'created',
_shards: { total: 2, successful: 1, failed: 0 },
created: true }
The only useful and relevant piece of information we can return to the client is the newly auto-generated _id field. Therefore, we should extract that information and make the function return a promise, which resolves to only the _id field value. As a last resort, return a 500 Internal Server error to indicate to the client that their request is valid, but our server is experiencing some issues:
client.index({
index: 'hobnob',
type: 'user',
body: req.body,
}).then((result) => {
res.status(201);
res.set('Content-Type', 'text/plain');
res.send(result._id);
}).catch(() => {
res.status(500);
res.set('Content-Type', 'application/json');
res.json({ message: 'Internal Server Error' });
});
Now, our E2E tests should all pass again!