aboutsummaryrefslogtreecommitdiff
path: root/content/snippets/11ty-fetch-put-request.md
blob: ac0a9e88eff5d38e7339edebcb0697afc9f35782 (plain)
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
---
title: Make a PUT request with @11ty/eleventy-fetch
description: Make a PUT request with @11ty/eleventy-fetch
tags: ["11ty"]
---

[11ty](https://www.11ty.dev/) fetch lets you cache resources for any remote asset at build time. It scored it in a cache in your project.

The basic request format supports `GET` only:

```js
const EleventyFetch = require("@11ty/eleventy-fetch");

module.exports = async function () {
  let url = "https://api.github.com/repos/11ty/eleventy";

  /* This returns a promise */
  return EleventyFetch(url, {
    duration: "1d", // save for 1 day
    type: "json", // we’ll parse JSON for you
  });
};
```

You can update it to change it to a `PUT` request (there were no examples I could find of this anywhere). Here i'm making a PUT request to retrieve my username from [Hardcover](https://hardcover.app/) using a GraphQL query.

```js
const url = "https://api.hardcover.app/v1/graphql";

return EleventyFetch(url, {
  duration: "1d",
  type: "json",
  fetchOptions: {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      authorization: "<BEARER_TOKEN>",
    },
    body: JSON.stringify({
      query: `{
            me {
              username
            }
          } `,
    }),
  },
});
```

Running this at build time in `_data/username.json` will store the asset in a global `username` object.