datocms / js-rest-api-clients

REST API clients to interact with DatoCMS
MIT License
11 stars 7 forks source link

Return conflicting/existing record ID on VALIDATION_UNIQUE error #11

Closed Siilwyn closed 1 year ago

Siilwyn commented 1 year ago

Trying to upsert new data so on conflict I want to update the existing record, however I don't see the existing record ID which I need to be able to update (afaik).

stefanoverna commented 1 year ago

Sorry, but I didn't understand the problem well. Could you give a concrete example with some code? Thanks!

Siilwyn commented 1 year ago

@stefanoverna so I'm looping over data and then do something like:

client.items.create({ ...newData });
  .catch(({ errors }) => {
    if (errors.find((error) =>
      error.attributes.details.field === 'space_id'
      && error.attributes.details.code === 'VALIDATION_UNIQUE'
    )) {
      return;
      // (client.items.update) somehow update the existing item?
    }
  })
stefanoverna commented 1 year ago

I see. You can find the record with that specific value for the field:

const allMatchingItems = await client.items.list({ filter: { type: '<ID OF MODEL>', fields: { space_id: { eq: '<FAILING VALUE>' }}}})