sanity-io / sanity-algolia

Utilities for indexing Sanity documents in Algolia
MIT License
65 stars 16 forks source link

scond parameter on `webhookSync` is keep giving me error #17

Open shoaibsharif opened 2 years ago

shoaibsharif commented 2 years ago

I was trying to integrate Algolia in one of my Next.js project. I was trying to sync with sanity-algolia via Next API but I keep getting error

error - TypeError: Cannot read property 'created' of undefined
    at _callee$ (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:891:57)
    at tryCatch (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:129:40)
    at Generator.invoke [as _invoke] (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:359:22)
    at Generator.next (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:184:21)
    at asyncGeneratorStep (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:29:24)
    at _next (/Volumes/workspace/clients/radiology-associates/ra-frontend/node_modules/sanity-algolia/dist/sanity-algolia.cjs.development.js:51:9) {
  page: '/api/sanityAlgolia'
}

I tried exactly the same example shown in READMe.md, but I think Sanity webhook sends a different data then what .webhookSync expects.

I have noticed Sanity webhook doesn't send the way .webhookSync methods expects. on req.body, I get

{
 _rev: '...',
  _type: 'physician',
_id,
  _createdAt: '2021-11-02T02:51:34Z'
}

Where .webhookSync expects

 ids: {
        created: string[];
        updated: string[];
        deleted: string[];
    };

Is this issue related to Webhook Sync?

runeb commented 2 years ago

Hello @shoaibsharif, thanks for your submitted issue. This plugin has not yet been updated to support Webhooks 2.0, which is why you are seeing this. It is next on the todo list, however!

runeb commented 2 years ago

@shoaibsharif Can you try with this webhook meanwhile?

darwinshameran commented 2 years ago

Any ETA when this'll be done @runeb? Thank you for the effort going into this plugin, much appreciated. 🥇

afflexux commented 2 years ago

@shoaibsharif Can you try with this webhook meanwhile?

Hello, I get the same error, I tried using the web hook you referenced first but I see you have changed the link now, I can't work out how to adapt for GROQ powered web hooks.

Edit: Sorry, I see you are working on updating the plugin, look forward to using it. Thanks.

gianpaj commented 2 years ago

Same error here image

[
{
"id": "atm-23q27HxphpnV3woUo5kSawaHkuD",
"projectId": "xmjoyymz",
"inProgress": false,
"duration": 2875,
"createdAt": "2022-01-17T19:18:44.502Z",
"updatedAt": "2022-01-17T19:18:44.502Z",
"messageId": "msg-23q270RPywHA46Ke2j7qnP2OqKX",
"hookId": "rjh15uFzGU5IFTcO",
"isFailure": true,
"failureReason": "other",
"resultCode": 502,
"resultBody": "{\"errorType\":\"TypeError\",\"errorMessage\":\"Cannot read property 'created' of undefined\",\"trace\":[\"TypeError: Cannot read property 'created' of undefined\",\"    at _callee$ (/var/task/netlify/functions/algolia-index.js:12167:61)\",\"    at tryCatch (/var/task/netlify/functions/algolia-index.js:11682:46)\",\"    at Generator.invoke [as _invoke] (/var/task/netlify/functions/algolia-index.js:11818:28)\",\"    at Generator.next (/var/task/netlify/functions/algolia-index.js:11714:27)\",\"    at asyncGeneratorStep (/var/task/netlify/functions/algolia-index.js:11617:28)\",\"    at _next (/var/task/netlify/functions/algolia-index.js:11635:13)\"]}"
}
]

The error looks to be in this line https://github.com/sanity-io/sanity-algolia/blob/28e256f3bf01545d538da523b1eb5f0878710f21/src/index.ts#L68

I can reproduce this by running the function locally:

netlify functions:invoke algolia-index --payload '{"foo": 1}'
◈ "port" flag was not specified. Attempting to connect to localhost:8888 by default
TypeError: Cannot read property 'created' of undefined
  _callee$ (./node_modules/sanity-algolia/src/index.ts:68:13)

( in another terminal you need to run netlify dev)

gianpaj commented 2 years ago

@runeb I tried adding the projection as mentioned in the Changelog

image

but I'm getting the same error.

alexthekiwi commented 2 years ago

Getting the same error as @gianpaj, after copying that projection from the changelog.

If I log the request body in my serverless function, I can see that it still seems to be sending the same data as if it didn't have that projection? 🤔

My projection is exactly as per the above, but my POST request body is..

{
  body: {
    _type: 'product',
    slug: { _type: 'slug', current: 'gmk-vn' },
    _createdAt: '2021-12-01T00:10:53Z',
    _updatedAt: '2022-01-19T00:45:07Z',
    theme: 'light',
    _lang: 'vn',
    category: {
      _ref: '2be7cce6-e03a-46db-b641-e7c03413e382',
      _type: 'reference'
    },
    _rev: 'QD86YgF5XjNgItC7JXTFA1',
    title: 'Ground Mount Kiosk',
    image: { _type: 'figure', alt: 'GMK', asset: [Object] },
    _id: 'i18n.e97904d1-d7f6-4833-b1be-54f5a8fc5c0f.vn'
  }
}
razvanmitre commented 2 years ago

I also had some problems with the legacy projection mentioned in the changelog. Make sure you use the "Apply to project " button in the webhook template from Sanity.

Also, you have to filter out null values in the body. Here is my full handler:

const handler = (req, res) => {
  // Tip: Its good practice to include a shared secret in your webhook URLs and
  // validate it before proceeding with webhook handling. Omitted in this short
  // example.
  if (req.headers['content-type'] !== 'application/json') {
    res.status(400)
    res.json({ message: 'Bad request' })
    return
  }

  const ids = {
    created: req.body.ids.created.filter((id) => !!id),
    updated: req.body.ids.updated.filter((id) => !!id),
    deleted: req.body.ids.deleted.filter((id) => !!id),
  }

  // Finally connect the Sanity webhook payload to Algolia indices via the
  // configured serializers and optional visibility function. `webhookSync` will
  // inspect the webhook payload, make queries back to Sanity with the `sanity`
  // client and make sure the algolia indices are synced to match.
  return sanityAlgolia
    .webhookSync(sanityClient, { ids })
    .then(() => res.status(200).send('ok'))
}

export default handler
gianpaj commented 2 years ago

@razvanmitre where is the Apply to project button? and what do you mean by "webhook template"?

www sanity io_manage_personal_project_xmjoyymz_api_webhooks_rjh15uFzGU5IFTcO(iPad Pro)

razvanmitre commented 2 years ago

See here, it's from the docs