如何处理来自 NextJS 后端 API 的 64 位有符号整数

问题描述 投票:0回答:1

我有一个 NextJS 应用程序,其中一个后端 API 路由返回一个包含 64 位有符号整数的 JSON 对象。

// userId is the 64-bit signed integer
res.status(200).json({ id: userId, attributes: userAttributes });

当我在前端取回数据时,我在解析用户 ID 时遇到了问题。当我记录它时 (

console.log(response.data)
) 我看到类似的东西:

{
    id: { high: 0, low: 1, unsigned: false },
    attributes: { ... }
}

我尝试使用

parseInt
BigInt
进行解析,但它不起作用。使用从 API 调用返回的 64 位有符号整数的正确方法是什么?

javascript next.js integer long-integer bigint
1个回答
0
投票

具有字段

{high, low, unsigned}
的对象似乎是
Long
来自 Long.js 库。

您可以直接使用它(Long.js 库提供了全套操作,请参阅其文档),也可以将其转换为 BigInt。可能(我还没有测试过)会是这样的:

function toBigInt(long) {
  let high = long.unsigned ? long.high >>> 0 : long.high;
  return (BigInt(high) << 32n) + BigInt(long.low >>> 0);
}
© www.soinside.com 2019 - 2024. All rights reserved.