Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
How can I "encapsulate" this code into a module so it could become reusable?

I have got this Node.JS snippet and would like to write it as a module, so I can use recaptcha in different parts of my system.

This is how it currently looks like:

app.post('/register_user', (req, res) => {
  const secret_key = process.env.RECAPTCHA_SECRET;
  const token = req.body.recaptcha;
  const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
  fetch(url, { method: "post",})
    .then((response) => response.json())
    .then((google_response) => {
      if (google_response.success == true) {      
        res.format({'text/html': () => res.redirect(303, '/register'),})
      } else {
        return res.send({ response: "Failed" });
      }
    })
    .catch((error) => {
      return res.json({ error });
    });
})

I have tried to write the following module which works absolutely great, but I have absolute no idea about how to call it from the app.post, since I always get undefined as return:

import fetch from 'node-fetch';

export function fetch_out(url, timeout = 7000) {
    return Promise.race([
        fetch(url),
        new Promise((_, reject) =>
            setTimeout(() => reject(new Error('timeout')), timeout)
        )
    ]);
}
export async function checkRecaptcha(token, secret_key){
    const url = "https://www.google.com/recaptcha/api/siteverify?secret=" + secret_key + "&response=" + token;
    try{
    const response = await fetch_out(url, 1000);
    const google_response = await response.json();
    }catch(error){
        return error;
    }
    return google_response;
}

Any help would be appreciated! Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could make this method reusable by removing the framework actions that need to happen and only return if the validation was successful or not. This way, it will be reusable in another project that doesn't use a specific framework.

Example module;

export async function checkRecaptcha(token, secret_key) {
    const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
    
    const response = await fetch(url, { method: "post",});
    if (!response.ok) return false;

    const json = await response.json();
    if (!json.success) return false;      
    
    return true;
}

Usage:

import { checkRecaptcha } from "./some-file-name";

app.post('/register_user', async (req, res) => {
    const isHuman = await checkRecaptcha(req.body.recaptcha, process.env.RECAPTCHA_SECRET);
    
    if (!isHuman) {
        return res.send({ response: "Failed" });
    }
    
    return res.format({'text/html': () => res.redirect(303, '/register'),});
});

If you specifically want to call an action after the validation, you can also use successful and error callbacks.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda