Created
June 8, 2018 14:27
-
-
Save chrisoverstreet/b3c9bbdf6c57293beacddfc0154e3c3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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