简体   繁体   English

NextJS getServerSideProps() 一次延迟获取多个端点

[英]NextJS getServerSideProps() fetch multiple endpoints at once in delay

Is there a way to fetch data from multiple API routes in a single getServerSideProps() in delay?有没有办法在单个 getServerSideProps() 中延迟从多个 API 路由中获取数据?

I encountered an 429 error(too many requests) when I was trying to fetch data from multiple endpoints at once with Promise.all() .当我尝试使用Promise.all()

Is there any method that I can use to fetch the multiple array endpoints in 1 second delay each?有什么方法可以用来在每个延迟 1 秒的时间内获取多个数组端点?

async function getClients () {
  const res = await fetch('http://localhost:3000/api/clients')
  const json = await res.json()
  return Object.entries(json)
}

async function getDetails (clients) {
  const details = await Promise.all(
    clients.map(async (item) => {
      const url = 'http://localhost:3000/api/clients/' + item.clientId;
      const res = await fetch(url)
      const json = await res.json()
      return json
    })
  )
  return details
}

export async function getServerSideProps() {
  const clients = await getClients()
  const details = await getDetails(clients)

  return {
    props: {
      clients,
      details,
    },
  }
}

You could try using the rate limiter that's part of the async-sema package.您可以尝试使用async-sema包中的速率限制器。

It's also worth noting that you should avoid calling your Nextjs API routes from your getServerSideProps function.还值得注意的是,您应该避免从getServerSideProps函数调用 Nextjs API 路由。 As it's already running on the server you can perform whatever logic is inside your API routes directly and avoid the penalty of an extra network hop.由于它已经在服务器上运行,您可以直接执行 API 路由中的任何逻辑,并避免额外网络跃点的损失。

import { RateLimit } from "async-sema";

async function getClients () {
  const res = await fetch('http://localhost:3000/api/clients')
  const json = await res.json()
  return Object.entries(json)
}

async function getDetails (clients) {
  const lim = RateLimit(5);
  const details = await Promise.all(
    clients.map(async (item) => {
      await lim();
      const url = 'http://localhost:3000/api/clients/' + item.clientId;
      const res = await fetch(url)
      const json = await res.json()
      return json
    })
  )
  return details
}

export async function getServerSideProps() {
  const clients = await getClients()
  const details = await getDetails(clients)

  return {
    props: {
      clients,
      details,
    },
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM