Skip to content
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

Server.js in speechtotext #4

Open
Montana opened this issue Dec 5, 2023 · 0 comments
Open

Server.js in speechtotext #4

Montana opened this issue Dec 5, 2023 · 0 comments

Comments

@Montana
Copy link

Montana commented Dec 5, 2023

Hey folks,

I think a better way of doing server.js in the speechtotext repo, is to extract the Azure configuration into a separate file, so make it like:

module.exports = {
  endpoint: process.env.AZURE_ENDPOINT, 
  key: process.env.AZURE_API_KEY,
  region: process.env.AZURE_TRANSLATOR_REGION
}

This can be called whatever, for the time being I'll call it azureConfig.js. Now create the translations service utilizing axios, async and promises:

const axios = require('axios'); 
const azureConfig = require('./azureConfig');

const translateText = async (text, targetLang) => {

  const headers = {
    'Ocp-Apim-Subscription-Key': azureConfig.key,
    'Ocp-Apim-Subscription-Region': azureConfig.region,
  };

  try {
    const response = await axios.post(`${azureConfig.endpoint}&to=${targetLang}`, [{ text }], { headers });
    return response.data[0].translations[0].text;

  } catch (error) {
    console.error('Translation error', error);
    throw error;
  }
}

module.exports = {
  translateText  
}

Then the final thing, is clean up the app code a bit:

const express = require('express');
const path = require('path'); 
const bodyParser = require('body-parser');

const translations = require('./translations');

const app = express();

app.use(bodyParser.json());

app.post('/translate', async (req, res) => {

  try {
    const text = await translations.translateText(req.body.text, req.body.targetLang);    
    res.json({ translatedText: text });
  
  } catch (error) {
    res.status(500).json({ error: 'Translation failed' }); 
  }

});

// ...

This way, JS can handle errors centrally in services, and overall a better flow. Just my opinion though.

-Michael

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant