Skip to content

Update to v3 API #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 17 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
"parser": "babel-eslint",
"extends": "airbnb/base",
"env": {
"mocha": true
"mocha": true,
"browser": true
},
"rules": {
"no-unused-expressions": "off"
}
}
6 changes: 3 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ jobs:
strategy:
matrix:
node-version:
- 24
- 22
- 20
- 18
- 14
- 12
- 10
name: Node ${{ matrix.node-version }} sample
steps:
- uses: actions/checkout@v3
Expand Down
19 changes: 19 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Publish package to npmjs
on:
release:
types: [published]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: 'https://registry.npmjs.org'
- run: yarn install
- run: yarn build
- run: yarn publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
DETECTLANGUAGE_API_KEY: ${{ secrets.DETECTLANGUAGE_API_KEY }}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.env.local

# Logs
logs
*.log
Expand Down
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).


## v3.0.0

### Added
- `detectBatch()` for batch detections

### Changed
- Switched to v3 API which uses updated language detection model
- ⚠️ `detect()` result fields are `language` and `score`
- Switched to the native `fetch` API. Minimum supported Node version 8.

### Deprecated
- Calling `detect()` with array argument. Use `detectBatch` instead.
- `userStatus()` - Use `accountStatus()` instead.

### Removed
- `axios` dependency
40 changes: 16 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,18 @@ Detect Language API Node.js Client
[![npm version](https://badge.fury.io/js/detectlanguage.svg)](https://badge.fury.io/js/detectlanguage)
[![Build Status](https://github.com/detectlanguage/detectlanguage-node/actions/workflows/main.yml/badge.svg)](https://github.com/detectlanguage/detectlanguage-node/actions)

Node.js wrapper for the [Detect Language API](https://detectlanguage.com/).
Node.js client for the [Detect Language API](https://detectlanguage.com/).

## Installation

```
npm install detectlanguage [--save]
```

### Upgrading

When upgrading please check [changelog](CHANGELOG.md) for breaking changes.

## Configuration

Before using Detect Language API client you have to setup your personal API key.
Expand Down Expand Up @@ -40,13 +44,7 @@ detectlanguage.detect(text).then(function(result) {
#### Response

```javascript
[
{
"language": "en",
"isReliable": true,
"confidence": 18.2
}
]
[{"language":"en","score":0.9955}]
```

### Batch Detection (recommended)
Expand All @@ -57,7 +55,7 @@ It is much faster than doing request for each text individually.
```javascript
var texts = ['šešios žąsys', 'Strč prst skrz krk'];

detectlanguage.detect(texts).then(function(result) {
detectlanguage.detectBatch(texts).then(function(result) {
console.log(JSON.stringify(result));
});
```
Expand All @@ -69,22 +67,20 @@ detectlanguage.detect(texts).then(function(result) {
[
{
"language": "lt",
"isReliable": true,
"confidence": 5.5
"score": 0.8696
}
],
[
{
"language": "cs",
"isReliable": true,
"confidence": 3.645
"score": 0.3653
},
...
]
]
```

### Language Code Detection
### Language Code Detection

Returns first detected language code.

Expand Down Expand Up @@ -117,27 +113,23 @@ detectlanguage.languages().then(function(result) {
```javascript
[
{
code: "aa",
name: "AFAR"
"code": "aa",
"name": "Afar"
},
{
code: "ab",
name: "ABKHAZIAN"
"code": "ab",
"name": "Abkhazian"
},
{
code: "af",
name: "AFRIKAANS"
}
...
]
```

### User Status
### Account Status

Returns information about your account and it's status.

```javascript
detectlanguage.userStatus().then(function(result) {
detectlanguage.accountStatus().then(function(result) {
console.log(JSON.stringify(result));
});
```
Expand Down
2 changes: 1 addition & 1 deletion examples/userStatus.js → examples/accountStatus.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ var DetectLanguage = require('../lib/');

var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY);

detectlanguage.userStatus().then(function(result) {
detectlanguage.accountStatus().then(function(result) {
console.log(JSON.stringify(result, null, 2));
});
2 changes: 1 addition & 1 deletion examples/detectBatch.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY);

var texts = ['šešios žąsys', 'Strč prst skrz krk'];

detectlanguage.detect(texts).then(function(result) {
detectlanguage.detectBatch(texts).then(function(result) {
console.log(JSON.stringify(result, null, 2));
});
28 changes: 28 additions & 0 deletions mise.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[tools]
node = "20"

[env]
_.file = ".env.local"

[tasks]
test = "yarn test"
build = "yarn build"

[tasks.examples]
depends = ["build"]
run = [
"node examples/detect.js",
"node examples/detectBatch.js",
"node examples/detectCode.js",
"node examples/languages.js",
"node examples/accountStatus.js"
]

[tasks.console]
depends = ["build"]
run = '''
node -i -e "\
var DetectLanguage = require('./lib');\
var detectlanguage = new DetectLanguage(process.env.DETECTLANGUAGE_API_KEY);\
"
'''
8 changes: 3 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "detectlanguage",
"version": "2.1.0",
"version": "3.0.0",
"description": "Detect Language API Node.js Client",
"main": "./lib/index.js",
"types": "./src/index.d.ts",
Expand Down Expand Up @@ -35,9 +35,6 @@
"url": "https://github.com/detectlanguage/detectlanguage-node/issues"
},
"homepage": "https://github.com/detectlanguage/detectlanguage-node",
"dependencies": {
"axios": "^0.21.1"
},
"devDependencies": {
"@babel/cli": "^7.11.6",
"@babel/core": "^7.11.6",
Expand All @@ -52,6 +49,7 @@
"eslint-plugin-import": "^2.22.0",
"mocha": "^8.1.3",
"nyc": "^15.1.0",
"rimraf": "^3.0.2"
"rimraf": "^3.0.2",
"sinon": "^20.0.0"
}
}
66 changes: 51 additions & 15 deletions src/client.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import axios from 'axios';
import * as defaults from './defaults';
import { handleError } from './error';

Expand All @@ -7,33 +6,70 @@ export default class Client {
const config = { ...defaults, ...options };

const headers = {
'Content-Type': 'application/json',
'User-Agent': config.userAgent,
Authorization: `Bearer ${apiKey}`,
};

this.connection = axios.create({
headers,
baseURL: `${config.protocol}://${config.host}/${config.apiVersion}/`,
timeout: config.timeout * 1000,
});
this.baseURL = `${config.protocol}://${config.host}/${config.apiVersion}/`;
this.timeout = config.timeout * 1000;
this.headers = headers;
}

/**
* Make a GET request
* @param {string} path - API endpoint path
* @returns {Promise<Object>} Response data
*/
async get(path) {
try {
const response = await this.connection.get(path);

return response.data;
} catch (e) {
return handleError(e);
}
return this.request(path, {
method: 'GET',
});
}

/**
* Make a POST request
* @param {string} path - API endpoint path
* @param {Object} data - Request body data
* @returns {Promise<Object>} Response data
*/
async post(path, data) {
return this.request(path, {
method: 'POST',
body: JSON.stringify(data),
});
}

/**
* Base request method that handles common request logic
* @param {string} path - API endpoint path
* @param {Object} options - Fetch options
* @returns {Promise<Object>} Response data
*/
async request(path, options = {}) {
try {
const response = await this.connection.post(path, data);
const controller = new AbortController();
const timeoutId = setTimeout(() => {
controller.abort();
}, this.timeout);

const response = await fetch(this.baseURL + path, {
headers: this.headers,
signal: controller.signal,
...options,
});

clearTimeout(timeoutId);

if (!response.ok) {
throw new Error(await response.text());
}

return response.data;
return await response.json();
} catch (e) {
if (e.name === 'AbortError') {
throw new Error(`Request timeout after ${this.timeout}ms`);
}
return handleError(e);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/defaults.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const { version } = require('../package.json');

module.exports = {
timeout: 60,
timeout: 60, // seconds
protocol: 'https',
host: 'ws.detectlanguage.com',
apiVersion: '0.2',
apiVersion: 'v3',
userAgent: `detectlanguage-node/${version}`,
};
10 changes: 9 additions & 1 deletion src/error.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
class DetectLanguageError extends Error {}

function handleError(error) {
const message = error?.response?.data?.error?.message || error.message;
let message;

try {
const json = JSON.parse(error.message);
message = json?.error?.message || error.message;
} catch (e) {
message = error.message;
}

const apiError = new DetectLanguageError(message);

apiError.stack = error.stack;
Expand Down
Loading