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

150
Visualizações
Javascript annotations / decorators on normal functions

I am developing a Next.js application, and I have an API defined in the following way:

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') {
    fn1Get(req, res);
  } else if (req.method === 'POST') {
    fn1Post(req, res);
  } else {
    res.status(501).json({ operation: `${req.method}: not implemented` });
  }
}
async function fn1Get(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  const authenticated = await checkAuth(req, res);
  if (authenticated) {
      // Get Stuff
      res.status(200).json({status: 'all right!'});
  }
}
async function fn1Post(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  const authenticated = await checkAuth(req, res);
  if (authenticated) {
      // Post Stuff
      res.status(201).json({status: 'all right!'});
  }
}
const checkAuth = async (req: NextApiRequest, res: NextApiResponse) => {
  const tokenValid = await extnernalApiCall(getToken(req));
  if (!tokenValid) {
    res.status(403).json({ error: 'Authentication Failed' });
  }
  return tokenValid
};

I am trying to find an easier setup to define authenticated methods, instead of adding inside of them the line const authenticated = await checkAuth(req, res);

In other languages like Java or Python I could use decorators / annotations / AOP, something like:

@checkAuth
async function fn1Get(
  req: NextApiRequest,
  res: NextApiResponse
):

Can I do something close to it in javascript? Maybe via wrapping functions, and/or using bind/call/apply??

Pseudo-code example:

const checkAuth = async (fn) => {
  const req = arguments[1];
  const res = arguments[2];
  const tokenValid = await extnernalApiCall(getToken(req));
  if (!tokenValid) {
    res.status(403).json({ error: 'Authentication Failed' });
  }
  return fn(arguments);
}
async function fn1Get = checkAuth(_fn1Get(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  const authenticated = await checkAuth(req, res);
  if (authenticated) {
      // Get Stuff
      res.status(200).json({status: 'all right!'});
  }
})

As you can see, all the functions that I want to authenticate will receive the same two parameters req and res (request and response), and my authentication function also need both parameters to get the token to authenticate from the req and write a 403 in res if it is not authenticated

The technologies I'm using are Next.js with React 17, TypeScript, ECMA6

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

0

Yes, you can achieve this with a wrapper function (that's basically what decorators are anyway). That wrapper function has to return a function. Something like the following (you'll have to adjust the types accordingly):

const checkAuth = (fn) => {
  return async (req: NextApiRequest,res: NextApiResponse): Promise<void> => {
    const tokenValid = await extnernalApiCall(getToken(req));
    if (!tokenValid) {
      res.status(403).json({ error: 'Authentication Failed' });
    } else {
      fn(req, res);
    }
  }
}

const fn1Get = checkAuth((
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> => {
  // Get Stuff
  res.status(200).json({status: 'all right!'});
})

Having said that, I'm not familiar with next.js. There might be a way to register middelware handlers that would fire on every request without you having to wrap every handler explicitly.

about 4 years ago · Juan Pablo Isaza Relatório

0

I use next js along with next-auth for authentication. I made a function that checks if the request has a session. If no session, the user gets redirected to the sign in page. If the user has a session, it passes the props to getServerSideProps function.

import { getSession } from "next-auth/react";

/* gssp =  */
export const requireAuth = (gssp) => {
  return async (ctx) => {
      const { req } = ctx;
      const session = await getSession({ req })
      if (!session) {
          return {
              redirect: { permanent: false, destination: '/api/auth/signin' }
          };
      };
      const ctxWithSession = { ...ctx, session };
      return await gssp(ctxWithSession);
  };
};

Then, i call this function in my next js page as a higher function of getServerSideProps :

export const getServerSideProps = requireAuth(async _ctx => {
    const { session } = _ctx;
    return {
        props: {
          session: session,  
        },
    };
});
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