Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created September 25, 2018 06:00
Show Gist options
  • Select an option

  • Save kmelve/52951fa9e56f0c3002fa121a21f2f8d6 to your computer and use it in GitHub Desktop.

Select an option

Save kmelve/52951fa9e56f0c3002fa121a21f2f8d6 to your computer and use it in GitHub Desktop.
Webtask.io Serverless Comments for Sanity.io based blog projects with SPAM protection
/*
* Webtask.io Serverless Comments for Sanity.io based blog projects with SPAM protection
*
* Get Akismet API token (free for non-commercial projects): https://akismet.com/development/
* Make an API token with write permissions in manage.sanity.io/projects/<ProjectId>
*
* Remember to add Secrets and NPM Modules
*/
require('babel-polyfill');
const sanityClient = require('@sanity/client');
const {Client: AxismetClient,Author, Comment } = require('@cedx/akismet');
const client = token => sanityClient({
projectId: '<PROJECTID>',
dataset: '<DATASETNAME>',
token
})
/**
* @param context {WebtaskContext}
*/
module.exports = async function(context, cb) {
const { comment } = context.body;
const { SANITY_TOKEN, AKISMET_TOKEN } = context.secrets;
const akismetClient = new AxismetClient(AKISMET_TOKEN, 'http://localhost:3000');
let isValid = await akismetClient.verifyKey();
if (isValid) {
try {
const commentToBeChecked = new Comment(
new Author('127.0.0.1', 'Mozilla/5.0'),
{content: comment.text, date: Date.now()}
);
const isSpam = await akismetClient.checkComment(commentToBeChecked);
console.log(isSpam ? `The comment is marked as spam. ${JSON.stringify(comment, null, 2)} ` : 'The comment is marked as ham.');
const response = isSpam ? cb(null, { error: 'This is spam!'}) : await client(SANITY_TOKEN).create(comment).catch(error => cb(null, {error}));
cb(null, { response });
} catch (error) {
console.log(`An error occurred: ${error}`);
cb(null, { error })
}
}
const response = await client(SANITY_TOKEN).create(comment).catch(error => cb(null, {error}));
cb(null, { response });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment