Custom service v4 not working

System Information
  • Strapi Version: 4.5.4
  • Operating System: MAC
  • Database: sql lite
  • Node Version: v18.12.1
  • NPM Version: 8.19.2

Created custom service in api/blog/services/blog.js

Blockquote
module.exports = createCoreService(‘api::blog.blog’), ({ strapi }) => ({
async doSomething() {
let response = { okay: true }
return response
}
})

and calling from controller as
await strapi.service(‘api::blog.blog’).doSomething();

getting error like
error: Cannot read properties of undefined (reading ‘doSomething’)
TypeError: Cannot read properties of undefined (reading ‘doSomething’)
at Object.find (/Users/P808694/projects/backend/src/api/blog/controllers/blog.js:17:35)


Did you create a custom route in the controller or how is your controller looking ?

I did not create new custom route but I was calling custom service method from existing find method. (basically modifying existing core controller action)

I’m having the same issue - any news here?

The only solution i’ve found to this is to create a single-type entity, and add the service there. For some reason a content-types and/or controllers and/or routes folder is required.

Also, writing the service in TS does not work either. Changing the file type from ts → js already results in another error message.

I don’t know if this can help, but I’m currently creating my Controllers and Services this way:

My code:

const modelUid = "api::company.company";
module.exports = createCoreService(modelUid, ({ strapi }) => ({
 async doSomething(){ ... }
} ) ); 

OP code:

module.exports = createCoreService(‘api::blog.blog’), ({ strapi }) => ({
 async doSomething() { ... }
} )

see the diference in createCoreService? My function still open until the final lines

REF: Services | Strapi Documentation

Hey buddy, thank you for the reply

This is how my code looks like:

module.exports = createCoreService(
  "api::my-collection.my-collection",
  ({ strapi }) => ({
    async doMagic() {
  }
}

As you can see here, I’m actually doing it the same as you do. I guess OP had some typo in there (?)

Anyhow, which strapi version are you currently using?

Today I’m using version v4.12.4 (because a bug was fixed that made it impossible to edit the component form) .
And in another project, the v4.11.2 .

In both I use the same code and they work

Your controller/service file inside is “…api/myCollection/services/myCollection.js” or “…api/my-collection/services/my-collection.js” ? Strapi requires filenames in kebab case to work

If the code is not something private (company etc) and you want to share part of your code / repository so I can see how the calls are organized, feel free!