Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/* eslint-disable no-console */
require('dotenv').config({ path: './.env.production' });
const express = require('express');
const bodyParser = require('body-parser');
const corser = require('corser');
const next = require('next');
const routes = require('./routes');
const algoliasearch = require('algoliasearch');
const convertDataToAlgoliaObject = require('./utils/convertDataToAlgoliaObject');
const fetch = require('isomorphic-fetch');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = routes.getRequestHandler(app);
const client = algoliasearch(
process.env.ALGOLIA_APPLICATION_ID,
process.env.ALGOLIA_ADMIN_API_KEY,
);
const itemsIndex = client.initIndex('items');
app.prepare()
.then(() => {
const server = express();
server.use(corser.create());
server.use(bodyParser.json());
// ---------- API endpoints for synchronizing Algolia -----------
server.post('/api/algolia/create', (req, res) => {
const { data } = req.body;
if (data.type_slug === 'items') {
const algoliaObject = convertDataToAlgoliaObject(data);
itemsIndex.addObject(algoliaObject)
.catch(err => console.error(err));
}
res.status(200).send();
});
server.post('/api/algolia/edit', (req, res) => {
const { data } = req.body;
if (data.type_slug === 'items') {
const algoliaObject = convertDataToAlgoliaObject(data);
itemsIndex.addObject(algoliaObject)
.catch(err => console.error(err));
}
res.status(200).send();
});
server.post('/api/algolia/delete', (req, res) => {
const { data } = req.body;
// data is an Array of one or more Object _ids
itemsIndex.deleteObjects(data)
.catch(err => console.error(err));
res.status(200).send();
});
server
.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.