/
index.tsx
59 lines (50 loc) · 1.37 KB
/
index.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
import {
Environment,
FetchFunction,
fetchQuery,
Network,
RecordSource,
Store,
} from 'relay-runtime'
import { GetServerSideProps } from 'next'
import { pagesQuery as pagesQueryType } from '../queries/__generated__/pagesQuery.graphql'
import pagesQuery from '../queries/pagesQuery'
type Props = { greeting: string }
export default function Index({ greeting }: Props) {
return <p>{greeting}</p>
}
function createGraphQLFetcher(host: string | undefined): FetchFunction {
return async function fetchGraphQL(params, variables) {
const url = host ? `http://${host}/api/query` : `/api/query`
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: params.text,
variables,
}),
})
return await response.json()
}
}
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
const environment = new Environment({
store: new Store(new RecordSource({}), {}),
network: Network.create(createGraphQLFetcher(req.headers.host)),
})
const result = await fetchQuery<pagesQueryType>(
environment,
pagesQuery,
{}
).toPromise()
if (!result) {
throw new Error(
'Mock GraphQL Server network request finished without a response!'
)
}
return {
props: { greeting: result.greeting },
}
}