All files translate.ts

96.67% Statements 29/30
76.67% Branches 23/30
100% Functions 3/3
96.67% Lines 29/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 821x 1x 1x   1x       9x 1x 1x 1x     9x 1x 1x   9x 2x 2x 2x 2x     7x 7x           7x                                 7x           7x 7x     7x                   7x 7x     7x 1x     7x       1x
const translateToken = require('./token');
import axios, { AxiosRequestConfig } from 'axios-https-proxy-fix';
import { arrayStringify } from './util';
import { Options } from './index';
import { isSupport, getCode } from './language';
 
function handletranslate(data: string[], extra: Options): Promise<any> {
  let e: any;
  if(extra.from) {
    Eif(!isSupport(extra.from)) {
      e = new Error();
      e.language = extra.from;
    }
  }
  if(!isSupport(extra.to)) {
    e = new Error();
    e.language = extra.to;
  }
  if (e) {
    e.code = 400;
    e.message = 'The language \'' + e.language + '\' is not supported';
    return new Promise(function (_, reject) {
        reject(e);
    });
  }
  const tld = extra.tld || 'com';
  return translateToken
    .get(data.join(''), {
      tld,
      proxy: extra.proxy || false,
    })
    .then(res => {
      const query = {
        anno: 3,
        client: extra.client || "t",
        format: extra.format,
        v: 1.0,
        key: null,
        logld: "vTE_20190506_00",
        sl: extra.from || 'auto',
        tl: extra.to || 'zh-CN',
        hl: 'zh-CN',
        sp: "nmt",
        tc: 2,
        sr: 1,
        tk: res.value,
        mode: 1
      };
 
      const headers = {
        "content-type": "application/x-www-form-urlencoded",
        "Accept": "application/json, text/plain, */*",
        'X-Requested-With': 'XMLHttpRequest'
      }
 
      Eif (typeof extra.isUserAgent === 'undefined' || extra.isUserAgent) {
        headers['User-Agent'] = extra.userAgent ? extra.userAgent : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36';
      }
 
      const options: AxiosRequestConfig = {
        method: "POST",
        headers,
        data: arrayStringify(data),
        url: '/translate_a/t',
        baseURL: `https://translate.google.${tld}`,
        params: query,
        proxy: extra.proxy || false,
        ...(extra.config)
      };
      let browersUrl = 'https://cors-anywhere.herokuapp.com/';
      Iif (extra.browersUrl) {
        browersUrl = extra.browersUrl;
      }
      if(extra.browers) {
        options.baseURL = browersUrl + options.baseURL;
      }
 
      return axios(options);
    })
}
 
export default handletranslate;