server-side-props.ts 909 B

1234567891011121314151617181920212223
  1. import type { GetServerSidePropsResult } from 'next';
  2. import deepMerge from 'ts-deepmerge';
  3. // Type-safe GetServerSidePropsResult merger for two results
  4. export function mergeGetServerSidePropsResults<T1, T2>(
  5. result1: GetServerSidePropsResult<T1>,
  6. result2: GetServerSidePropsResult<T2>,
  7. ): GetServerSidePropsResult<T1 & T2> {
  8. // Check for redirect responses (return the first one found)
  9. if ('redirect' in result1) return result1;
  10. if ('redirect' in result2) return result2;
  11. // Check for notFound responses (return the first one found)
  12. if ('notFound' in result1) return result1;
  13. if ('notFound' in result2) return result2;
  14. // Both results must have props for successful merge
  15. if (!('props' in result1) || !('props' in result2)) {
  16. throw new Error('Invalid GetServerSidePropsResult - missing props');
  17. }
  18. return deepMerge(result1, result2) as GetServerSidePropsResult<T1 & T2>;
  19. }