Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
waithawoo committed Jun 17, 2023
0 parents commit 43d093c
Show file tree
Hide file tree
Showing 6 changed files with 200 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Wai Thaw Oo

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.
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Node Deepl API Translation

## To translate languages with Deepl Translation API

- **[Installation](#installation)**
- **[Usage](#usage)**

## Installation
Install this package via [npm](https://npmjs.com/).

```
npm install deepltranslate
```
## Usage
- import the package and create a new object by passing token
```
let deeplApi = require("deepltranslate")
let deeplTranslation = new deeplApi({token: 'this is token'})
```
- default hostname is 'api.deepl.com' and you can also pass hostname like this :
```
let deeplTranslation = new deeplApi({token: 'this is token', hostname: 'this is hostname'})
```
### Translate
```
deeplTranslation.translate("hello", "en", "ja").then((res)=>{
console.log(res);
})
```
### Get supported languages
```
deeplTranslation.getLanguages().then((res)=>{
console.log(res);
})
```
## Security

If you discover any security related issues, please email them to [[email protected]](mailto:[email protected]) instead of using the issue tracker.

## License

The MIT License (MIT). Please see the [License File](LICENSE) for more information.

28 changes: 28 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "deepltranslate",
"version": "1.0.0",
"description": "To use deepl translate api",
"main": "src/index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/waithawoo/node-deepl-translate.git"
},
"keywords": [
"deepltranslate"
],
"author": "Wai Thaw Oo",
"license": "MIT",
"bugs": {
"url": "https://github.com/waithawoo/node-deepl-translate/issues"
},
"homepage": "https://github.com/waithawoo/node-deepl-translate#readme",
"dependencies": {
"deepltranslate": "^1.0.0"
}
}
9 changes: 9 additions & 0 deletions src/deeplTranslateError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class deeplTranslateError extends Error {
constructor (message){
super(message)
Error.captureStackTrace(this, this.constructor)

this.name = this.constructor.name
}
}
module.exports = deeplTranslateError
87 changes: 87 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
const https = require('https');
const deeplTranslateError = require('./deeplTranslateError');

class deeplApi {

hostname = 'api.deepl.com';
headers = {'Content-Type': 'application/x-www-form-urlencoded'};
API_LANGUAGE_RESOURCE = 'languages';
API_TRANSLATE_RESOURCE = 'translate';
API_VERSION = '2';

#_token;
#options;
constructor(options) {
this.#options = {
hostname : this.hostname,
...options
}
this.hostname = this.#options.hostname;
this.#_token = this.#options.token;
}

translate = async (text, source_lang, target_lang, split_sentences = 0) => {
let prefix = `/v${this.API_VERSION}/${this.API_TRANSLATE_RESOURCE}?auth_key=${this.#_token}&`;
let path = this.#buildPath(prefix, {text:text,source_lang:source_lang,target_lang:target_lang,split_sentences:split_sentences})
try{
const response = await this.#requestAPI(path)
if(response.message) throw new deeplTranslateError(JSON.stringify(response.message))
return response.translations[0].text
}catch(error){
throw error
}
}

getLanguages = async (type = 'source') => {
let prefix = `/v${this.API_VERSION}/${this.API_LANGUAGE_RESOURCE}?auth_key=${this.#_token}&`;
let path = this.#buildPath(prefix, {type:type})
try {
const response = await this.#requestAPI(path)
if(response.message) throw new deeplTranslateError(JSON.stringify(response.message))
return response
}catch(error){
throw error
}
}

#buildPath = (prefix, parameters) =>{
let params = new URLSearchParams(parameters);
let body = prefix+params.toString();

return body;
}

#requestAPI = (path) =>{
return new Promise(resolve => {
const options = {
hostname: this.hostname,
port: 443,
path: path,
method: 'GET',
headers: this.headers,
// rejectUnauthorized:false
}

const req = https.request(options, res => {
let data = [];

res.on('data', chunk => {
data.push(chunk);
});

res.on('end', () => {
const result = JSON.parse(Buffer.concat(data).toString());
resolve(result);
});

})
req.on('error', error => {
throw new deeplTranslateError(JSON.stringify(error))
})
req.end()
});

}
}

module.exports = deeplApi
11 changes: 11 additions & 0 deletions test/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
let deeplApi = require("deepltranslate")

let deeplTranslation = new deeplApi({token: 'this is token'})

deeplTranslation.translate("hello", "en", "ja").then((res)=>{
console.log(res);
})

deeplTranslation.getLanguages().then((res)=>{
console.log(res);
})

0 comments on commit 43d093c

Please sign in to comment.