From 73c2f31100f8b766509d905f49edf289f07470f4 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Mon, 31 Aug 2020 00:59:13 +0300 Subject: [PATCH 01/22] Fetch languages --- .editorconfig | 15 +++ .eslintignore | 3 + .eslintrc | 15 +++ .gitignore | 44 ++++++++- .npmignore | 25 +++++ .travis.yml | 26 +++--- LICENSE | 223 +++++---------------------------------------- README.md | 2 +- lib/apirequest.js | 56 ------------ lib/transporter.js | 74 --------------- lib/utils.js | 40 -------- package.json | 49 +++++++--- src/client.ts | 34 +++++++ src/config.ts | 6 ++ src/index.ts | 18 ++++ test/detect.js | 37 -------- test/index.ts | 18 ++++ test/languages.js | 22 ----- test/status.js | 21 ----- tsconfig.json | 16 ++++ 20 files changed, 263 insertions(+), 481 deletions(-) create mode 100644 .editorconfig create mode 100644 .eslintignore create mode 100644 .eslintrc create mode 100644 .npmignore delete mode 100644 lib/apirequest.js delete mode 100644 lib/transporter.js delete mode 100644 lib/utils.js create mode 100644 src/client.ts create mode 100644 src/config.ts create mode 100644 src/index.ts delete mode 100644 test/detect.js create mode 100644 test/index.ts delete mode 100644 test/languages.js delete mode 100644 test/status.js create mode 100644 tsconfig.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ed5699b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# EditorConfig helps developers define and maintain +# consistent coding styles between different editors and IDEs. + +root = true + +[*] +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..437238e --- /dev/null +++ b/.eslintignore @@ -0,0 +1,3 @@ +node_modules +lib +test diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 0000000..ece2868 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,15 @@ +{ + "root": true, + "parser": "@typescript-eslint/parser", + "plugins": [ + "@typescript-eslint" + ], + "extends": [ + "eslint:recommended", + "plugin:@typescript-eslint/eslint-recommended", + "plugin:@typescript-eslint/recommended" + ], + "rules": { + "@typescript-eslint/no-var-requires": "off" + } +} diff --git a/.gitignore b/.gitignore index b8ffe08..9d9848b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,45 @@ -node_modules/ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules +jspm_packages + +# Optional npm cache directory +.npm +.npmrc + +# Optional REPL history +.node_repl_history + +# Editors +.idea + +# Lib +lib + +# npm package lock package-lock.json +yarn.lock +others +.DS_Store \ No newline at end of file diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..45c2f4a --- /dev/null +++ b/.npmignore @@ -0,0 +1,25 @@ +*.log +npm-debug.log* + +# Coverage directory used by tools like istanbul +coverage +.nyc_output + +# Dependency directories +node_modules + +# npm package lock +package-lock.json +yarn.lock + +# project files +src +test +examples +CHANGELOG.md +.travis.yml +.editorconfig +.eslintignore +.eslintrc +.babelrc +.gitignore diff --git a/.travis.yml b/.travis.yml index 37e897f..9fdba3c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,20 +1,18 @@ language: node_js -sudo: false node_js: -- '13' -- '12' -- '11' -- '10' -- '9' -- '8' -- '7' -- '6' -- '5' -- '4' -install: -- npm install +- 14 +- 13 +- 12 +- 11 +- 10 +- 9 +- 8 +- 7 +- 6 +- 5 +- 4 script: -- npm test +- yarn test env: global: secure: c9C48dtqsLNKkf/JPzp1B+M0oIWWt4k0Y1Mf5dl++Nt2RheIVh78s91RhwMYd8/WXp7/mCplkhS/hJoRAvSO39GLn4xHAInu5UuBl9KwvnojA4oo/5WW7I2E4ZNzETsjqAnriF80gJfPXumQ9T+toEza2Bbb8Q1jpfEEiXLPWJehMnBMy5D4TfZFXr7HJ7l0P06gUjvmdXyO+3/MPJo73M8CJTGRqFkbcap/CC3qTgPbZJ4NJ7N7NheJ+Fi3bv7vTtw+hwLNbV7BC+bw0KAUYkMn6AgS/FHfgv9YIkMOksn6qmBwjfIqbsRYD6Rp38Q6TCSpwIdHlnNj758j/zKsGpB7aoYKF74JXgS/fthtkUGOaqlHnt9b2Erb3/1pkNSEQ6zROU/Afn36c8KA1Ofgrps4oQhG2UWnxxZ18wi45e7Uvoe4nMxYjRw21LOraHfhljRAEnRBM/OnF+E3t+cx/rk7+ieOsV/6SjDj85D+M6hCJ27+NpdwrIEJ5kntwFsoy26+hw0Whe1HWHht1zOWrCEgs+Fgzb5jJbkJ0gvNE1hFf4oozlYRBFbTAZo0aEgOV7DAtp9ZddvnmYF7xE60tKi11B2/EsN74nh/9+RX7FW5THlySR7X2hGfQOZUjmsZCsSxxkJ9V4GnIpeNAHyhDMhcJZRQ2b0WySJoLtCpiro= diff --git a/LICENSE b/LICENSE index 360229d..6bb8ee0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,22 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2015 Peter Andreas Moelgaard - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +Copyright (c) 2020 Laurynas Butkus + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index a495313..a761474 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -Language Detection API Node Client +Language Detection API Node.js Client === [![npm version](https://badge.fury.io/js/detectlanguage.svg)](https://badge.fury.io/js/detectlanguage) diff --git a/lib/apirequest.js b/lib/apirequest.js deleted file mode 100644 index b803a88..0000000 --- a/lib/apirequest.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -var Transporter = require('./transporter.js'), - utils = require('./utils.js'); - - -/** - * Create and send request to DetectLanguage API - * @param {object} parameters Parameters used to form request - * @param {Function} callback Callback when request finished or error found - * @return {Request} Returns Request object or null - */ -function createAPIRequest(parameters, callback) { - - var url = parameters.options.ssl ? 'https' : 'http'; - url += '://'; - url += parameters.options.host; - url += '/'; - url += parameters.options.version; - url += '/'; - url += parameters.options.service; - - parameters.options.url = url; - - var params = utils.extend( - { json: true }, - parameters.params - ); - - var req = new Transporter(parameters.options).request(params, function(error, result) { - callback(error, result); - }); - return req; -} - -/** - * Exports createAPIRequest - * @type {Function} - */ -module.exports = createAPIRequest; diff --git a/lib/transporter.js b/lib/transporter.js deleted file mode 100644 index c49ba88..0000000 --- a/lib/transporter.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -var request = require('request'), - utils = require('./utils'), - pkg = require('../package.json'); - -/** - * Default transporter constructor. - * Wraps request and callback functions. - */ -function Transporter(options) { - this.options = options; -} - -/** - * Default user agent. - */ -Transporter.prototype.USER_AGENT = 'detectlanguage-javascript-client/' + pkg.version; - -/** - * Configures request options before making a request. - * @param {object} opts Options to configure. - * @return {object} Configured options. - */ -Transporter.prototype.configure = function(args) { - - // set transporter user agent - var headers = args && args.headers ? args.headers : {}; - headers['Authorization'] = 'Bearer ' + this.options.key; - headers['User-Agent'] = headers['User-Agent'] ? headers['User-Agent'] +' '+ this.USER_AGENT : this.USER_AGENT; - - args = utils.extend( - this.options, - args, - { - headers: headers, - key: null - } - ); - - return args; -}; - -/** - * Makes a request with given options and invokes callback. - * @param {object} opts Options. - * @param {Function=} opt_callback Optional callback. - * @return {Request} Request object - */ -Transporter.prototype.request = function(args, callback) { - args = this.configure(args); - return request(args, callback); -}; - -/** - * Exports Transporter. - */ -module.exports = Transporter; diff --git a/lib/utils.js b/lib/utils.js deleted file mode 100644 index 4e6e934..0000000 --- a/lib/utils.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -/** - * Export extend - * @type {Object} - */ -module.exports = { - /** - * Copy key/values to obj from all other objects passed in - * - * @param {object} a the destination object. - * @return {object} the destination object. - */ - extend: function(obj) { - var source, prop; - for (var i = 1, length = arguments.length; i < length; i++) { - source = arguments[i]; - for (prop in source) { - obj[prop] = source[prop]; - } - } - return obj; - } -}; diff --git a/package.json b/package.json index 6d09c49..0542b4d 100644 --- a/package.json +++ b/package.json @@ -1,14 +1,20 @@ { "name": "detectlanguage", - "version": "1.2.2", - "description": "This is a JavaScript Client Library for the DetectLanguage Service API", - "main": "index.js", - "directories": { - "test": "test" - }, + "version": "2.0.0", + "description": "Detect Language API Node.js Client", + "main": "./lib/index.js", + "types": "./types/index.d.ts", "scripts": { - "test": "mocha" + "clean": "rimraf lib .nyc_output node_modules/.cache coverage", + "test": "yarn lint && yarn mocha", + "mocha": "nyc mocha --require ts-node/register test/**/*.ts", + "lint": "eslint src", + "build": "yarn tsc" }, + "files": [ + "lib", + "src" + ], "repository": { "type": "git", "url": "https://github.com/detectlanguage/detectlanguage-node" @@ -16,20 +22,35 @@ "keywords": [ "language", "detection", - "detectlanguage", - "javascript" + "detect language", + "nlp", + "sdk", + "client", + "api", + "text" ], - "author": "Peter Andreas Moelgaard (http://petermolgaard.com/)", - "license": "Apache-2.0", + "author": "Laurynas Butkus ", + "license": "MIT", "bugs": { "url": "https://github.com/detectlanguage/detectlanguage-node/issues" }, "homepage": "https://github.com/detectlanguage/detectlanguage-node", "dependencies": { - "request": "^2.53.0" + "@types/node": "^14.6.2", + "axios": "^0.20.0" }, "devDependencies": { - "chai": "^4.1.2", - "mocha": "^5.1.1" + "@types/chai": "^4.2.12", + "@types/mocha": "^8.0.3", + "@typescript-eslint/eslint-plugin": "^3.10.1", + "@typescript-eslint/parser": "^3.10.1", + "chai": "^4.2.0", + "chai-as-promised": "^7.1.1", + "eslint": "^7.7.0", + "mocha": "^8.1.3", + "nyc": "^15.1.0", + "rimraf": "^3.0.2", + "ts-node": "^9.0.0", + "typescript": "^4.0.2" } } diff --git a/src/client.ts b/src/client.ts new file mode 100644 index 0000000..be8d6ea --- /dev/null +++ b/src/client.ts @@ -0,0 +1,34 @@ +import { Config } from './config'; +import axios, { AxiosInstance } from 'axios'; + +const { version } = require('../package.json'); +const USER_AGENT = 'detectlanguage-node/' + version; + +export class Client { + public connection: AxiosInstance; + + constructor(apiKey: string, config: Config) { + const protocol = config.protocol || 'https'; + const host = config.host || 'ws.detectlanguage.com'; + const apiVersion = config.apiVersion || '0.2'; + const baseURL = protocol + '://' + host + '/' + apiVersion + '/'; + const timeout = config.timeout || 60; + + const headers = { + 'User-Agent': USER_AGENT, + 'Authorization': 'Bearer ' + apiKey, + } + + this.connection = axios.create({ + baseURL, + headers, + timeout: timeout * 1000, + }) + } + + async get(path: string) { + const response = await this.connection.get(path) + + return response.data; + } +} diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..25f23f1 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,6 @@ +export interface Config { + timeout?: number, + protocol?: string, + host?: string, + apiVersion?: string, +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..7bd9fb4 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,18 @@ +import { Config } from './config'; +import { Client } from './client'; + +export class DetectLanguageInstance { + client: Client; + + constructor(apiKey: string, config: Config = {}) { + this.client = new Client(apiKey, config); + } + + async languages() { + return this.client.get('languages'); + } +} + +export default (apiKey: string, config: Config = {}): DetectLanguageInstance => { + return new DetectLanguageInstance(apiKey, config); +} diff --git a/test/detect.js b/test/detect.js deleted file mode 100644 index 3fa93bc..0000000 --- a/test/detect.js +++ /dev/null @@ -1,37 +0,0 @@ -var expect = require('chai').expect; -var DetectLanguage = require('../index'); - -describe('detect()', function () { - var detectLanguage; - - before(function() { - detectLanguage = new DetectLanguage({ - key: process.env.DETECTLANGUAGE_API_KEY, - ssl: true, - }); - }); - - it('detect language', function (done) { - var text = "I am a Teapot and a Submarine"; - - detectLanguage.detect(text, function(error, result) { - expect(error).to.be.null; - expect(result[0].language).to.be.equal('en'); - done(); - }); - }); - - it('detect languages in batch mode', function (done) { - var texts = [ - "I am a Teapot and a Submarine", - "Soy una tetera y un submarino", - "Jeg er en tekande og en ubåd" - ]; - - detectLanguage.detect(texts, function(error, result) { - expect(error).to.be.null; - expect(result[0][0].language).to.be.equal('en'); - done(); - }); - }); -}); diff --git a/test/index.ts b/test/index.ts new file mode 100644 index 0000000..c5e6715 --- /dev/null +++ b/test/index.ts @@ -0,0 +1,18 @@ +import DetectLanguage, { DetectLanguageInstance } from '../lib/index'; +import { expect } from 'chai'; + +const API_KEY = process.env.DETECTLANGUAGE_API_KEY || ''; +let detectLanguage: DetectLanguageInstance; + +beforeEach(() => { + detectLanguage = DetectLanguage(API_KEY); +}) + +describe('languages', function () { + it('fetches languages', async () => { + const result = await detectLanguage.languages(); + + expect(result[0].code).to.be.string; + expect(result[0].name).to.be.string; + }); +}); diff --git a/test/languages.js b/test/languages.js deleted file mode 100644 index 7d0838e..0000000 --- a/test/languages.js +++ /dev/null @@ -1,22 +0,0 @@ -var expect = require('chai').expect; -var DetectLanguage = require('../index'); - -describe('languages()', function () { - var detectLanguage; - - before(function() { - detectLanguage = new DetectLanguage({ - key: process.env.DETECTLANGUAGE_API_KEY, - ssl: true, - }); - }); - - it('fetches languages lists', function (done) { - detectLanguage.languages(function(error, result) { - expect(error).to.be.null; - expect(result[0].code).to.be.string; - expect(result[0].name).to.be.string; - done(); - }); - }); -}); diff --git a/test/status.js b/test/status.js deleted file mode 100644 index 14520b1..0000000 --- a/test/status.js +++ /dev/null @@ -1,21 +0,0 @@ -var expect = require('chai').expect; -var DetectLanguage = require('../index'); - -describe('status()', function () { - var detectLanguage; - - before(function() { - detectLanguage = new DetectLanguage({ - key: process.env.DETECTLANGUAGE_API_KEY, - ssl: true, - }); - }); - - it('fetches account status', function (done) { - detectLanguage.status(function(error, result) { - expect(error).to.be.null; - expect(result.status).to.be.string; - done(); - }); - }); -}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..90cf7bd --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "outDir": "./lib", + "target": "ES5", + "module": "commonjs", + "strict": true, + "declaration": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "baseUrl": "./src/", + "types": ["node", "mocha"] + }, + "include": [ + "src/**/*", + ] +} From fb42e26aca4dce742631e8c08935630970b188fe Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 20:51:46 +0300 Subject: [PATCH 02/22] Add return types --- src/client.ts | 2 +- src/index.ts | 9 +++++---- src/types.ts | 4 ++++ test/index.ts | 6 ++++-- 4 files changed, 14 insertions(+), 7 deletions(-) create mode 100644 src/types.ts diff --git a/src/client.ts b/src/client.ts index be8d6ea..1237f85 100644 --- a/src/client.ts +++ b/src/client.ts @@ -26,7 +26,7 @@ export class Client { }) } - async get(path: string) { + async get(path: string): Promise { const response = await this.connection.get(path) return response.data; diff --git a/src/index.ts b/src/index.ts index 7bd9fb4..fa24608 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,18 +1,19 @@ import { Config } from './config'; import { Client } from './client'; +import { Language } from './types'; -export class DetectLanguageInstance { +export class DetectLanguageAPI { client: Client; constructor(apiKey: string, config: Config = {}) { this.client = new Client(apiKey, config); } - async languages() { + async languages(): Promise { return this.client.get('languages'); } } -export default (apiKey: string, config: Config = {}): DetectLanguageInstance => { - return new DetectLanguageInstance(apiKey, config); +export default (apiKey: string, config: Config = {}): DetectLanguageAPI => { + return new DetectLanguageAPI(apiKey, config); } diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..4a6fc24 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,4 @@ +export interface Language { + code: string, + name: string, +} diff --git a/test/index.ts b/test/index.ts index c5e6715..4dc7bee 100644 --- a/test/index.ts +++ b/test/index.ts @@ -1,8 +1,8 @@ -import DetectLanguage, { DetectLanguageInstance } from '../lib/index'; +import DetectLanguage, { DetectLanguageAPI } from '../src/index'; import { expect } from 'chai'; const API_KEY = process.env.DETECTLANGUAGE_API_KEY || ''; -let detectLanguage: DetectLanguageInstance; +let detectLanguage: DetectLanguageAPI; beforeEach(() => { detectLanguage = DetectLanguage(API_KEY); @@ -12,6 +12,8 @@ describe('languages', function () { it('fetches languages', async () => { const result = await detectLanguage.languages(); + console.log(result); + expect(result[0].code).to.be.string; expect(result[0].name).to.be.string; }); From 85da0a0e1e99428c0f7ab34d69e7e7457e311bf7 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 21:07:02 +0300 Subject: [PATCH 03/22] Add user status endpoint --- src/index.ts | 6 +++++- src/types.ts | 11 +++++++++++ test/index.ts | 11 +++++++++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index fa24608..84d50e7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ import { Config } from './config'; import { Client } from './client'; -import { Language } from './types'; +import { Language, UserStatus } from './types'; export class DetectLanguageAPI { client: Client; @@ -12,6 +12,10 @@ export class DetectLanguageAPI { async languages(): Promise { return this.client.get('languages'); } + + async userStatus(): Promise { + return this.client.get('user/status'); + } } export default (apiKey: string, config: Config = {}): DetectLanguageAPI => { diff --git a/src/types.ts b/src/types.ts index 4a6fc24..d95295b 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2,3 +2,14 @@ export interface Language { code: string, name: string, } + +export interface UserStatus { + status: string, + date: string, + requests: number, + bytes: number, + plan: string, + plan_expires?: string, + daily_rquests_limit: number, + daily_bytes_limit: number, +} diff --git a/test/index.ts b/test/index.ts index 4dc7bee..a9055a1 100644 --- a/test/index.ts +++ b/test/index.ts @@ -12,9 +12,16 @@ describe('languages', function () { it('fetches languages', async () => { const result = await detectLanguage.languages(); - console.log(result); - expect(result[0].code).to.be.string; expect(result[0].name).to.be.string; }); }); + +describe('userStatus', function () { + it('fetches user status', async () => { + const result = await detectLanguage.userStatus(); + + expect(result.status).to.be.a('string'); + expect(result.requests).to.be.a('number'); + }); +}); From eece9f0e8959bacd1c6d04eb3911eb447055d54a Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 21:42:14 +0300 Subject: [PATCH 04/22] Add detection endpoints --- src/client.ts | 6 ++++++ src/index.ts | 20 +++++++++++++++++++- src/types.ts | 6 ++++++ test/index.ts | 27 +++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/client.ts b/src/client.ts index 1237f85..153ca32 100644 --- a/src/client.ts +++ b/src/client.ts @@ -31,4 +31,10 @@ export class Client { return response.data; } + + async post(path: string, data: any): Promise { + const response = await this.connection.post(path, data); + + return response.data; + } } diff --git a/src/index.ts b/src/index.ts index 84d50e7..3a06239 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ import { Config } from './config'; import { Client } from './client'; -import { Language, UserStatus } from './types'; +import { DetectionResult, Language, UserStatus } from './types'; export class DetectLanguageAPI { client: Client; @@ -9,6 +9,24 @@ export class DetectLanguageAPI { this.client = new Client(apiKey, config); } + async detect(text: string): Promise { + const response = await this.client.post('detect', { q: text }) + + return response.data.detections; + } + + async detectCode(text: string): Promise { + const results = await this.detect(text); + + return results[0].language; + } + + async detectBatch(texts: string[]): Promise { + const response = await this.client.post('detect', { q: texts }) + + return response.data.detections; + } + async languages(): Promise { return this.client.get('languages'); } diff --git a/src/types.ts b/src/types.ts index d95295b..b8280c4 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,9 @@ +export interface DetectionResult { + language: string, + isReliable: boolean, + confidence: number, +} + export interface Language { code: string, name: string, diff --git a/test/index.ts b/test/index.ts index a9055a1..074b3a6 100644 --- a/test/index.ts +++ b/test/index.ts @@ -8,6 +8,33 @@ beforeEach(() => { detectLanguage = DetectLanguage(API_KEY); }) +describe('detect', function () { + it('detects language', async () => { + const result = await detectLanguage.detect('labas rytas'); + + expect(result[0].language).to.eq('lt') + expect(result[0].isReliable).to.eq(true) + expect(result[0].confidence).to.be.a('number') + }); +}); + +describe('detectCode', function () { + it('detects language code', async () => { + const result = await detectLanguage.detectCode('vidur prūdo bliūdas plūdur'); + + expect(result).to.eq('lt') + }); +}); + +describe('detectBatch', function () { + it('detects languages', async () => { + const result = await detectLanguage.detectBatch(['šešios žąsys', 'Strč prst skrz krk']); + + expect(result[0][0].language).to.eq('lt'); + expect(result[1][0].language).to.eq('cs'); + }); +}); + describe('languages', function () { it('fetches languages', async () => { const result = await detectLanguage.languages(); From 73b5ee3044256e6c07de3d537f514843461f7d34 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 21:43:11 +0300 Subject: [PATCH 05/22] Adjust order --- src/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client.ts b/src/client.ts index 153ca32..54e1c27 100644 --- a/src/client.ts +++ b/src/client.ts @@ -8,11 +8,11 @@ export class Client { public connection: AxiosInstance; constructor(apiKey: string, config: Config) { + const timeout = config.timeout || 60; const protocol = config.protocol || 'https'; const host = config.host || 'ws.detectlanguage.com'; const apiVersion = config.apiVersion || '0.2'; const baseURL = protocol + '://' + host + '/' + apiVersion + '/'; - const timeout = config.timeout || 60; const headers = { 'User-Agent': USER_AGENT, From a9d867f52c969cfb50a9a6ba90b150531d5d4b1d Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 21:52:00 +0300 Subject: [PATCH 06/22] Handle not detected --- src/index.ts | 4 ++-- test/index.ts | 10 ++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index 3a06239..93483a7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -15,10 +15,10 @@ export class DetectLanguageAPI { return response.data.detections; } - async detectCode(text: string): Promise { + async detectCode(text: string): Promise { const results = await this.detect(text); - return results[0].language; + return results[0]?.language || null; } async detectBatch(texts: string[]): Promise { diff --git a/test/index.ts b/test/index.ts index 074b3a6..8b69a34 100644 --- a/test/index.ts +++ b/test/index.ts @@ -24,6 +24,12 @@ describe('detectCode', function () { expect(result).to.eq('lt') }); + + it('handles not detected', async () => { + const result = await detectLanguage.detectCode('?'); + + expect(result).to.be.null; + }); }); describe('detectBatch', function () { @@ -39,8 +45,8 @@ describe('languages', function () { it('fetches languages', async () => { const result = await detectLanguage.languages(); - expect(result[0].code).to.be.string; - expect(result[0].name).to.be.string; + expect(result[0].code).to.be.a('string'); + expect(result[0].name).to.be.a('string'); }); }); From f9a936054d515d70882f25e53945b98b865ccc5f Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 22:01:01 +0300 Subject: [PATCH 07/22] Adjust types --- .eslintrc | 3 ++- src/client.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.eslintrc b/.eslintrc index ece2868..adc50da 100644 --- a/.eslintrc +++ b/.eslintrc @@ -10,6 +10,7 @@ "plugin:@typescript-eslint/recommended" ], "rules": { - "@typescript-eslint/no-var-requires": "off" + "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/no-explicit-any": "off" } } diff --git a/src/client.ts b/src/client.ts index 54e1c27..507e55b 100644 --- a/src/client.ts +++ b/src/client.ts @@ -32,7 +32,7 @@ export class Client { return response.data; } - async post(path: string, data: any): Promise { + async post(path: string, data: unknown): Promise { const response = await this.connection.post(path, data); return response.data; From 6fff3e37ea6aff24b1a7fe65b48f4ae88e702bc8 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 22:01:58 +0300 Subject: [PATCH 08/22] Remove old files --- api/detect.js | 64 ------------------------------------------------ api/index.js | 29 ---------------------- api/languages.js | 55 ----------------------------------------- api/status.js | 55 ----------------------------------------- 4 files changed, 203 deletions(-) delete mode 100644 api/detect.js delete mode 100644 api/index.js delete mode 100644 api/languages.js delete mode 100644 api/status.js diff --git a/api/detect.js b/api/detect.js deleted file mode 100644 index 4d7ac22..0000000 --- a/api/detect.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -var utils = require('../lib/utils'); -var APIRequest = require('../lib/apirequest'); - -var API = {}; - -/** - * Detect Language from String or Array of Strings - * - * @param {object} params - Parameters for request - * @param {callback} callback - The callback that handles the response. - * @return {object} Result - */ -API.detect = function (params, callback) { - - var options = utils.extend({}, this.options, { - service: 'detect', - method: 'POST' - } - ) - - var requestParams = { - options: options, - params: { - json: { q: params } - } - }; - - var apiRequest = APIRequest(requestParams, function(error, result) { - if(!error) { - if(result.body && result.body.data && result.body.data.detections) { - result = result.body.data.detections; - } - else { - error = result; - } - } - callback(error, result); - }); - return apiRequest; -} - -/** - * Exports the APIs - * @type {Object} - */ -module.exports = API; diff --git a/api/index.js b/api/index.js deleted file mode 100644 index dd5c827..0000000 --- a/api/index.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -var API = {}; - -API.detect = require('./detect').detect; -API.languages = require('./languages').languages; -API.status = require('./status').status; - -/** - * Exports the APIs - * @type {Object} - */ -module.exports = API; \ No newline at end of file diff --git a/api/languages.js b/api/languages.js deleted file mode 100644 index 2a3804a..0000000 --- a/api/languages.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -var utils = require('../lib/utils'); - -var API = {}; - -/** - * Gets all languages - * - * @param {callback} callback - The callback that handles the response. - * @return {object} Result - */ -API.languages = function(callback) { - - var options = utils.extend({}, this.options, { - service: 'languages', - method: 'GET' - } - ) - - var params = { - options: options - } - - var APIRequest = require('../lib/apirequest'); - var apiRequest = APIRequest(params, function(error, result) { - if(!error) { - result = result.body; - } - callback(error, result); - }); - return apiRequest; -} - -/** - * Exports the APIs - * @type {Object} - */ -module.exports = API; diff --git a/api/status.js b/api/status.js deleted file mode 100644 index 4003758..0000000 --- a/api/status.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -var utils = require('../lib/utils'); - -var API = {}; - -/** - * Get Status - * - * @param {callback} callback - The callback that handles the response. - * @return {object} Result - */ -API.status = function (callback) { - - var options = utils.extend({}, this.options, { - service: 'user/status', - method: 'GET' - } - ); - - var params = { - options: options - } - - var APIRequest = require('../lib/apirequest'); - var apiRequest = APIRequest(params, function (error, result) { - if (!error) { - result = result.body; - } - callback(error, result); - }); - return apiRequest; -} - -/** - * Exports the APIs - * @type {Object} - */ -module.exports = API; From 205b5057fa50c6a742b32e1e8883d4867edfb945 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Thu, 3 Sep 2020 22:03:57 +0300 Subject: [PATCH 09/22] Remove old files --- index.js | 66 -------------------------------------------------------- 1 file changed, 66 deletions(-) delete mode 100644 index.js diff --git a/index.js b/index.js deleted file mode 100644 index 680ac48..0000000 --- a/index.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright 2015 Peter Andreas Moelgaard. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -'use strict'; - -var utils = require('./lib/utils'); - -/** - * A module for interacting with DetectLanguage API - * @module DetectLanguage - */ - -/** - * DetectLanguage constructor. - * @param {object} options Options to be passed in - * @constructor - */ -function API(options) { - - this.options = utils.extend( - { - host: 'ws.detectlanguage.com', - version: '0.2', - ssl: true - }, - options - ); - - /** - * Load the apis from apis directory - * This file holds all version information - * @private - */ - var apis = require('./api'); - this.addAPIs(apis); -} - -/** - * Add API endpoints to object - * - * @param {Array} api Api to be added - * @private - */ -API.prototype.addAPIs = function(apis) { - for (var apiName in apis) { - this[apiName] = apis[apiName].bind(this); - } -}; - -/** - * Exports DetectLanguage. - */ -module.exports = API; From 7fb4ef794c4c74d4366ca73d28d4aded49b15274 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Sun, 6 Sep 2020 15:15:46 +0300 Subject: [PATCH 10/22] Handle errors --- package.json | 3 ++- src/client.ts | 38 ++++++++++++++++++++++++++------------ src/index.ts | 6 +++++- test/index.ts | 13 +++++++++++-- tsconfig.json | 7 +++---- 5 files changed, 47 insertions(+), 20 deletions(-) diff --git a/package.json b/package.json index 0542b4d..461a040 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "2.0.0", "description": "Detect Language API Node.js Client", "main": "./lib/index.js", - "types": "./types/index.d.ts", + "types": "./lib/index.d.ts", "scripts": { "clean": "rimraf lib .nyc_output node_modules/.cache coverage", "test": "yarn lint && yarn mocha", @@ -41,6 +41,7 @@ }, "devDependencies": { "@types/chai": "^4.2.12", + "@types/chai-as-promised": "^7.1.3", "@types/mocha": "^8.0.3", "@typescript-eslint/eslint-plugin": "^3.10.1", "@typescript-eslint/parser": "^3.10.1", diff --git a/src/client.ts b/src/client.ts index 507e55b..a9ac5b7 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,14 +1,15 @@ import { Config } from './config'; -import axios, { AxiosInstance } from 'axios'; +import { DetectLanguageError } from './index'; +import axios, { AxiosInstance, AxiosError } from 'axios'; const { version } = require('../package.json'); const USER_AGENT = 'detectlanguage-node/' + version; export class Client { - public connection: AxiosInstance; + private connection: AxiosInstance; constructor(apiKey: string, config: Config) { - const timeout = config.timeout || 60; + const timeout = (config.timeout || 60) * 1000; const protocol = config.protocol || 'https'; const host = config.host || 'ws.detectlanguage.com'; const apiVersion = config.apiVersion || '0.2'; @@ -19,22 +20,35 @@ export class Client { 'Authorization': 'Bearer ' + apiKey, } - this.connection = axios.create({ - baseURL, - headers, - timeout: timeout * 1000, - }) + this.connection = axios.create({ baseURL, headers, timeout }); } async get(path: string): Promise { - const response = await this.connection.get(path) + try { + const response = await this.connection.get(path) - return response.data; + return response.data; + } catch(e) { + this.handleError(e); + } } async post(path: string, data: unknown): Promise { - const response = await this.connection.post(path, data); + try { + const response = await this.connection.post(path, data); + + return response.data; + } catch(e) { + this.handleError(e); + } + } + + private handleError(error: AxiosError) { + const message = error?.response?.data?.error?.message || error.message; + const apiError = new DetectLanguageError(message); + + apiError.stack = error.stack; - return response.data; + throw(apiError); } } diff --git a/src/index.ts b/src/index.ts index 93483a7..886b2ae 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,6 +2,8 @@ import { Config } from './config'; import { Client } from './client'; import { DetectionResult, Language, UserStatus } from './types'; +export class DetectLanguageError extends Error {} + export class DetectLanguageAPI { client: Client; @@ -36,6 +38,8 @@ export class DetectLanguageAPI { } } -export default (apiKey: string, config: Config = {}): DetectLanguageAPI => { +const DetectLanguageAPIConstructor = (apiKey: string, config: Config = {}): DetectLanguageAPI => { return new DetectLanguageAPI(apiKey, config); } + +export default DetectLanguageAPIConstructor; diff --git a/test/index.ts b/test/index.ts index 8b69a34..177e0e8 100644 --- a/test/index.ts +++ b/test/index.ts @@ -1,5 +1,8 @@ -import DetectLanguage, { DetectLanguageAPI } from '../src/index'; -import { expect } from 'chai'; +import DetectLanguage, { DetectLanguageAPI, DetectLanguageError } from '../src/index'; +import chai, { expect } from 'chai'; +import chaiAsPromised from 'chai-as-promised'; + +chai.use(chaiAsPromised); const API_KEY = process.env.DETECTLANGUAGE_API_KEY || ''; let detectLanguage: DetectLanguageAPI; @@ -16,6 +19,12 @@ describe('detect', function () { expect(result[0].isReliable).to.eq(true) expect(result[0].confidence).to.be.a('number') }); + + it('detects language', async () => { + detectLanguage = DetectLanguage('invalid'); + + await expect(detectLanguage.detect('hello')).to.be.rejected; + }); }); describe('detectCode', function () { diff --git a/tsconfig.json b/tsconfig.json index 90cf7bd..ed5204b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,16 +1,15 @@ { "compilerOptions": { "outDir": "./lib", - "target": "ES5", + "target": "es5", "module": "commonjs", "strict": true, "declaration": true, "resolveJsonModule": true, "esModuleInterop": true, "baseUrl": "./src/", + "moduleResolution": "node", "types": ["node", "mocha"] }, - "include": [ - "src/**/*", - ] + "include": ["src"] } From a60896e7316f1ba8f01c8b42e6d5ba49a8dd51de Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Sun, 6 Sep 2020 15:43:59 +0300 Subject: [PATCH 11/22] Adjust structure --- src/client.ts | 2 +- src/config.ts | 6 ------ src/index.ts | 5 +++-- src/types.ts | 7 +++++++ test/index.ts | 2 +- 5 files changed, 12 insertions(+), 10 deletions(-) delete mode 100644 src/config.ts diff --git a/src/client.ts b/src/client.ts index a9ac5b7..89e1085 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,4 +1,4 @@ -import { Config } from './config'; +import { Config } from './types'; import { DetectLanguageError } from './index'; import axios, { AxiosInstance, AxiosError } from 'axios'; diff --git a/src/config.ts b/src/config.ts deleted file mode 100644 index 25f23f1..0000000 --- a/src/config.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface Config { - timeout?: number, - protocol?: string, - host?: string, - apiVersion?: string, -} diff --git a/src/index.ts b/src/index.ts index 886b2ae..e6239ed 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ -import { Config } from './config'; import { Client } from './client'; -import { DetectionResult, Language, UserStatus } from './types'; +import { Config, DetectionResult, Language, UserStatus } from './types'; + +export * from './types'; export class DetectLanguageError extends Error {} diff --git a/src/types.ts b/src/types.ts index b8280c4..c1765a6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,10 @@ +export interface Config { + timeout?: number, + protocol?: string, + host?: string, + apiVersion?: string, +} + export interface DetectionResult { language: string, isReliable: boolean, diff --git a/test/index.ts b/test/index.ts index 177e0e8..223cf22 100644 --- a/test/index.ts +++ b/test/index.ts @@ -1,4 +1,4 @@ -import DetectLanguage, { DetectLanguageAPI, DetectLanguageError } from '../src/index'; +import DetectLanguage, { DetectLanguageAPI } from '../src/index'; import chai, { expect } from 'chai'; import chaiAsPromised from 'chai-as-promised'; From 590bf934a16ccabda3b199f61d94034051d65e2d Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Sun, 6 Sep 2020 20:52:08 +0300 Subject: [PATCH 12/22] Switch to babel --- .babelrc | 6 ++ .eslintignore | 1 - .eslintrc | 17 ++--- README.md | 126 ++++++++++++++++++------------------ examples/detect.js | 7 ++ examples/detectBatch.js | 7 ++ examples/detectCode.js | 7 ++ examples/languages.js | 5 ++ examples/userStatus.js | 5 ++ package.json | 30 ++++----- src/client.js | 41 ++++++++++++ src/client.ts | 54 ---------------- src/defaults.js | 9 +++ src/error.js | 15 +++++ src/index.js | 31 +++++++++ src/index.ts | 46 ------------- test/{index.ts => index.js} | 46 +++++++------ tsconfig.json | 15 ----- src/types.ts => types.ts | 0 19 files changed, 236 insertions(+), 232 deletions(-) create mode 100644 .babelrc create mode 100644 examples/detect.js create mode 100644 examples/detectBatch.js create mode 100644 examples/detectCode.js create mode 100644 examples/languages.js create mode 100644 examples/userStatus.js create mode 100644 src/client.js delete mode 100644 src/client.ts create mode 100644 src/defaults.js create mode 100644 src/error.js create mode 100644 src/index.js delete mode 100644 src/index.ts rename test/{index.ts => index.js} (57%) delete mode 100644 tsconfig.json rename src/types.ts => types.ts (100%) diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..1cb1603 --- /dev/null +++ b/.babelrc @@ -0,0 +1,6 @@ +{ + "presets": [ + ["@babel/preset-env", { "targets": { "node": 6 } }], + "minify" + ] +} diff --git a/.eslintignore b/.eslintignore index 437238e..491fc35 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,3 +1,2 @@ node_modules lib -test diff --git a/.eslintrc b/.eslintrc index adc50da..3eecb6f 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,16 +1,7 @@ { - "root": true, - "parser": "@typescript-eslint/parser", - "plugins": [ - "@typescript-eslint" - ], - "extends": [ - "eslint:recommended", - "plugin:@typescript-eslint/eslint-recommended", - "plugin:@typescript-eslint/recommended" - ], - "rules": { - "@typescript-eslint/no-var-requires": "off", - "@typescript-eslint/no-explicit-any": "off" + "parser": "babel-eslint", + "extends": "airbnb/base", + "env": { + "mocha": true } } diff --git a/README.md b/README.md index a761474..72de7b3 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Language Detection API Node.js Client [![npm version](https://badge.fury.io/js/detectlanguage.svg)](https://badge.fury.io/js/detectlanguage) [![Build Status](https://travis-ci.org/detectlanguage/detectlanguage-node.svg?branch=master)](https://travis-ci.org/detectlanguage/detectlanguage-node) -JavaScript wrapper for [Language Detection API](https://detectlanguage.com/). +Node.js wrapper for [Language Detection API](https://detectlanguage.com/). ## Installation @@ -18,11 +18,7 @@ Before using Detect Language API client you have to setup your personal API key. You can get it by signing up at [detectlanguage.com](https://detectlanguage.com) ```javascript -var DetectLanguage = require('detectlanguage'); -var detectLanguage = new DetectLanguage({ - key: '[INSERT YOUR KEY HERE]', - ssl: true|false (defaults to TRUE) -}); +var detectlanguage = require('detectlanguage')('YOUR API KEY'); ``` ## Usage @@ -32,26 +28,23 @@ var detectLanguage = new DetectLanguage({ Takes a text string and returns a list of detections. ```javascript -var text = "I am a Teapot and a Submarine"; -detectLanguage.detect(text, function(error, result) { - console.log(JSON.stringify(result)); +var text = "Hello! How are you?"; + +detectlanguage.detect(text).then(function(result) { + console.log(JSON.stringify(result)); }); ``` #### Response ```javascript -{ - data: { - detections: [ - { - language: "en", - isReliable: true, - confidence: 7.85 - } - ] +[ + { + "language": "en", + "isReliable": true, + "confidence": 18.2 } -} +] ``` ### Batch Detection (recommended) @@ -60,46 +53,51 @@ Takes an array of texts and returns a list of detections. It is much faster than doing request for each text individually. ```javascript -var texts = [ - "I am a Teapot and a Submarine", - "Soy una tetera y un submarino", - "Jeg er en tekande og en ubåd" +var texts = ['šešios žąsys', 'Strč prst skrz krk']; + +detectlanguage.detect(texts).then(function(result) { + console.log(JSON.stringify(result)); +}); +``` + +#### Response + +```javascript +[ + [ + { + "language": "lt", + "isReliable": true, + "confidence": 5.5 + } + ], + [ + { + "language": "cs", + "isReliable": true, + "confidence": 3.645 + }, + ... + ] ] -detectLanguage.detect(texts, function(error, result) { - console.log(JSON.stringify(result)); +``` + +### Language Code Detection + +Returns first detected language code. + +```javascript +var text = "Hello! How are you?"; + +detectlanguage.detectCode(text).then(function(result) { + console.log(JSON.stringify(result)); }); ``` #### Response ```javascript -{ - data: { - detections: [ - [ - { - language: "en", - isReliable: true, - confidence: 7.85 - } - ], - [ - { - language: "es", - isReliable: true, - confidence: 3.75 - } - ], - [ - { - language: "da", - isReliable: true, - confidence: 4.09 - } - ] - ] - } -} +"en" ``` ### Supported Languages @@ -107,8 +105,8 @@ detectLanguage.detect(texts, function(error, result) { Returns the list of supported languages. ```javascript -detectLanguage.languages(function(error, result) { - console.log(JSON.stringify(result)); +detectlanguage.languages().then(function(result) { + console.log(JSON.stringify(result)); }); ``` @@ -116,14 +114,14 @@ detectLanguage.languages(function(error, result) { ```javascript [ - { - code: "ab", - name: "ABKHAZIAN" - }, { code: "aa", name: "AFAR" }, + { + code: "ab", + name: "ABKHAZIAN" + }, { code: "af", name: "AFRIKAANS" @@ -137,8 +135,8 @@ detectLanguage.languages(function(error, result) { Returns information about your account and it's status. ```javascript -detectLanguage.status(function(error, result) { - console.log(JSON.stringify(result)); +detectlanguage.userStatus().then(function(result) { + console.log(JSON.stringify(result)); }); ``` @@ -146,12 +144,12 @@ detectLanguage.status(function(error, result) { ```javascript { - date: "2015-02-21", + date: "2020-01-01", requests: 31, bytes: 429, plan: "FREE", plan_expires: null, - daily_requests_limit: 5000, + daily_requests_limit: 1000, daily_bytes_limit: 1048576, status: "ACTIVE" } @@ -159,8 +157,8 @@ detectLanguage.status(function(error, result) { ## Author -Peter Andreas Moelgaard ([GitHub](https://github.com/pmoelgaard), [Twitter](https://twitter.com/petermoelgaard)) +Laurynas Butkus ([GitHub](https://github.com/laurynas) ## License -Licensed under the Apache License, Version 2.0: [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) +Licensed under the MIT License: [https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT) diff --git a/examples/detect.js b/examples/detect.js new file mode 100644 index 0000000..7076fdf --- /dev/null +++ b/examples/detect.js @@ -0,0 +1,7 @@ +var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); + +var text = "Hello! How are you?"; + +detectlanguage.detect(text).then(function(result) { + console.log(JSON.stringify(result, null, 2)); +}); diff --git a/examples/detectBatch.js b/examples/detectBatch.js new file mode 100644 index 0000000..0e96d04 --- /dev/null +++ b/examples/detectBatch.js @@ -0,0 +1,7 @@ +var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); + +var texts = ['šešios žąsys', 'Strč prst skrz krk']; + +detectlanguage.detect(texts).then(function(result) { + console.log(JSON.stringify(result, null, 2)); +}); diff --git a/examples/detectCode.js b/examples/detectCode.js new file mode 100644 index 0000000..1d08fd1 --- /dev/null +++ b/examples/detectCode.js @@ -0,0 +1,7 @@ +var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); + +var text = "Hello! How are you?"; + +detectlanguage.detectCode(text).then(function(result) { + console.log(JSON.stringify(result)); +}); diff --git a/examples/languages.js b/examples/languages.js new file mode 100644 index 0000000..8737d26 --- /dev/null +++ b/examples/languages.js @@ -0,0 +1,5 @@ +var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); + +detectlanguage.languages().then(function(result) { + console.log(JSON.stringify(result, null, 2)); +}); diff --git a/examples/userStatus.js b/examples/userStatus.js new file mode 100644 index 0000000..a503281 --- /dev/null +++ b/examples/userStatus.js @@ -0,0 +1,5 @@ +var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); + +detectlanguage.userStatus().then(function(result) { + console.log(JSON.stringify(result, null, 2)); +}); diff --git a/package.json b/package.json index 461a040..636326f 100644 --- a/package.json +++ b/package.json @@ -3,13 +3,13 @@ "version": "2.0.0", "description": "Detect Language API Node.js Client", "main": "./lib/index.js", - "types": "./lib/index.d.ts", + "types": "./types.ts", "scripts": { "clean": "rimraf lib .nyc_output node_modules/.cache coverage", - "test": "yarn lint && yarn mocha", - "mocha": "nyc mocha --require ts-node/register test/**/*.ts", - "lint": "eslint src", - "build": "yarn tsc" + "test": "yarn lint && yarn mocha --require @babel/register", + "mocha": "nyc mocha", + "lint": "eslint src test", + "build": "babel src --out-dir lib" }, "files": [ "lib", @@ -36,22 +36,22 @@ }, "homepage": "https://github.com/detectlanguage/detectlanguage-node", "dependencies": { - "@types/node": "^14.6.2", "axios": "^0.20.0" }, "devDependencies": { - "@types/chai": "^4.2.12", - "@types/chai-as-promised": "^7.1.3", - "@types/mocha": "^8.0.3", - "@typescript-eslint/eslint-plugin": "^3.10.1", - "@typescript-eslint/parser": "^3.10.1", + "@babel/cli": "^7.11.6", + "@babel/core": "^7.11.6", + "@babel/preset-env": "^7.11.5", + "@babel/register": "^7.11.5", + "babel-eslint": "^10.1.0", + "babel-preset-minify": "^0.5.1", "chai": "^4.2.0", "chai-as-promised": "^7.1.1", - "eslint": "^7.7.0", + "eslint": "^7.8.1", + "eslint-config-airbnb": "^18.2.0", + "eslint-plugin-import": "^2.22.0", "mocha": "^8.1.3", "nyc": "^15.1.0", - "rimraf": "^3.0.2", - "ts-node": "^9.0.0", - "typescript": "^4.0.2" + "rimraf": "^3.0.2" } } diff --git a/src/client.js b/src/client.js new file mode 100644 index 0000000..adbb80f --- /dev/null +++ b/src/client.js @@ -0,0 +1,41 @@ +import axios from 'axios'; +import * as defaults from './defaults'; +import { handleError } from './error'; + +export default class Client { + constructor(apiKey, options) { + const config = { ...defaults, ...options }; + const baseURL = `${config.protocol}://${config.host}/${config.apiVersion}/`; + + const headers = { + 'User-Agent': config.userAgent, + Authorization: `Bearer ${apiKey}`, + }; + + this.connection = axios.create({ + headers, + baseURL, + timeout: config.timeout * 1000, + }); + } + + async get(path) { + try { + const response = await this.connection.get(path); + + return response.data; + } catch (e) { + return handleError(e); + } + } + + async post(path, data) { + try { + const response = await this.connection.post(path, data); + + return response.data; + } catch (e) { + return handleError(e); + } + } +} diff --git a/src/client.ts b/src/client.ts deleted file mode 100644 index 89e1085..0000000 --- a/src/client.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { Config } from './types'; -import { DetectLanguageError } from './index'; -import axios, { AxiosInstance, AxiosError } from 'axios'; - -const { version } = require('../package.json'); -const USER_AGENT = 'detectlanguage-node/' + version; - -export class Client { - private connection: AxiosInstance; - - constructor(apiKey: string, config: Config) { - const timeout = (config.timeout || 60) * 1000; - const protocol = config.protocol || 'https'; - const host = config.host || 'ws.detectlanguage.com'; - const apiVersion = config.apiVersion || '0.2'; - const baseURL = protocol + '://' + host + '/' + apiVersion + '/'; - - const headers = { - 'User-Agent': USER_AGENT, - 'Authorization': 'Bearer ' + apiKey, - } - - this.connection = axios.create({ baseURL, headers, timeout }); - } - - async get(path: string): Promise { - try { - const response = await this.connection.get(path) - - return response.data; - } catch(e) { - this.handleError(e); - } - } - - async post(path: string, data: unknown): Promise { - try { - const response = await this.connection.post(path, data); - - return response.data; - } catch(e) { - this.handleError(e); - } - } - - private handleError(error: AxiosError) { - const message = error?.response?.data?.error?.message || error.message; - const apiError = new DetectLanguageError(message); - - apiError.stack = error.stack; - - throw(apiError); - } -} diff --git a/src/defaults.js b/src/defaults.js new file mode 100644 index 0000000..975ceaf --- /dev/null +++ b/src/defaults.js @@ -0,0 +1,9 @@ +const { version } = require('../package.json'); + +module.exports = { + timeout: 60, + protocol: 'https', + host: 'ws.detectlanguage.com', + apiVersion: '0.2', + userAgent: `detectlanguage-node/${version}`, +}; diff --git a/src/error.js b/src/error.js new file mode 100644 index 0000000..027cfb2 --- /dev/null +++ b/src/error.js @@ -0,0 +1,15 @@ +class DetectLanguageError extends Error {} + +function handleError(error) { + const message = error?.response?.data?.error?.message || error.message; + const apiError = new DetectLanguageError(message); + + apiError.stack = error.stack; + + throw apiError; +} + +export { + DetectLanguageError, + handleError, +}; diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..e78a21c --- /dev/null +++ b/src/index.js @@ -0,0 +1,31 @@ +import Client from './client'; + +class API { + constructor(apiKey, options = {}) { + this.client = new Client(apiKey, options); + } + + async detect(text) { + const response = await this.client.post('detect', { q: text }); + + return response.data.detections; + } + + async detectCode(text) { + const results = await this.detect(text); + + return results[0]?.language || null; + } + + async languages() { + return this.client.get('languages'); + } + + async userStatus() { + return this.client.get('user/status'); + } +} + +const init = (apiKey, options = {}) => new API(apiKey, options); + +module.exports = init; diff --git a/src/index.ts b/src/index.ts deleted file mode 100644 index e6239ed..0000000 --- a/src/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { Client } from './client'; -import { Config, DetectionResult, Language, UserStatus } from './types'; - -export * from './types'; - -export class DetectLanguageError extends Error {} - -export class DetectLanguageAPI { - client: Client; - - constructor(apiKey: string, config: Config = {}) { - this.client = new Client(apiKey, config); - } - - async detect(text: string): Promise { - const response = await this.client.post('detect', { q: text }) - - return response.data.detections; - } - - async detectCode(text: string): Promise { - const results = await this.detect(text); - - return results[0]?.language || null; - } - - async detectBatch(texts: string[]): Promise { - const response = await this.client.post('detect', { q: texts }) - - return response.data.detections; - } - - async languages(): Promise { - return this.client.get('languages'); - } - - async userStatus(): Promise { - return this.client.get('user/status'); - } -} - -const DetectLanguageAPIConstructor = (apiKey: string, config: Config = {}): DetectLanguageAPI => { - return new DetectLanguageAPI(apiKey, config); -} - -export default DetectLanguageAPIConstructor; diff --git a/test/index.ts b/test/index.js similarity index 57% rename from test/index.ts rename to test/index.js index 223cf22..312fd87 100644 --- a/test/index.ts +++ b/test/index.js @@ -1,56 +1,54 @@ -import DetectLanguage, { DetectLanguageAPI } from '../src/index'; import chai, { expect } from 'chai'; import chaiAsPromised from 'chai-as-promised'; +import DetectLanguage from '../src'; + chai.use(chaiAsPromised); -const API_KEY = process.env.DETECTLANGUAGE_API_KEY || ''; -let detectLanguage: DetectLanguageAPI; +let detectLanguage; beforeEach(() => { - detectLanguage = DetectLanguage(API_KEY); -}) + detectLanguage = DetectLanguage(process.env.DETECTLANGUAGE_API_KEY || ''); +}); -describe('detect', function () { +describe('detect', () => { it('detects language', async () => { const result = await detectLanguage.detect('labas rytas'); - expect(result[0].language).to.eq('lt') - expect(result[0].isReliable).to.eq(true) - expect(result[0].confidence).to.be.a('number') + expect(result[0].language).to.eq('lt'); + expect(result[0].isReliable).to.eq(true); + expect(result[0].confidence).to.be.a('number'); }); it('detects language', async () => { detectLanguage = DetectLanguage('invalid'); - await expect(detectLanguage.detect('hello')).to.be.rejected; + await expect(detectLanguage.detect('hello')).to.be.rejectedWith('Invalid API key'); + }); + + it('works with batch', async () => { + const result = await detectLanguage.detect(['šešios žąsys', 'Strč prst skrz krk']); + + expect(result[0][0].language).to.eq('lt'); + expect(result[1][0].language).to.eq('cs'); }); }); -describe('detectCode', function () { +describe('detectCode', () => { it('detects language code', async () => { const result = await detectLanguage.detectCode('vidur prūdo bliūdas plūdur'); - expect(result).to.eq('lt') + expect(result).to.eq('lt'); }); it('handles not detected', async () => { const result = await detectLanguage.detectCode('?'); - expect(result).to.be.null; - }); -}); - -describe('detectBatch', function () { - it('detects languages', async () => { - const result = await detectLanguage.detectBatch(['šešios žąsys', 'Strč prst skrz krk']); - - expect(result[0][0].language).to.eq('lt'); - expect(result[1][0].language).to.eq('cs'); + expect(result).to.be.a('null'); }); }); -describe('languages', function () { +describe('languages', () => { it('fetches languages', async () => { const result = await detectLanguage.languages(); @@ -59,7 +57,7 @@ describe('languages', function () { }); }); -describe('userStatus', function () { +describe('userStatus', () => { it('fetches user status', async () => { const result = await detectLanguage.userStatus(); diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index ed5204b..0000000 --- a/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "outDir": "./lib", - "target": "es5", - "module": "commonjs", - "strict": true, - "declaration": true, - "resolveJsonModule": true, - "esModuleInterop": true, - "baseUrl": "./src/", - "moduleResolution": "node", - "types": ["node", "mocha"] - }, - "include": ["src"] -} diff --git a/src/types.ts b/types.ts similarity index 100% rename from src/types.ts rename to types.ts From bb3ead3b0cc51380a8f8b6b9f096063104186aa8 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Sun, 6 Sep 2020 20:55:40 +0300 Subject: [PATCH 13/22] Adjust baseurl setting --- src/client.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/client.js b/src/client.js index adbb80f..197912f 100644 --- a/src/client.js +++ b/src/client.js @@ -5,7 +5,6 @@ import { handleError } from './error'; export default class Client { constructor(apiKey, options) { const config = { ...defaults, ...options }; - const baseURL = `${config.protocol}://${config.host}/${config.apiVersion}/`; const headers = { 'User-Agent': config.userAgent, @@ -14,7 +13,7 @@ export default class Client { this.connection = axios.create({ headers, - baseURL, + baseURL: `${config.protocol}://${config.host}/${config.apiVersion}/`, timeout: config.timeout * 1000, }); } From 6da8a0784c3014c5edf468f7f776ae03d84d3c71 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Mon, 14 Sep 2020 21:39:29 +0300 Subject: [PATCH 14/22] Update types --- package.json | 2 +- src/index.d.ts | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ types.ts | 28 --------------------------- 3 files changed, 52 insertions(+), 29 deletions(-) create mode 100644 src/index.d.ts delete mode 100644 types.ts diff --git a/package.json b/package.json index 636326f..510eabe 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "2.0.0", "description": "Detect Language API Node.js Client", "main": "./lib/index.js", - "types": "./types.ts", + "types": "./src/index.d.ts", "scripts": { "clean": "rimraf lib .nyc_output node_modules/.cache coverage", "test": "yarn lint && yarn mocha --require @babel/register", diff --git a/src/index.d.ts b/src/index.d.ts new file mode 100644 index 0000000..20ee4e0 --- /dev/null +++ b/src/index.d.ts @@ -0,0 +1,51 @@ +import Client from "./client"; + +export interface Options { + timeout?: number, + protocol?: string, + host?: string, + apiVersion?: string, +} + +export interface DetectionResult { + language: string, + isReliable: boolean, + confidence: number, +} + +export interface Language { + code: string, + name: string, +} + +export interface UserStatus { + status: string, + date: string, + requests: number, + bytes: number, + plan: string, + plan_expires?: string, + daily_rquests_limit: number, + daily_bytes_limit: number, +} + +export interface Client { + get(path: string): Promise; + post(path: string, data: any): Promise; +} + +export interface APIInstance { + client: Client; + detect(text: (string | string[])): (Promise | Promise); + detectCode(text: string): (Promise | Promise); + languages(): Promise; + userStatus(): Promise; +} + +export interface APIStatic { + (apiKey: string, options?: Options): APIInstance; +} + +declare const API: APIStatic; + +export default API; diff --git a/types.ts b/types.ts deleted file mode 100644 index c1765a6..0000000 --- a/types.ts +++ /dev/null @@ -1,28 +0,0 @@ -export interface Config { - timeout?: number, - protocol?: string, - host?: string, - apiVersion?: string, -} - -export interface DetectionResult { - language: string, - isReliable: boolean, - confidence: number, -} - -export interface Language { - code: string, - name: string, -} - -export interface UserStatus { - status: string, - date: string, - requests: number, - bytes: number, - plan: string, - plan_expires?: string, - daily_rquests_limit: number, - daily_bytes_limit: number, -} From eb1e2428de81e2cf799d9a1838da3e6df1a20c5c Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Mon, 14 Sep 2020 23:51:20 +0300 Subject: [PATCH 15/22] Adjust types --- src/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/index.d.ts b/src/index.d.ts index 20ee4e0..7ae0691 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -36,8 +36,9 @@ export interface Client { export interface APIInstance { client: Client; - detect(text: (string | string[])): (Promise | Promise); - detectCode(text: string): (Promise | Promise); + detect(text: string): Promise; + detect(text: string[]): Promise; + detectCode(text: string): Promise | Promise; languages(): Promise; userStatus(): Promise; } From 908bc159a520aa219d0adb1e32b649199b6afeab Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Mon, 14 Sep 2020 23:52:53 +0300 Subject: [PATCH 16/22] Adjust types --- src/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/index.d.ts b/src/index.d.ts index 7ae0691..76248f7 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -1,5 +1,3 @@ -import Client from "./client"; - export interface Options { timeout?: number, protocol?: string, From 9a71bdc695d4730700c18b924ca5ab80bb8d7040 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Mon, 14 Sep 2020 23:57:07 +0300 Subject: [PATCH 17/22] Adjust types --- src/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/index.d.ts b/src/index.d.ts index 76248f7..3ca3725 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -36,7 +36,7 @@ export interface APIInstance { client: Client; detect(text: string): Promise; detect(text: string[]): Promise; - detectCode(text: string): Promise | Promise; + detectCode(text: string): Promise; languages(): Promise; userStatus(): Promise; } From e4aacdfc60265c1a83d0dd33ca04a5c7acb834c1 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Tue, 15 Sep 2020 00:19:00 +0300 Subject: [PATCH 18/22] Adjust types --- README.md | 4 +++- examples/detect.js | 4 +++- examples/detectBatch.js | 4 +++- examples/detectCode.js | 4 +++- examples/languages.js | 4 +++- examples/userStatus.js | 4 +++- src/index.d.ts | 17 +++++------------ src/index.js | 4 +--- test/index.js | 4 ++-- 9 files changed, 26 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 72de7b3..5e9967e 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,9 @@ Before using Detect Language API client you have to setup your personal API key. You can get it by signing up at [detectlanguage.com](https://detectlanguage.com) ```javascript -var detectlanguage = require('detectlanguage')('YOUR API KEY'); +var DetectLanguage = require('detectlanguage'); + +var detectlanguage = new DetectLanguage('YOUR API KEY'); ``` ## Usage diff --git a/examples/detect.js b/examples/detect.js index 7076fdf..35ef478 100644 --- a/examples/detect.js +++ b/examples/detect.js @@ -1,4 +1,6 @@ -var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); +var DetectLanguage = require('../lib/'); + +var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY); var text = "Hello! How are you?"; diff --git a/examples/detectBatch.js b/examples/detectBatch.js index 0e96d04..e75a845 100644 --- a/examples/detectBatch.js +++ b/examples/detectBatch.js @@ -1,4 +1,6 @@ -var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); +var DetectLanguage = require('../lib/'); + +var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY); var texts = ['šešios žąsys', 'Strč prst skrz krk']; diff --git a/examples/detectCode.js b/examples/detectCode.js index 1d08fd1..6548f17 100644 --- a/examples/detectCode.js +++ b/examples/detectCode.js @@ -1,4 +1,6 @@ -var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); +var DetectLanguage = require('../lib/'); + +var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY); var text = "Hello! How are you?"; diff --git a/examples/languages.js b/examples/languages.js index 8737d26..219a632 100644 --- a/examples/languages.js +++ b/examples/languages.js @@ -1,4 +1,6 @@ -var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); +var DetectLanguage = require('../lib/'); + +var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY); detectlanguage.languages().then(function(result) { console.log(JSON.stringify(result, null, 2)); diff --git a/examples/userStatus.js b/examples/userStatus.js index a503281..fbd6abb 100644 --- a/examples/userStatus.js +++ b/examples/userStatus.js @@ -1,4 +1,6 @@ -var detectlanguage = require('../lib')(process.env.DETECTLANGUAGE_API_KEY); +var DetectLanguage = require('../lib/'); + +var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY); detectlanguage.userStatus().then(function(result) { console.log(JSON.stringify(result, null, 2)); diff --git a/src/index.d.ts b/src/index.d.ts index 3ca3725..e6231d5 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -28,23 +28,16 @@ export interface UserStatus { } export interface Client { - get(path: string): Promise; - post(path: string, data: any): Promise; + async get(path: string): any; + async post(path: string, data: any): any; } -export interface APIInstance { +export default class DetectLanguage { client: Client; - detect(text: string): Promise; + constructor (apiKey: string, options?: Options); + detect(text: string): Promise detect(text: string[]): Promise; detectCode(text: string): Promise; languages(): Promise; userStatus(): Promise; } - -export interface APIStatic { - (apiKey: string, options?: Options): APIInstance; -} - -declare const API: APIStatic; - -export default API; diff --git a/src/index.js b/src/index.js index e78a21c..8dc3d2a 100644 --- a/src/index.js +++ b/src/index.js @@ -26,6 +26,4 @@ class API { } } -const init = (apiKey, options = {}) => new API(apiKey, options); - -module.exports = init; +module.exports = API; diff --git a/test/index.js b/test/index.js index 312fd87..6286d25 100644 --- a/test/index.js +++ b/test/index.js @@ -8,7 +8,7 @@ chai.use(chaiAsPromised); let detectLanguage; beforeEach(() => { - detectLanguage = DetectLanguage(process.env.DETECTLANGUAGE_API_KEY || ''); + detectLanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY || ''); }); describe('detect', () => { @@ -21,7 +21,7 @@ describe('detect', () => { }); it('detects language', async () => { - detectLanguage = DetectLanguage('invalid'); + detectLanguage = new DetectLanguage('invalid'); await expect(detectLanguage.detect('hello')).to.be.rejectedWith('Invalid API key'); }); From 5ff25194ab1d659a348dc6c26b9ac9f871364862 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Wed, 16 Sep 2020 18:25:36 +0300 Subject: [PATCH 19/22] Adjust types --- src/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/index.d.ts b/src/index.d.ts index e6231d5..a1df067 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -28,8 +28,8 @@ export interface UserStatus { } export interface Client { - async get(path: string): any; - async post(path: string, data: any): any; + get(path: string): Promise; + post(path: string, data: any): Promise; } export default class DetectLanguage { From 686ee3033ef81d84e553db24f0ed1231cd96d0ba Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Wed, 16 Sep 2020 18:41:21 +0300 Subject: [PATCH 20/22] Separate travis stages --- .travis.yml | 37 ++++++++++++++++++++++++------------- package.json | 2 +- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9fdba3c..49373c6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,18 +1,29 @@ language: node_js node_js: -- 14 -- 13 -- 12 -- 11 -- 10 -- 9 -- 8 -- 7 -- 6 -- 5 -- 4 -script: -- yarn test + - 14 + - 13 + - 12 + - 11 + - 10 + - 9 + - 8 + - 7 + - 6 + - 5 + - 4 + +stages: + - lint + - test + +jobs: + include: + - stage: lint + script: yarn lint + node_js: 14 + + - stage: test + script: yarn test env: global: secure: c9C48dtqsLNKkf/JPzp1B+M0oIWWt4k0Y1Mf5dl++Nt2RheIVh78s91RhwMYd8/WXp7/mCplkhS/hJoRAvSO39GLn4xHAInu5UuBl9KwvnojA4oo/5WW7I2E4ZNzETsjqAnriF80gJfPXumQ9T+toEza2Bbb8Q1jpfEEiXLPWJehMnBMy5D4TfZFXr7HJ7l0P06gUjvmdXyO+3/MPJo73M8CJTGRqFkbcap/CC3qTgPbZJ4NJ7N7NheJ+Fi3bv7vTtw+hwLNbV7BC+bw0KAUYkMn6AgS/FHfgv9YIkMOksn6qmBwjfIqbsRYD6Rp38Q6TCSpwIdHlnNj758j/zKsGpB7aoYKF74JXgS/fthtkUGOaqlHnt9b2Erb3/1pkNSEQ6zROU/Afn36c8KA1Ofgrps4oQhG2UWnxxZ18wi45e7Uvoe4nMxYjRw21LOraHfhljRAEnRBM/OnF+E3t+cx/rk7+ieOsV/6SjDj85D+M6hCJ27+NpdwrIEJ5kntwFsoy26+hw0Whe1HWHht1zOWrCEgs+Fgzb5jJbkJ0gvNE1hFf4oozlYRBFbTAZo0aEgOV7DAtp9ZddvnmYF7xE60tKi11B2/EsN74nh/9+RX7FW5THlySR7X2hGfQOZUjmsZCsSxxkJ9V4GnIpeNAHyhDMhcJZRQ2b0WySJoLtCpiro= diff --git a/package.json b/package.json index 510eabe..c4e18f9 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "types": "./src/index.d.ts", "scripts": { "clean": "rimraf lib .nyc_output node_modules/.cache coverage", - "test": "yarn lint && yarn mocha --require @babel/register", + "test": "yarn mocha --require @babel/register", "mocha": "nyc mocha", "lint": "eslint src test", "build": "babel src --out-dir lib" From 93a4c8a21e8f38f314d4fca2a7f307b6a67f5500 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Wed, 16 Sep 2020 18:48:25 +0300 Subject: [PATCH 21/22] Revert "Separate travis stages" This reverts commit 686ee3033ef81d84e553db24f0ed1231cd96d0ba. --- .travis.yml | 37 +++++++++++++------------------------ package.json | 2 +- 2 files changed, 14 insertions(+), 25 deletions(-) diff --git a/.travis.yml b/.travis.yml index 49373c6..9fdba3c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,29 +1,18 @@ language: node_js node_js: - - 14 - - 13 - - 12 - - 11 - - 10 - - 9 - - 8 - - 7 - - 6 - - 5 - - 4 - -stages: - - lint - - test - -jobs: - include: - - stage: lint - script: yarn lint - node_js: 14 - - - stage: test - script: yarn test +- 14 +- 13 +- 12 +- 11 +- 10 +- 9 +- 8 +- 7 +- 6 +- 5 +- 4 +script: +- yarn test env: global: secure: c9C48dtqsLNKkf/JPzp1B+M0oIWWt4k0Y1Mf5dl++Nt2RheIVh78s91RhwMYd8/WXp7/mCplkhS/hJoRAvSO39GLn4xHAInu5UuBl9KwvnojA4oo/5WW7I2E4ZNzETsjqAnriF80gJfPXumQ9T+toEza2Bbb8Q1jpfEEiXLPWJehMnBMy5D4TfZFXr7HJ7l0P06gUjvmdXyO+3/MPJo73M8CJTGRqFkbcap/CC3qTgPbZJ4NJ7N7NheJ+Fi3bv7vTtw+hwLNbV7BC+bw0KAUYkMn6AgS/FHfgv9YIkMOksn6qmBwjfIqbsRYD6Rp38Q6TCSpwIdHlnNj758j/zKsGpB7aoYKF74JXgS/fthtkUGOaqlHnt9b2Erb3/1pkNSEQ6zROU/Afn36c8KA1Ofgrps4oQhG2UWnxxZ18wi45e7Uvoe4nMxYjRw21LOraHfhljRAEnRBM/OnF+E3t+cx/rk7+ieOsV/6SjDj85D+M6hCJ27+NpdwrIEJ5kntwFsoy26+hw0Whe1HWHht1zOWrCEgs+Fgzb5jJbkJ0gvNE1hFf4oozlYRBFbTAZo0aEgOV7DAtp9ZddvnmYF7xE60tKi11B2/EsN74nh/9+RX7FW5THlySR7X2hGfQOZUjmsZCsSxxkJ9V4GnIpeNAHyhDMhcJZRQ2b0WySJoLtCpiro= diff --git a/package.json b/package.json index c4e18f9..510eabe 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "types": "./src/index.d.ts", "scripts": { "clean": "rimraf lib .nyc_output node_modules/.cache coverage", - "test": "yarn mocha --require @babel/register", + "test": "yarn lint && yarn mocha --require @babel/register", "mocha": "nyc mocha", "lint": "eslint src test", "build": "babel src --out-dir lib" From 3852f35db4a6ea847446a958f20926e7961dc001 Mon Sep 17 00:00:00 2001 From: Laurynas Butkus Date: Wed, 16 Sep 2020 18:49:21 +0300 Subject: [PATCH 22/22] Remove old node versions from travis --- .travis.yml | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9fdba3c..60da163 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,18 +1,12 @@ language: node_js node_js: -- 14 -- 13 -- 12 -- 11 -- 10 -- 9 -- 8 -- 7 -- 6 -- 5 -- 4 + - 14 + - 13 + - 12 + - 11 + - 10 script: -- yarn test + - yarn test env: global: secure: c9C48dtqsLNKkf/JPzp1B+M0oIWWt4k0Y1Mf5dl++Nt2RheIVh78s91RhwMYd8/WXp7/mCplkhS/hJoRAvSO39GLn4xHAInu5UuBl9KwvnojA4oo/5WW7I2E4ZNzETsjqAnriF80gJfPXumQ9T+toEza2Bbb8Q1jpfEEiXLPWJehMnBMy5D4TfZFXr7HJ7l0P06gUjvmdXyO+3/MPJo73M8CJTGRqFkbcap/CC3qTgPbZJ4NJ7N7NheJ+Fi3bv7vTtw+hwLNbV7BC+bw0KAUYkMn6AgS/FHfgv9YIkMOksn6qmBwjfIqbsRYD6Rp38Q6TCSpwIdHlnNj758j/zKsGpB7aoYKF74JXgS/fthtkUGOaqlHnt9b2Erb3/1pkNSEQ6zROU/Afn36c8KA1Ofgrps4oQhG2UWnxxZ18wi45e7Uvoe4nMxYjRw21LOraHfhljRAEnRBM/OnF+E3t+cx/rk7+ieOsV/6SjDj85D+M6hCJ27+NpdwrIEJ5kntwFsoy26+hw0Whe1HWHht1zOWrCEgs+Fgzb5jJbkJ0gvNE1hFf4oozlYRBFbTAZo0aEgOV7DAtp9ZddvnmYF7xE60tKi11B2/EsN74nh/9+RX7FW5THlySR7X2hGfQOZUjmsZCsSxxkJ9V4GnIpeNAHyhDMhcJZRQ2b0WySJoLtCpiro=