mathis
February 21, 2024, 2:12pm
1
site name: https://kiaboeck-training.netlify.app
Hi, I am trying to implement this function: Using Netlify Functions to Delete Form Submissions - Adrian Payne | Frontend Dev Blog
I first got errors regarding the import. Now I use the following
import { NetlifyAPI } from 'netlify';
export default async () => {
const client = new NetlifyAPI(process.env.NETLIFY_API_ACCESS_TOKEN);
const submissions = await client
.listSiteSubmissions({
site_id: process.env.SITE_ID,
})
.catch((e) => console.log('Error getting submissions', e));
if (submissions.length) {
console.log('Deleting ' + submissions.length + ' submissions');
for (i = 0; i < submissions.length; i++) {
await client.deleteSubmission({ submission_id: submissions[i].id });
}
return {
statusCode: 200,
body: 'Submissions deleted',
};
} else {
return {
statusCode: 200,
body: 'No submissions to delete',
};
}
};
But I get the error Error: Cannot find module ‘@netlify /open-api’
I tried adding that as a dependency, but no luck.
"@netlify/functions": "^2.6.0",
"netlify": "^13.1.14",
"@netlify/open-api": "^2.28.0",
Can someone help?
How can I delete form submissions automatically?
You don’t need to use any package. Simply make a DELETE
request to: https://api.netlify.com/api/v1/submissions/{submission_id}
with your auth token.
mathis
February 21, 2024, 3:36pm
3
Ah, great. Thanks. Do you also know how I can make sure this runs after every form submission and how do I get the submission_id?
For running after every submission, you can refer to: Form submissions | Netlify Docs . You’d be looking at submission-created
function. That should contain the ID as well.
mathis
February 23, 2024, 9:48am
5
Thank you. I have a working solution:
file: netlify/functions/submission-created.js
exports.handler = async function (event, context) {
const response = await fetch(
'https://api.netlify.com/api/v1/sites/' + process.env.SITE_ID + '/submissions',
{
method: 'GET',
headers: {
Authorization: 'Bearer ' + process.env.NETLIFY_API_ACCESS_TOKEN,
},
}
);
if (!response.ok) {
return {
statusCode: response.status,
body: response.statusText,
};
}
let responseText = await response.text();
let submissions = JSON.parse(responseText);
if (submissions.length) {
console.log('found ' + submissions.length + ' submissions');
for (let i = 0; i < submissions.length; i++) {
await deleteSubmission(submissions[i].id);
}
return {
statusCode: 200,
body: 'Submissions deleted',
};
} else {
return {
statusCode: 200,
body: 'No submissions to delete',
};
}
};
async function deleteSubmission(submission_id) {
const response = await fetch('https://api.netlify.com/api/v1/submissions/' + submission_id, {
method: 'DELETE',
headers: {
Authorization: 'Bearer ' + process.env.NETLIFY_API_ACCESS_TOKEN,
},
});
if (response.ok) {
console.log('deleted submission: ', submission_id);
} else {
console.log('failed to delete submission: ', response.statusText);
}
}