Letterpad
Search…
Typescript
To access data from a Graphql API, there are various clients available than can simplify the process. We are going to keep it simple and use the default fetch API.
You can have all the queries typed by configuring codegen. Lets see how to configure this.
Install these modules.
1
# as dependencies
2
yarn add typescript graphql graphql-tag
3
4
# as dev-dependencies
5
yarn add @graphql-codegen/cli \
6
@graphql-codegen/typescript \
7
@graphql-codegen/typescript-operations \
8
@types/graphql -D
Copied!
Create a file codegen.yml in your root directory and add the below lines
1
schema: https://letterpad.app/admin/api/graphql
2
documents:
3
- ./**/*.tsx
4
generates:
5
lib/graphql.ts:
6
plugins:
7
- typescript
8
- typescript-operations
9
config:
10
exportFragmentSpreadSubTypes: true
11
Copied!
Lets understand whats going on here.
schema - Link to graphql schema
documents - Path of your queries
generates - It is going to generate the types in lib/graphql.ts file.
plugins - The plugins it will use to create the types.
exportFragmentSpreadSubTypes - If set to true, it will export the sub-types created in order to make it easier to access fields declared under fragment spread.
Refer to this documentation for more details.

Generate Types

Enter a new script in package.json to execute the codegen.
package.json
1
scripts: {
2
...
3
"generate": "graphql-codegen",
4
...
5
}
Copied!
Executing yarn generate wont generate any types yet because we have not written any query.
So lets write a query in index.ts which is again in the root folder.
1
import gql from "graphql-tag";
2
3
const pageQuery = gql`
4
query PageQuery($slug: String) {
5
post(filters: { slug: $slug }) {
6
... on Post {
7
id
8
title
9
}
10
... on PostError {
11
message
12
}
13
__typename
14
}
15
}
16
`;
Copied!
Graphql Codegen is going to read all files having a query or mutation and will generate types for it. So execute the below command.
1
yarn generate
Copied!
You should see a new file - lib/graphql.ts which got generated and has all the necessary types.
Since the name of query is PageQuery the respose type corresponding to this would be PageQueryQuery.
Now lets try to send an API request to get the data.
1
import { print } from "graphql";
2
import fetch from "node-fetch";
3
import { PageQueryQuery } from "../lib/graphql";
4
5
fetch("https://letterpad.app/admin/api/graphql", {
6
method: "POST",
7
headers: {
8
"Content-Type": "application/json",
9
Authorization: "Bearer YOUR-CLIENT-ID",
10
},
11
body: JSON.stringify({
12
query: print(postQuery),
13
variables: { slug: "walk-around-music" },
14
}),
15
})
16
.then(res => res.json())
17
.then(({ data }: { data: PageQueryQuery }) => {
18
if (data.post.__typename === "Post") {
19
console.log(data.post.title);
20
}
21
})
Copied!
Last modified 3mo ago
Copy link