UNPKG

@kduprey/perspective-api-client

Version:
118 lines 3.23 kB
// src/index.ts import axios from "axios"; import _ from "lodash"; import ISO6391 from "iso-639-1"; var COMMENT_ANALYZER_URL = "https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze"; var MAX_LENGTH = 20480; var PerspectiveAPIClientError = class extends Error { constructor(message) { super(message); Error.captureStackTrace(this, this.constructor); this.name = "PerspectiveAPIClientError"; } }; var TextEmptyError = class extends PerspectiveAPIClientError { constructor() { super("text must not be empty"); this.name = "TextEmptyError"; } }; var TextTooLongError = class extends PerspectiveAPIClientError { constructor() { super( `text must not be greater than ${MAX_LENGTH.toString()} characters in length` ); this.name = "TextTooLongError"; } }; var ResponseError = class extends PerspectiveAPIClientError { response; constructor(message, response) { super(message); this.response = response; this.name = "ResponseError"; } }; var Perspective = class { static PerspectiveAPIClientError; static TextEmptyError; static TextTooLongError; static ResponseError; apiKey; constructor({ apiKey }) { this.apiKey = apiKey; if (!this.apiKey) { throw new Error("Must provide options.apiKey"); } } async analyze(text, attriubtes, options) { const request = { comment: { text }, requestedAttributes: this.parseAttributes(attriubtes ?? { TOXICITY: {} }), ...options }; this.validateComment(text); if (options?.languages) { this.validateLanguages(options.languages); request.languages = options.languages; } const response = await axios.post(COMMENT_ANALYZER_URL, request, { params: { key: this.apiKey } }).catch((error) => { if (axios.isAxiosError(error)) { const responseError = new ResponseError(error.message, error); throw responseError; } console.error("Unknown error", error); return Promise.reject(new Error("Unknown error - see logs")); }); return response.data; } validateComment(text) { if (!text) { throw new TextEmptyError(); } if (text.length > MAX_LENGTH) { throw new TextTooLongError(); } } validateLanguages(languages) { languages.forEach((language) => { if (ISO6391.validate(language)) { throw new PerspectiveAPIClientError( `language ${language} is not supported` ); } }); } parseAttributes(attributes) { if (_.isArray(attributes)) { return _.reduce( attributes, (acc, attribute) => { acc[attribute] = {}; return acc; }, {} ); } Object.values(attributes).forEach((attribute) => { if (attribute.scoreThreshold && (attribute.scoreThreshold < 0 || attribute.scoreThreshold > 1)) { throw new PerspectiveAPIClientError( "scoreThreshold must be between 0 and 1" ); } }); return attributes; } }; var src_default = Perspective; export { MAX_LENGTH, PerspectiveAPIClientError, ResponseError, TextEmptyError, TextTooLongError, src_default as default }; //# sourceMappingURL=index.mjs.map