How to create a new entry on creation of a separate content type

System Information
  • Strapi Version: 4
  • Operating System: Windows11
  • Database: SQLite
  • Node Version: 14
  • NPM Version:
  • Yarn Version:

I have two content types: Products and Inventory Items.
If created a file:
app\src\api\hotel-product\lifecycles.js

with content:

module.exports = {
    async beforeCreate(event) {
        const { data, where, select, populate } = event.params;

        console.log("creating product", data);

        if (!data.inventory_item.data) {
            try {
                const new_inventory_item = await strapi.services.query("inventory_item").create({quantity: data.quantity});
                event.params.data.inventory_item = new_inventory_item;
            } catch (err) {
                strapi.log("Error assigning new inventory item to newly created product", err);
            }
        }
    },
  
    afterCreate(event) {
      const { result, params } = event;
  
      // do something to the result;
    },
  };

The point is to create a new inventory item any time a product is created and not assigned an existing inventory item.

I can’t even debug this because no console shows me the error messages and the strapi.log function isn’t logging anywhere that I can see. Documentation is severly lacking. I have so many questions…

Please correct me if you see something wrong and let me know where I can start looking for logs

Ok the main problem was that the file needed to be in app\src\api\hotel-product\content-types\hotel-product\lifecycles.js instead, then I could see the logs.

Then the correct way to use services to access another content type is different and the object to create the entry needs to be different

See code below (it’s working now)

module.exports = {
    async beforeCreate(event) {
        const { data, where, select, populate } = event.params;

        console.log("creating product", data);
        
        if (!data.inventory_item) {
            try {
                // console.log(Object.keys(strapi.services['api::inventory-item.inventory-item'].create));
                const new_inventory_item = await strapi.services['api::inventory-item.inventory-item'].create({data: {quantity: data.quantity_in_stock, title: data.slug}});
                // console.log("new inventory item", new_inventory_item);
                event.params.data.inventory_item = new_inventory_item;
                
            } catch (err) {
                strapi.log.debug("Error assigning new inventory item to newly created product\n", err);    
            }
        }
    },
  
    afterCreate(event) {
      const { result, params } = event;
  
      // do something to the result;
    },
  };