UNPKG

velocity-api

Version:

A super fast API Wrapper for Perspective.

70 lines (69 loc) 2.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Velocity = void 0; const tslib_1 = require("tslib"); const petitio_1 = tslib_1.__importDefault(require("petitio")); class Velocity { #key; constructor(key) { this.#key = key; } async processMessage(message, options) { const { attributes = ['SPAM', 'TOXICITY'], context, doNotStore = true, languages = ['en'], } = options; this.#validateString(message); this.#validateAttributes(attributes); const request = { comment: { text: message, }, context, doNotStore, languages, requestedAttributes: this.#buildAttributes(attributes), }; try { const response = await this.#analyzeMessage(request); const scoreVals = {}; const keys = Object.keys(response.attributeScores); for (var i = 0; i !== keys.length; ++i) { const k = keys[i]; if (response.attributeScores[k]) scoreVals[k] = Number.parseFloat(response.attributeScores[k].summaryScore.value); } return scoreVals; } catch (ex) { throw new Error(ex); } } #validateString(message) { switch (true) { case message.length === 0: throw new Error('Message provided should not be empty'); case message.length > 20480: throw new Error('Message should be under 20,480 characters.'); } } #validateAttributes(attributes) { if (attributes.length < 1) throw new Error('Please provide at least one attribute to score.'); for (var i = 0; i !== attributes.length; ++i) { const k = attributes[i]; if (k === undefined) throw new Error(`Invalid attribute provided: ${k}`); } } #buildAttributes(attributes) { const attrObj = {}; for (var i = 0; i !== attributes.length; ++i) attrObj[attributes[i]] = {}; return attrObj; } async #analyzeMessage(object) { return (0, petitio_1.default)('https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze', 'POST') .body(object) .query('key', this.#key) .json(); } } exports.Velocity = Velocity;