superjson.ts 940 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * SuperJSON 配置 - 用于 JSON 序列化/反序列化
  3. * 处理 Next.js Server Components 和 Client Components 之间的数据传输
  4. */
  5. import { SuperJSON } from 'superjson';
  6. export const superjson = SuperJSON;
  7. /**
  8. * 将数据序列化为 JSON 字符串(用于 Server -> Client 传输)
  9. */
  10. export function serialize<T>(data: T): string {
  11. return superjson.stringify(data);
  12. }
  13. /**
  14. * 从 JSON 字符串反序列化数据(用于 Client -> Server 传输)
  15. */
  16. export function deserialize<T>(json: string): T {
  17. return superjson.parse(json);
  18. }
  19. /**
  20. * Server Actions 返回值的序列化包装
  21. */
  22. export function createSerializedResponse<T>(data: T) {
  23. return {
  24. data: superjson.serialize(data).json,
  25. };
  26. }
  27. /**
  28. * 解析从 Server 传来的序列化数据
  29. */
  30. export function parseSerializedResponse<T>(response: { data: unknown }): T {
  31. return superjson.deserialize({
  32. json: response.data as any,
  33. }) as T;
  34. }