my strapi cheat-sheet

strapi is a really nice headless CMS, very flexible and very productive - but written in javascript. Not sure if the huge amount of flexibility is a prove for the awesomenes of strapi or a prove how broken javascript is …

However, i dive deeper and need a place to write down a few snippets :)

Basics

for environment configurations, just overwrite everything you need in /config/env/STAGE/

// loading configs, in the /config folder
const conf = strapi.config.get('file.object.attribute')

// load a service
const modelService = strapi.services["my-model"]
// load service from a plugin
const pluginService = strapi.plugins['my-plugin'].services['my-plugin-service'];

// working with models
strapi.query('user').find({ _where: {}})
strapi.query('user').findOne({ id: 1})
strapi.query('user').create({})
strapi.query('user').update({id: 1}, {})
strapi.query('user').delete({ id: 1})

// models from plugins
strapi.query('user', 'plugin').create({})

// https://strapi.io/documentation/v3.x/concepts/queries.html#queries

Middlewares

// middlewares/name/index.js
module.exports = strapi => {
  return {
    initialize() {

      // load config
      const conf = strapi.config.get('middleware.settings.name')
      
      strapi.app.use(async (ctx, next) => {

        // code before controller
        await next();
        // code after strapi logic

        // we want to replace image URLs in all graphql responses
        if(ctx.request.url.startsWith(`/graphql`)) {
          // body is plain string
          const replaced = ctx.response.body.replace(new RegExp(conf.original, 'g'), conf.replacement)
          ctx.response.body = replaced

        } 
      });
    },
  };
};

Replacement regex

with a positive lookahead

...

Last posts

Tags