Search code examples
javascriptreactjsstrapi

how to disable unpublish in strapi


I am using strapi 4 and I am creating a custom middleware to prevent unpublish posts. Actually I don't want to let user to unpublish posts.

This is my middleware code

// src/middlewares/prevent-unpublish.ts

module.exports = (config, { strapi }) => {
    return async (context, next) => {
        const isPostRequest = context.request.method === 'POST';
        const isPostsEndpoint = context.request.url.startsWith('/content-manager/collection-types/api::post.post');
      // Check if the request is a POST request and the URL is for the posts endpoint
        
      strapi.log.info('Checking request:', isPostRequest, isPostsEndpoint);
    
      if (isPostRequest && isPostsEndpoint) {
        const data = context.request.body;
        strapi.log.info('Request body:', data);
  
        // Check if the publishedAt field is set to null (indicating an attempt to unpublish)
        if (data && data.publishedAt === null) {
          // Throw an error to prevent unpublishing
          context.throw(403, 'Unpublishing posts is not allowed.');
        }
      }
  
      // Continue with the next middleware
      await next();
    };
  };
  

Currently this code is not working, because I dont have access to request body. How can I fix this problem?


Solution

  • You had incorrect parameter for strapi.log.info(), try this:

    strapi.log.info(`Request body: ${JSON.stringify(data)}`); 
    // or
    console.log("Request body:", data);
    

    if you are using VS Code, you can set breakpoints to watch value of variables instead of print out: https://forum.strapi.io/t/strapi-v4-debug-breakpoints-do-not-bind-in-vs-code/21181/2