使用 getInitialProps 保护路由 - Next.js

我们目前正在研究特定于用户的流程,即需要一些保护措施来防止用户访问某些页面。我们根据来自 GraphQL API 的数据执行此操作,据我们所知,我们应该在getInitialProps.


我们想为此使用一些实用程序函数,而不是重写每个页面上的所有逻辑。请参阅此处的示例:


来自我们的 getInitialProps 的片段


Email.getInitialProps = async ({ req, res, apolloClient }) => {

  const deviceInfo = getDeviceInfo(req)


  try {

    const {

      data: { viewer },

    } = await apolloClient.query({

      query: GET_CHECKOUT,

      fetchPolicy: 'network-only',

    })


    checkForCart(viewer, res)

    checkForProcessingPayment(viewer, res)


    return {

      namespacesRequired: ['buy-common', 'common', 'buy-email'],

      deviceInfo,

    }

  } catch (error) {

    const { href, as } = getLinkProps('CART')

    return redirect({ href, as }, res)

  }

}

实用程序函数(handleRedirect只是res.redirect一个res.end在后台执行 a和 a的重定向实用程序)


export const checkForCart = ({ cart, checkout }, res) => {

  const { rows = [] } = checkout || {}


  if (!cart || !rows.length) {

    return handleRedirect('CART', res)

  }

}

这看起来不错,因为我们可以使用checkForCart()而不是为每个页面重复此代码。它有一个问题,那就是return对的checkForCartUTIL只返回的功能,而不是网页。所以,因为重定向需要一些时间,checkForCart()get下面的代码被执行。所以如果我在console.log下面做一个checkForCart(viewer, res)它会记录。


有没有一种巧妙的方法可以停止从 util 执行,或者在 Next.js 中有一种巧妙的方法来解决这样的情况?实施“守卫”之类的最佳方法是什么?


MM们
浏览 261回答 1
1回答

红颜莎娜

getInitialProps是一个async函数,这意味着您可以利用await语法。转换checkForCart成一个函数,返回一个promise和await它,然后处理结果。例如:export const checkForCart = ({ cart, checkout }, res) => {  const { rows = [] } = checkout || {}  return new Promise((resolve, reject) => {    if (!cart || !rows.length) {      reject()    }    resolve()  })}Email.getInitialProps = async ({ req, res, apolloClient }) => {  const deviceInfo = getDeviceInfo(req)  try {    const {      data: { viewer },    } = await apolloClient.query({      query: GET_CHECKOUT,      fetchPolicy: 'network-only',    })    // If this rejects/fails because !cart || !rows.length    // execution will jump to the catch block    await checkForCart(viewer, res)    // This won't run until checkForCart finishes and resolves    checkForProcessingPayment(viewer, res)    return {      namespacesRequired: ['buy-common', 'common', 'buy-email'],      deviceInfo,    }  } catch (error) {    const { href, as } = getLinkProps('CART')    return redirect({ href, as }, res)  }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript