I’m using Strapi for a few projects and have begun diving into leveraging it to power most of the backend business logic for my apps.
What remains unclear are the recommended best practices for building backend services. How to I call functions from my development environment for the purpose of debugging?
I thought strapi console
was the solution but running service functions (e.g.: strapi.services.myservice.function()
) doesn’t output console.logs or the return value, just things like [AsyncFunction: myFunc]
.
Short of debugging through the API, I don’t see what other solutions might exist. I’ve searched and couldn’t find any good articles on this or proper use of strapi console
.
Thanks
With the help of people in the Slack, I was able to find two solutions to my question.
Solution 1: The hack
It’s possible to load Strapi in a js file and debug from within this file. Save this file as run.js
in the project root folder and run node run.js .
const path = require('path')
const createStrapiApp = async projectPath => {
if (!projectPath) {
throw new Error(`
-> Path to strapi project is missing.
-> Usage: node run.js [path]`)
}
let strapi
let app
try {
strapi = require(require.resolve('strapi', { paths: [projectPath] }))
const pkgJSON = require(path.resolve(projectPath, 'package.json'))
if (!pkgJSON || !pkgJSON.dependencies || !pkgJSON.dependencies.strapi) {
throw new Error()
}
} catch (e) {
throw new Error(`
-> Strapi lib couldn\'t be found. Are the node_modules installed?
-> Fix: yarn install or npm install`)
}
try {
app = await strapi({ dir: projectPath }).load()
} catch (e) {
throw new Error(`
-> The migration couldn't be proceed because Strapi app couldn't start.
-> ${e.message}`)
}
return app
}
const run = async () => {
const projectPath = process.argv[2]
const strapi = await createStrapiApp(projectPath)
// call strapi commands here
strapi.query('entity')
strapi.services.myservice.myfunc()
}
run()
.catch(e => {
console.error(e)
process.exit(1)
})
.then(() => {
console.log('Done')
process.exit(0)
})
Solution 2: strapi console
You can call the strapi
object in strapi console
strapi.services.myservice.myfunc().then(result => strapi.log.info(result))
1 Like