-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataFetcher.ts
96 lines (85 loc) · 2.18 KB
/
dataFetcher.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { gql, QueryRunnerOptions } from '@zeusdeux/serverless-graphql'
import { createClient } from 'contentful'
import { runQuery } from './schema'
import {
GetPostQuery,
GetPostQueryVariables,
GetPostsQuery,
GetPostsQueryVariables
} from './types.generated'
export const ctflConfig =
process.env.NODE_ENV === 'production' && process.env.FORCE_PREVIEW !== 'true' // FORCE_PREVIEW to deploy a preview version from localhost
? {
space: process.env.SPACE_ID!,
accessToken: process.env.CDA_TOKEN! // comes from next.config.js and there from the env itself
}
: {
space: process.env.SPACE_ID!,
accessToken: process.env.PREVIEW_TOKEN!, // // comes from next.config.js and there from the env itselfP
host: 'preview.contentful.com'
}
const ctfl = createClient(ctflConfig)
async function fetchViaGql<T>(args: QueryRunnerOptions) {
const argsWithContext: QueryRunnerOptions = {
...args,
context: {
ctfl
}
}
const { data, errors } = await runQuery<T>(argsWithContext)
if (errors) {
console.log(errors) // tslint:disable-line
throw new Error(errors[0].message)
}
return data
}
export async function getPosts(variables: GetPostsQueryVariables = {}): Promise<GetPostsQuery> {
const result = await fetchViaGql<GetPostsQuery>({
req: gql`
query getPosts {
posts {
id
slug
title
}
}
`,
variables
})
if (!result) {
throw new Error(`Unexpected result ${result} for getPosts query`)
}
return result
}
export async function getPost(variables: GetPostQueryVariables): Promise<GetPostQuery> {
const result = await fetchViaGql<GetPostQuery>({
req: gql`
query getPost($slug: String!) {
post(slug: $slug) {
metadata {
id
slug
title
}
body
tags
previous {
id
slug
title
}
next {
id
slug
title
}
}
}
`,
variables
})
if (!result) {
throw new Error(`Unexpected result ${result} for getPost query`)
}
return result
}