Search code examples
strapi

Cannot find Strapi entityService?


Any idea why this isn’t working? Strapi v4.

I’m trying to update contentVersion field inside a single-type "version" whenever any other content-type gets updated. I’m calling the incrementVersion function from lifecycles.js in other content types:

module.exports = {
  async afterCreate() {
    await strapi.service('api::version.version').incrementVersion();
  },
  async afterUpdate() {
    await strapi.service('api::version.version').incrementVersion();
  },
  async afterDelete() {
    await strapi.service('api::version.version').incrementVersion();
  },
};

This is in src/api/version/services/version.js:

'use strict';

/**
 * version service
 */

const { createCoreService } = require('@strapi/strapi').factories;

module.exports = createCoreService('api::version.version', ({ strapi }) => ({
    async incrementVersion() {
        const versions = await strapi.entityService.findMany('api::version.version');
        
        if (versions && versions.length > 0) {
          const version = versions[0];
          let currentVersion = version.contentVersion || 0; 
          currentVersion += 1; 
      
          await strapi.entityService.update('api::version.version', version.id, {
            data: {
                attributes: {
                  contentVersion: currentVersion,
                }
              },
          });
      
        } else {
          console.log('Global config not found, creating new entry');
          await strapi.entityService.create('api::version.version', {
            data: {
              attributes: {
                contentVersion: 1,
              }
            },
          });
        }
      }
}));

From the logs, I can tell it gets successfully called, but it never finds the entity, and likewise it never creates the entity in the else {} part.

I simply get this in server log, again and again:

Global config not found, creating new entry

Solution

  • You have to remove the "attributes" object

    await strapi.entityService.create('api::version.version', {
      data: {
        contentVersion: 1,
      },
    });
    

    Just tested and that works well on my side.