Search code examples
gatsbynetlify

How to fetch a remote file during build-time in Gatsby?


I am using Gatsby to build a website, hosted on Netlify. The website shows the Video on Youtube playlist. In order to make a faster website, I would like to cache the videos in the youtube playlist locally.

So are there any memcache-like item on Netlify (or Gatsby)? Or should I use any alternative method?

Thanks in advance


Solution

  • There are two steps:

    1. Instead of storing the content in the project, store it in a CMS. Here is an example of using DatoCMS to manage content and build a static webpage using Gatsby.
    2. createRemoteFileNode would fetch the Youtube thumbnail into local cache. All I need to do is find the Youtube Thumbnail URL, then call the createRemoteFileNode function. All is done within the exports.createResolvers in gatsby-node.js. Here is the code snippet:
    exports.createResolvers = ({
      actions,
      cache,
      createNodeId,
      createResolvers,
      store,
      reporter,
    }) => {
      const { createNode } = actions;
      const resolvers = {
        DatoCmsVideoItem: {
          featuredImg: {
            type: `File`,
            resolve: async (source, args, context, info) => {
              return createRemoteFileNode({
                url: source.videoId,
                createNode,
                createNodeId,
                reporter,
                cache,
                store,
              });
            },
          },
        },
      };
      createResolvers(resolvers);
    };
    

    This would fetch the file in node source.videoId and then store the file in node source.featuredImg for future use.