-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
85 lines (72 loc) · 2.31 KB
/
api.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
require('dotenv').load();
const express = require('express');
const bodyParser = require('body-parser');
const algolia = require('algoliasearch');
const APP_ID = process.env.ALGOLIA_APP_ID;
const API_KEY = process.env.ALGOLIA_API_KEY;
const SEARCH_API_KEY = process.env.ALGOLIA_SEARCH_API_KEY;
const INDEX_NAME = process.env.ALGOLIA_INDEX_NAME;
if (!API_KEY || !API_KEY || !INDEX_NAME || !SEARCH_API_KEY) {
throw new Error("Environment variables missing, see README.md");
}
const algoliaClient = algolia(APP_ID, API_KEY);
const moviesIndex = algoliaClient.initIndex(INDEX_NAME);
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json({strict: true}));
/**
* Get react webapp
*/
app.use('/', express.static('./client/build'));
/**
* Get algolia config for clients
*/
app.get('/api/1/credentials', (req, res) => {
console.log(`Getting credentials`);
res.status(200).send({
'app_id': APP_ID,
'search_api_key': SEARCH_API_KEY,
'index_name': INDEX_NAME,
});
});
/*
* Add a new movie to the index
*/
app.post('/api/1/movies', (req, res) => {
console.log(`Adding movie ${req.body.title}`);
moviesIndex.addObjects([req.body], (err, content) => {
if (err) throw err;
let taskId = content.taskID;
let objId = content.objectIDs[0];
console.log(`Created with obj id: ${objId}`);
console.log(`Waiting for task ${taskId}`);
moviesIndex.waitTask(taskId, (err, content) => {
if (err) throw err;
console.log(content);
console.log(`Successfully added movie ${req.body.title}`);
let movieData = Object.assign({objectID: objId}, req.body);
res.status(201).send(req.body);
});
});
});
/*
* Remove a movie from the index
*/
app.delete('/api/1/movies/:id', (req, res) => {
console.log(`Removing movie ${req.params.id}`);
moviesIndex.deleteObjects([req.params.id], (err, content) => {
if (err) throw err;
let taskId = content.taskID;
console.log(`Waiting for task ${taskId}`);
moviesIndex.waitTask(taskId, (err, content) => {
if (err) throw err;
console.log(content);
console.log(`Successfully removed movie ${req.params.id}`);
res.status(204).send();
});
});
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
console.log(`Algolia app id: ${APP_ID} index: ${INDEX_NAME}`);
});