Best practices for backend development

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