Created
March 21, 2023 13:30
-
-
Save felipeorlando/17381f55a2e3b0e65ab64018caed4159 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { SanityDocumentStub } from '@sanity/client' | |
import { algolia, sanity } from '~/libs' | |
import { NextApiRequest, NextApiResponse } from 'next' | |
import indexer from 'sanity-algolia' | |
const handler = (req: NextApiRequest, res: NextApiResponse) => { | |
if (req.headers['content-type'] !== 'application/json') { | |
res.status(400) | |
res.json({ message: 'Bad request' }) | |
return | |
} | |
if (req.headers['token'] !== process.env.SANITY_INDEXER_TOKEN) { | |
res.status(401) | |
res.json({ message: 'Unauthorized' }) | |
return | |
} | |
const algoliaIndex = algolia.initIndex('places') | |
const typeIndexMap = { | |
city: { | |
index: algoliaIndex, | |
projection: `{ | |
name, | |
"path": slug.current, | |
}`, | |
}, | |
neighborhood: { | |
index: algoliaIndex, | |
projection: `{ | |
name, | |
"path": slug.current, | |
city->{ | |
_id, | |
name, | |
"path": slug.current, | |
} | |
}`, | |
}, | |
} | |
const serializer = (document: SanityDocumentStub) => { | |
const { _id, _rev, _type, ...rest } = document | |
switch (document._type) { | |
case 'city': | |
return { | |
...rest, | |
objectID: document._id, | |
type: 'city', | |
} | |
case 'neighborhood': | |
return { | |
...rest, | |
objectID: document._id, | |
type: 'neighborhood', | |
cityID: document.city?._id, | |
cityName: document.city?.name, | |
cityPath: document.city?.path, | |
humanizedName: `${document.name}, ${document.city?.name}`, | |
} | |
default: | |
return document | |
} | |
} | |
const sanityAlgolia = indexer(typeIndexMap, serializer) | |
return sanityAlgolia | |
.webhookSync(sanity, req.body) | |
.then(() => res.status(200).send('ok!')) | |
} | |
export default handler |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment