A couple of days ago i needed to create a webhook to trigger a GatsbyJs build after update, create or delete something in our backend using Strapi.
Strapi has a built in option to do that very easy if your frontend app is on Netlify, but our app is on Digitalocean so we need to create our own webhook.
Reading digitalocean's documentation i found that the url that we need to make the request is this one:
https://api.digitalocean.com/v2/apps/YOUR_APP_ID/deployments
First we need to go to our api endpoint models (in this case i'm using Strapi) and i want to rebuild after creating , deleting or updating a post, so i will go to /api/posts/models/posts.js
We are going to use Strapi lifecycles hooks, afterCreate,afterUpdate,afterDestroy.
We also need to create a Token / Key in digitalocean (your digitalocean account/->api->Tokens/Keys)
I put the token in a .env file as POSTS_BUILD_TOKEN
then install axios npm i axios
Our /api/posts/models/posts.js
should look like this:
'use strict';
const axios = require('axios')
const token = process.env.POSTS_BUILD_TOKEN
module.exports = {
lifecycles: {
async afterCreate() {
axios({
method: 'post',
headers: {
'Content-Type': 'json',
'Authorization': `Bearer ${token}`
},
url: 'https://api.digitalocean.com/v2/apps/${token}/deployments',
body:{
"force_build":true
}
});
},
}
};
Then you can go to your Content Type and create, edit or delete and as soon as you click save, it will trigger the build.
Top comments (5)
@sujithvn @garbanv
The build was skipped because the "force_build" parameter wasn't passed correctly.
You should change body:{"force_build":true} to data:{"force_build":true}.
It worked for me and it pulls the updated content.
Also, instead of using Strapi's lifecicle hooks for each content type, I'm using the built-in webhooks. But since you can't set a body (only the headers), I made a small node service that receives a request from Strapi, and then sends a proper request to DigitalOcean.
I hope this helps,
Cheers
It does create the build, but does not pull the updated content from strapi. The DO deployment build log says
"The build was skipped for component "my-gatsby-app""
Note - in your code sample of posts.js, we have to use the APP-ID instead of token in the 'url' parameter. APP-ID is the id of the gatsby app deployed.
Hello, thanks for noticing, it was my mistake, it is as you say, the APP_ID what you need to put in the url. Did you manage to get the updated content from strapi? am also having the same issue
No, as I mentioned above, I was able to trigger the build, but it gets skipped as there are no changes to the source code.
I do not remember where I read it, but someone was mentioning that #digitalocean does not give option to clear build cache when done via API call.
Hi Can I find the APP_ID