فهرست منبع

Refactor cron task for blog publishing: add safety checks, enhance error handling, and update auto_publish logic; update blog schema to include auto_publish attribute.

kai-zong 8 ماه پیش
والد
کامیت
54118a9977
3فایلهای تغییر یافته به همراه91 افزوده شده و 43 حذف شده
  1. 50 20
      config/cron-tasks.ts
  2. 25 12
      src/api/blog/content-types/blog/schema.json
  3. 16 11
      types/generated/contentTypes.d.ts

+ 50 - 20
config/cron-tasks.ts

@@ -1,28 +1,58 @@
 module.exports = {
 module.exports = {
   checkPublish: {
   checkPublish: {
-    task: async ({ strapi }) => {
-      const now = new Date();
-      const drafts = await strapi.documents('api::blog.blog').findMany({
-        filters: { 
-          publish_at: { $lte: now },
-          isNewVersion: true 
-        },
-        status: 'draft',
-      });
-      for (const draft of drafts) {
-        console.log('Publishing entry:', draft.documentId);
-        await strapi.documents('api::blog.blog').update({
-          documentId: draft.documentId,
-          data: { isNewVersion: false },
-          status: 'draft',
-        });
-        await strapi.documents('api::blog.blog').publish({
-          documentId: draft.documentId,
-        });
+    task: async ({ strapi }: { strapi: any }) => {
+      try {
+        // Safety check: verify the content type exists before proceeding
+        if (!strapi.contentTypes['api::blog.blog']) {
+          console.log('Blog content type not found. Skipping scheduled publish task.');
+          return;
+        }
+
+        const now = new Date();
+        console.log('[Cron] Checking for scheduled blog posts to publish at:', now.toISOString());
+
+        try {
+          const drafts = await strapi.documents('api::blog.blog').findMany({
+            filters: { 
+              publish_at: { $lte: now },
+              auto_publish: true 
+            },
+            status: 'draft',
+          });
+
+          console.log(`[Cron] Found ${drafts?.length || 0} blog posts to publish`);
+
+          for (const draft of drafts) {
+            try {
+              console.log('[Cron] Publishing entry:', draft.documentId);
+              
+              // Update the auto_publish flag first
+              await strapi.documents('api::blog.blog').update({
+                documentId: draft.documentId,
+                data: { auto_publish: false },
+                status: 'draft',
+              });
+              
+              // Then publish the blog post
+              await strapi.documents('api::blog.blog').publish({
+                documentId: draft.documentId,
+              });
+              
+              console.log('[Cron] Successfully published blog post:', draft.documentId);
+            } catch (postError) {
+              console.error(`[Cron] Error publishing blog post ${draft.documentId}:`, postError);
+              // Continue with next post even if one fails
+            }
+          }
+        } catch (queryError) {
+          console.error('[Cron] Error querying drafts:', queryError);
+        }
+      } catch (error) {
+        console.error('[Cron] Uncaught error in checkPublish task:', error);
       }
       }
     },
     },
     options: {
     options: {
-      rule: '* * * * *',
+      rule: '*/10 * * * *', // Run every 10 minutes
     },
     },
   },
   },
 };
 };

+ 25 - 12
src/api/blog/content-types/blog/schema.json

@@ -4,31 +4,44 @@
   "info": {
   "info": {
     "singularName": "blog",
     "singularName": "blog",
     "pluralName": "blogs",
     "pluralName": "blogs",
-    "displayName": "blog",
-    "description": ""
+    "displayName": "blog"
   },
   },
   "options": {
   "options": {
     "draftAndPublish": true
     "draftAndPublish": true
   },
   },
   "attributes": {
   "attributes": {
     "title": {
     "title": {
-      "type": "string"
+      "type": "string",
+      "required": true,
+      "unique": true
     },
     },
-    "idk": {
-      "type": "blocks"
+    "author_name": {
+      "type": "string",
+      "default": "Genii"
     },
     },
-    "publish_at": {
-      "type": "datetime"
-    },
-    "ckeditor": {
+    "main_body": {
       "type": "customField",
       "type": "customField",
+      "required": true,
       "options": {
       "options": {
-        "preset": "defaultHtml"
+        "preset": "defaultMarkdown"
       },
       },
       "customField": "plugin::ckeditor5.CKEditor"
       "customField": "plugin::ckeditor5.CKEditor"
     },
     },
-    "isNewVersion": {
-      "type": "boolean"
+    "publish_at": {
+      "type": "datetime"
+    },
+    "auto_publish": {
+      "type": "boolean",
+      "default": false,
+      "required": true
+    },
+    "cover_image": {
+      "allowedTypes": [
+        "images",
+        "files"
+      ],
+      "type": "media",
+      "multiple": false
     }
     }
   }
   }
 }
 }

