|
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; |
|
}; |
|
} |