strapi

How to get Strapi relationship fields in lifecycle methods


In my Inventory model, I have two relationships, one for supplier and one for the product. They are both 1 to many with Inventory. My question is how can I get these relationships from the event object that strapi generates in afterCreate or afterUpdate method. For example, here's my code where I want to retrieve supplier and product info from the event object, unfortunately the event object doesn't seem to have relationship fields, I only get these values:

result: {
    id: 1,
    availableStockQuantity: 4,
    uom: 'Kg',
    createdAt: '2024-07-03T04:54:00.941Z',
    updatedAt: '2024-07-03T04:54:16.211Z',
    publishedAt: null,
    locale: 'en',
    stockAvailabilityDate: '2024-07-10T04:00:00.000Z',
    product: { count: 1 },
    supplier: { count: 1 },
   {...}

Code

import { errors } from '@strapi/utils';
import { MessageType, Topic, handleEvent } from '../../../../../config/topics';
const { ApplicationError } = errors;

const validateDate = (dateStrUTC: string): void => {
  const date = new Date(dateStrUTC);
  const isThursdayMidnight = 
    date.getUTCDay() === 4 && 
    date.getUTCHours() === 0 && 
    date.getUTCMinutes() === 0 && 
    date.getUTCSeconds() === 0 && 
    date.getUTCMilliseconds() === 0;
    
  if (!isThursdayMidnight) {
    throw new ApplicationError('Stock availability can only be set to Thursdays midnight');
  }
};

interface Inventory {
  product: string,
  stockAvailabilityDate: string,
  supplier: string,
  availableStockQuantity: number,
  uom: "Kg" | "Unit"
}

const cast = (result): Inventory => {
  return {
    product: result.name,
    stockAvailabilityDate: result.stockAvailabilityDate,
    supplier: "",
    availableStockQuantity: result.availableStockQuantity,
    uom: result.uom
  }
}

export default {
  beforeCreate(event) {
    const { data } = event.params;
    // validateDate(data.stockAvailabilityDate);
  },
  afterCreate(event) {
    handleEvent(event, MessageType.Create, cast, Topic.Inventory);
  },
  afterUpdate(event) {
    console.log("Got this as event", event);
    handleEvent(event, MessageType.Update, cast, Topic.Inventory);
  },
};

Here's my handleEvent method

export const handleEvent = <T>(event: any, messageType: MessageType, cast: Caster<T>, topic: Topic) => {
    const { result } = event;
    const data = cast(result);
    const message = buildMessage(data, messageType);
    sendMessageToQueue(topic, message);
};

Solution

  • Yes, I also have this issue, I solved it by fetching within the hook

    export default {
      afterUpdate: async (event) => {
        const result = await strapi.entityService.findMany(...
        handleEvent(event, result.relation);
      },
    };