Like what we’re doing? Star us on GitHub!

afterDelete hook error

jakehopking
4 weeks ago
11

Hi - I'm having a problem running this hook.




Here's the complete hook:



export const orderAfterDelete: AfterDeleteHook = async ({
  req,
  id,
  doc,
}: {
  req: PayloadRequest;
  id: string;
  doc: Omit<OrderType, 'customerRelationship'> & {
    customerRelationship: string;
  };
}) => {
  const { payload } = req;
  const customerOrders: CustomerType['orders'] = await payload
    .findByID({
      collection: 'customers',
      id: doc.customerRelationship,
    })
    .then((customer) => customer.orders)
    .catch((error) => {
      payload.logger.error(`orderAfterDelete: ${error.message}`);
      return null;
    })

  if (customerOrders.length === 0) {
    payload.logger.info(`orderAfterDelete: Customer has no orders`);
  } else {
    // Remove order from customer
    await payload.update({
      collection: 'customers',
      id: doc?.customerRelationship,
      data: {
        orders: customerOrders
          .filter((order) => order?.id !== id)
          .map((order) => order?.id),
      },
    });
    payload.logger.info(`orderAfterDelete: Removed order from customer`);
  }

  console.log({ id, doc, customerOrders });
  payload.logger.info(`orderAfterDelete: finished`);
};


I get this error in my console when trying to delete the record from the admin ui:



[10:50:03] ERROR (payload): NotFound: The requested resource was not found.
    at new ExtendableError (/Users/jake/Development/personal/elkli-and-hart/node_modules/payload/src/errors/APIError.ts:26:11)
    at new APIError (/Users/jake/Development/personal/elkli-and-hart/node_modules/payload/src/errors/APIError.ts:43:5)
    at new NotFound (/Users/jake/Development/personal/elkli-and-hart/node_modules/payload/src/errors/NotFound.ts:7:5)
    at findByID (/Users/jake/Development/personal/elkli-and-hart/node_modules/payload/src/collections/operations/findByID.ts:113:13)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runNextTicks (node:internal/process/task_queues:64:3)
    at processImmediate (node:internal/timers:442:9)
    at async findByIDHandler (/Users/jake/Development/personal/elkli-and-hart/node_modules/payload/src/collections/requestHandlers/findByID.ts:13:17)


When I run this logic inside my test env (the

getServerSideProps

which I use as a playground for sanity checking) it successfully run and removes the order from the customer.



Please can you help shine a light on what I'm doing wrong?



Logging the

id

and

doc

inside the afterDelete hook I get this... so all the data I need is there:



{
  id: '63f4a1e2c0a1587558cb5afc',
  doc: {
    id: '63f4a1e2c0a1587558cb5afc',
    customer: {
      email: 'jake@hopking.io',
      name: 'Jake Hopking',
      address: [Object]
    },
    customerRelationship: '63ed08df3b7466e4b53c3676',
    dates: {
      created: '2023-02-21T00:47:13.007Z',
      paid: '2023-02-21T00:47:16.896Z'
    },
    payment: {
      currency: 'gbp',
      paymentMethod: 'card',
      priceTotal: 12000,
      priceVat: 2000,
      status: 'payment_success',
      vatRate: 20
    },
    products: [ [Object] ],
    status: 'order_paid',
    stripe: { payment_intent: [Object] },
    statusValidation: {
      hasOrderReadyToDispatchCompleted: false,
      hasOrderShippedCompleted: false
    },
    createdAt: '2023-02-21T10:50:10.332Z',
    updatedAt: '2023-02-21T10:50:10.332Z'
  }
}


Also, logging the

customerOrders

- I can see that the customer has been found from the

doc.customerRelationship

customerOrders: [
    {
      id: '63eaaeba288a86128622d103',
      customer: [Object],
      dates: [Object],
      payment: [Object],
      products: [Array],
      status: 'order_paid',
      stripe: [Object],
      createdAt: '2023-02-13T21:42:18.727Z',
      updatedAt: '2023-02-19T16:58:23.603Z',
      tracking: [Object],
      customerRelationship: [Object],
      statusValidation: {}
    },
    {
      id: '63f41257628f2726b98d35e3',
      customer: [Object],
      customerRelationship: [Object],
      dates: [Object],
      payment: [Object],
      products: [Array],
      status: 'order_paid',
      stripe: [Object],
      statusValidation: [Object],
      createdAt: '2023-02-21T00:37:43.269Z',
      updatedAt: '2023-02-21T00:47:16.900Z',
      tracking: {}
    },
    '63f4a7d151729824a8a93b3e'
  ]


actually - now i see that the order id is all that remains... (two full objects, and a string.... which makes sense because this runs

after

delete). So maybe I need to filter based on type before mapping the ids back in?



-



Tried this and it works....



await payload.update({
  collection: 'customers',
  id: doc?.customerRelationship,
  data: {
    orders: customerOrders
      .filter((order) => typeof order !== 'string' && order?.id !== id)
      .map((order) => order?.id),
  },
});


-



Is there a better way of doing this?



Could be a nice feature to add to collections.... option of automatically removing the stale id from an array of defined collections (which share this relationship) upon record deletion

  • jesschow
    Payload Team
    2 weeks ago

    Hi @jakehopking - that would definitely be a great feature. A similar discussion about checking relationships to a doc before deleting was had here:

    https://github.com/payloadcms/payload/discussions/558

    The way you have filtered the orders looks good to me 👍

  • jakehopking
    2 weeks ago

    Thanks for replying and for the link @jesschow 👍

Open the post
Continue the discussion in Discord
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More