How to refactor the schedule posts for strapi v4

System Information
  • Strapi Version: v4.*

I’m trying to rewrite the schedule posts from guides to strapi V4

  let draftArticleToPublish = await strapi.api.article.services.article.find(
        { publicationState: 'preview',
          // next two filter not taken into account in find 
          published_at_null: true,      // so we add another condition here to filter entries that have not been published
          publish_at_lt: new Date()
        }
      )

       // update published_at of articles
      await Promise.all(draftArticleToPublish.results.map(article => {
        console.log('article', article.id)
        // filters in update not working 
        return strapi.api.article.services.article.update(
          { id: article.id },
          { published_at: new Date() }
        );
      }));

first question: the filters in find() are not working.

  • PublicationState: “preview” is returning draft and published

  • But filters published_at: null is not filtering in the result

  • and the update() functions return error Undefined attribute level operator id


So i Found the solution to the first part of my problem,
You need to use the filter property in the find() like this

      let draftArticleToPublish = await strapi.api.article.services.article.find(
        {
          publicationState: 'preview',
          filters: {
            publishedAt: null,
            publishOn: new Date(new Date().setSeconds(0, 0))  // round the date to minute
          }   
        }
      )

thanks @Daedalus for sharing this solutions with me it’s working

/config/controllers/schedulePost.js

module.exports = {
  schedulePublishArticles: async (strapi) => {
    try {
      const entries = await strapi.entityService.findMany('api::article.article', {
        publicationState: 'preview',
        filters: {
          publishedAt: {$null: true},
          // publish_at: {$lt: new Date()},
        },
      });

      await Promise.all(entries.map(async (article) => {
        return await strapi.entityService.update('api::article.article', article.id, {
          data: {
            publishedAt: new Date()
          }
        })
      }))

    } catch (e) {
      console.log(e.message)
    }
  }
}

config/server/

schedule = require('./controllers/scedulePosts')

module.exports = ({ env }) => ({
  host: env('HOST', '0.0.0.0'),
  port: env.int('PORT', 1337),
  cron :{
    enabled: true,
    tasks: {
      '* * * * *': ({ strapi }) => {
        schedule.schedulePublishArticles(strapi)
      }
    }
  }
});