Skip to content

Server.js in speechtotext #4

@Montana

Description

@Montana

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions