-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtools.tsx
67 lines (54 loc) · 1.7 KB
/
tools.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import * as hoistNonReactStatics from 'hoist-non-react-statics';
import type { GetServerSideProps } from 'next';
import * as React from 'react';
import SuperJSON from 'superjson';
type SuperJSONProps<P> = P & {
_superjson?: ReturnType<typeof SuperJSON.serialize>['meta'];
};
export function withSuperJSONProps<P>(
gssp: GetServerSideProps<P>,
exclude: string[] = []
): GetServerSideProps<SuperJSONProps<P>> {
return async function withSuperJSON(...args) {
const result = await gssp(...args);
if (!('props' in result)) {
return result;
}
if (!result.props) {
return result;
}
const excludedPropValues = exclude.map((propKey) => {
const value = (result.props as any)[propKey];
delete (result.props as any)[propKey];
return value;
});
const { json, meta } = SuperJSON.serialize(result.props);
const props = json as any;
if (meta) {
props._superjson = meta;
}
exclude.forEach((key, index) => {
const excludedPropValue = excludedPropValues[index];
if (typeof excludedPropValue !== 'undefined') {
props[key] = excludedPropValue;
}
});
return {
...result,
props,
};
};
}
export function deserializeProps<P>(serializedProps: SuperJSONProps<P>): P {
const { _superjson, ...props } = serializedProps;
return SuperJSON.deserialize({ json: props as any, meta: _superjson });
}
export function withSuperJSONPage<P>(
Page: React.ComponentType<P>
): React.ComponentType<SuperJSONProps<P>> {
function WithSuperJSON(serializedProps: SuperJSONProps<P>) {
return <Page {...deserializeProps<P>(serializedProps)} />;
}
hoistNonReactStatics(WithSuperJSON, Page);
return WithSuperJSON;
}