Skip to content
Advertisement

How to add side effect to creating new record in Strapi by customizing controller?

I am trying to trigger a side effect (send notification, using socket.io) when adding new record in Strapi. The socket setup is OK, successfully emitting from back-end (Strapi API) to front-end. I followed the docs on customizing controllers and the recommendations in this Stack Overflow thread, but didn’t help. Nothing happens when changing the controller – tried to break it by replacing the create function body with just return null; or console.log(), but still nothing. Here’s the ../controllers/Orders.js:

'use strict';
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
module.exports = {
  async create(ctx) {
    let entity;
    if (ctx.is('multipart')) {
      const { data, files } = parseMultipartData(ctx);
      entity = await strapi.api.order.services.order.create(data, { files });
    } else {
      entity = await strapi.api.order.services.order.create(ctx.request.body);
    }
    strapi.emitToAllUsers(entity);
    return sanitizeEntity(entity, { model: strapi.query('order').model });
  },
};

strapi.emitToAllUsers() is defined in bootstrap.js. Connection ready messages and other emitted data is received in the front end, but stuff inside the controller seems to not be invoked at all. Here’s the boilerplate stuff from bootstrap.js:

'use strict'; 
require('dotenv').config({ path: require('find-config')('.env') }); 

module.exports = () => {   
  var io = require('socket.io')(strapi.server);   
  var users = [];     
  io.on('connection', socket => {
     socket.user_id = (Math.random() * 100000000000000); // not so secure
     users.push(socket); // save the socket to use it later
     socket.on('disconnect', () => {
       users.forEach((user, i) => {
         // delete saved user when they disconnect
         if (user.user_id === socket.user_id) {
           users.splice(i, 1);
         }
       });
     });
     io.emit('emit_test');   
  });   
  strapi.io = io;   
  // send to all users connected   
  strapi.emitToAllUsers = (order) => { 
    io.emit('new_order', order);   
  }; 
};

Advertisement

Answer

API controllers ./api/blabla/controllers/Blabla.js are only called by your REST API. To make sure the Admin panel will work in any circumstances, the Content Manager plugin uses it’s own functions. If you want to apply so things to both REST API and Admin panel, you will have to customize the life cycle functions. But you will have less flexibility because of some issues you will be able to find in this thread https://github.com/strapi/strapi/issues/1443

Source: Strapi

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement