Search code examples
javascriptnode.jsrestcontent-management-systemstrapi

How to perform certain action when a post is created in Strapi CMS?


I am using Strapi CMS for my data handling with a NoSQL database. So, what I am trying to do is to publish the blog on Medium also when I publish it on Strapi CMS.

I have all the credentials for publishing it on medium using API.

So, the question is how to achieve this, how to perform a certain action in Strapi CMS when a post is created or updated, so that I can get the data and send to Medium via POST request.

enter image description here


Solution

  • So after some research and instruction by Ghosh I came to know about the webhooks provided by Strapi by default.

    These hooks are somewhat same as React Lifecycle Hooks

    More about hooks: Here

    So for my case I have to add a hook which trigger some action after blog post is created. So, in api/blog/models/{blog}.js, I added this code

    "use strict";
    const fetch = require("node-fetch");
    
    module.exports = {
      lifecycles: {
        async afterCreate(data) {
          const body = {
            title: data.title,
            contentFormat: "markdown",
            content: data.blog_data,
            tags: [],
          };
          const response = await fetch(
            `https://api.medium.com/v1/users/${process.env.CLIENT_SECRET}/posts?accessToken=${process.env.ACCESS_TOKEN}`,
            {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(body),
            }
          );
        },
      },
    };