+ 16 - 11
types/generated/contentTypes.d.ts

@@ -473,7 +473,6 @@ export interface ApiAuthorAuthor extends Struct.CollectionTypeSchema {
 export interface ApiBlogBlog extends Struct.CollectionTypeSchema {
 export interface ApiBlogBlog extends Struct.CollectionTypeSchema {
   collectionName: 'blogs';
   collectionName: 'blogs';
   info: {
   info: {
-    description: '';
     displayName: 'blog';
     displayName: 'blog';
     pluralName: 'blogs';
     pluralName: 'blogs';
     singularName: 'blog';
     singularName: 'blog';
@@ -482,24 +481,30 @@ export interface ApiBlogBlog extends Struct.CollectionTypeSchema {
     draftAndPublish: true;
     draftAndPublish: true;
   };
   };
   attributes: {
   attributes: {
-    ckeditor: Schema.Attribute.RichText &
-      Schema.Attribute.CustomField<
-        'plugin::ckeditor5.CKEditor',
-        {
-          preset: 'defaultHtml';
-        }
-      >;
+    author_name: Schema.Attribute.String & Schema.Attribute.DefaultTo<'Genii'>;
+    auto_publish: Schema.Attribute.Boolean &
+      Schema.Attribute.Required &
+      Schema.Attribute.DefaultTo<false>;
+    cover_image: Schema.Attribute.Media<'images' | 'files'>;
     createdAt: Schema.Attribute.DateTime;
     createdAt: Schema.Attribute.DateTime;
     createdBy: Schema.Attribute.Relation<'oneToOne', 'admin::user'> &
     createdBy: Schema.Attribute.Relation<'oneToOne', 'admin::user'> &
       Schema.Attribute.Private;
       Schema.Attribute.Private;
-    idk: Schema.Attribute.Blocks;
-    isNewVersion: Schema.Attribute.Boolean;
     locale: Schema.Attribute.String & Schema.Attribute.Private;
     locale: Schema.Attribute.String & Schema.Attribute.Private;
     localizations: Schema.Attribute.Relation<'oneToMany', 'api::blog.blog'> &
     localizations: Schema.Attribute.Relation<'oneToMany', 'api::blog.blog'> &
       Schema.Attribute.Private;
       Schema.Attribute.Private;
+    main_body: Schema.Attribute.RichText &
+      Schema.Attribute.Required &
+      Schema.Attribute.CustomField<
+        'plugin::ckeditor5.CKEditor',
+        {
+          preset: 'defaultMarkdown';
+        }
+      >;
     publish_at: Schema.Attribute.DateTime;
     publish_at: Schema.Attribute.DateTime;
     publishedAt: Schema.Attribute.DateTime;
     publishedAt: Schema.Attribute.DateTime;
-    title: Schema.Attribute.String;
+    title: Schema.Attribute.String &
+      Schema.Attribute.Required &
+      Schema.Attribute.Unique;
     updatedAt: Schema.Attribute.DateTime;
     updatedAt: Schema.Attribute.DateTime;
     updatedBy: Schema.Attribute.Relation<'oneToOne', 'admin::user'> &
     updatedBy: Schema.Attribute.Relation<'oneToOne', 'admin::user'> &
       Schema.Attribute.Private;
       Schema.Attribute.Private;