papago.js 1.96 KB

var client_id = '6hpmInU0TCrQIiiJwgJX';
var client_secret = 'jpYZbkj0_g';
// var query = "언어를 감지할 문장을 입력하세요.";
// app.get('/detectLangs', function (req, res) {
//    var api_url = 'https://openapi.naver.com/v1/papago/detectLangs';
//    var request = require('request');
//    var options = {
//        url: api_url,
//        form: {'query': query},
//        headers: {'X-Naver-Client-Id':client_id, 'X-Naver-Client-Secret': client_secret}
//     };
//    request.post(options, function (error, response, body) {
//      if (!error && response.statusCode == 200) {
//        console.log(JSON.parse(body).langCode);
//        res.writeHead(200, {'Content-Type': 'text/json;charset=utf-8'});
//        res.end(body);
//      } else {
//        res.status(response.statusCode).end();
//        console.log('error = ' + response.statusCode);
//      }
//    });
//  });
//  app.listen(3000, function () {
//    console.log('http://127.0.0.1:3000/detectLangs app listening on port 3000!');
//  });

async function findLanguage(sourceText) {
  const api_url = 'https://openapi.naver.com/v1/papago/detectLangs';
  const request = require('request');
  let options = {
      url: api_url,
      form: {'query': sourceText},
      headers: {'X-Naver-Client-Id':client_id, 'X-Naver-Client-Secret': client_secret}
  };

  return new Promise((resolve, reject) => {
    let resultLang = {};
    
    request.post(options, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            resultLang = JSON.parse(body).langCode
            console.log(resultLang);
            resolve(resultLang);
        }
        else {
            console.log('error = ' + response.statusCode);
            reject("error");
        }
    });  
});
}
/*
export async function getLang(comment) {
  const lang =  await findLanguage(comment);
  return lang;  
}
*/
exports.getLang = async function(comment) {
    const lang =  await findLanguage(comment);
    return lang;  
  }