我正在开发一个Next.js应用程序,并且我有一个按以下方式定义

我正在开发一个 Next.js 应用程序,并且我有一个按以下方式定义的 API:

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 {
  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 {
  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
};

我试图找到一种更简单的设置来定义已验证的方法,而不是添加行 const authenticated = await checkAuth(req, res);

在Java或Python等其他语言中,我可以使用装饰器/注释/AOP,例如:

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

我可以在 javascript 中做一些接近它的事情吗?也许通过包装一个函数,和/或使用绑定/调用/应用? ?

伪代码示例:

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 {
  const authenticated = await checkAuth(req, res);
  if (authenticated) {
      // Get Stuff
      res.status(200).json({status: 'all right!'});
  }
})

如您所见,我要认证的所有函数都会收到相同的两个参数req和res(请求和响应),而我的认证函数也需要这两个参数来获取token进行认证,从req中写入403未通过身份验证的 res

我使用的技术是 Next.js 和 React 17、TypeScript、ECMA6

© 版权声明
THE END
喜欢就支持一下吧
点赞190赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容