Skip to content

Instantly share code, notes, and snippets.

@vivianspencer
Created July 17, 2022 03:58
Show Gist options
  • Save vivianspencer/abe97884f11d46c8b36c6572ef7cefdd to your computer and use it in GitHub Desktop.
Save vivianspencer/abe97884f11d46c8b36c6572ef7cefdd to your computer and use it in GitHub Desktop.
import pjson from './package.json';
export default class Akismet {
protected blog: string;
protected key: string;
protected userAgent: string;
protected rootEndpoint: string;
protected endpoint: string;
// Configure our client based on provided options
constructor() {
this.blog = process.env.APP_URL;
this.key = process.env.AKISMET_API_KEY;
this.userAgent = `Node.js/${process.version} | ${pjson.name}/${pjson.version}`;
this.rootEndpoint = `https://rest.akismet.com/1.1`;
this.endpoint = `https://${this.key}.rest.akismet.com/1.1`;
}
verifyKey = async () => {
try {
const url = `${this.rootEndpoint}/verify-key`;
const request = fetch(url, {
method: 'POST',
headers: {
'User-Agent': this.userAgent,
},
body: new URLSearchParams({
key: this.key,
blog: this.blog,
}),
});
const response = await request;
if (response.status === 200) {
return true;
}
} catch (err) {
console.error('Could not reach Akismet');
}
return false;
};
checkSpam = async (name: string, email: string, message: string) => {
try {
const url = `${this.endpoint}/comment-check`;
const data = {
user_ip: '127.0.0.1',
// user_ip: userRequest.ip,
// user_agent: userRequest.ua,
// permalink: userRequest.nextUrl,
comment_type: 'contact-form',
comment_author: name,
comment_email: email,
comment_content: message,
blog: this.blog,
is_test: process.env.DEBUG,
};
console.log(data);
const request = fetch(url, {
method: 'POST',
headers: {
'User-Agent': this.userAgent,
},
body: new URLSearchParams(data),
});
const response = await request;
if (response.status === 200) {
const result = await response.text();
console.log(result);
if (result === 'true') {
return true;
}
if (result === 'false') {
return false;
}
if (result === 'invalid') {
throw new Error('Invalid API key');
}
const platformError = response.headers.get('x-akismet-debug-help');
if (platformError) {
throw new Error(platformError);
}
throw new Error(result);
}
} catch (err) {
console.error('An error occurred with Akismet');
console.log(err);
}
return false;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment