DEV Community

Phong Duong
Phong Duong

Posted on • Originally published at phongduong.dev on

Create collections from API with Gridsome

Gridsome provides many source plugins that help you create collections from your source. But if you want to create collections from your API or a third-party API, you have to create collections manually.

In gridsome.server.js file, you call loadSource method of api parameter. You pass a callback function which you will fetch the API and create collections from data.

Your callback has an actions parameter, it has addCollection method. You will use this method to create your collections

const axios = require("axios")

module.exports = function(api) {
  api.loadSource(actions) => {
    const { data } = await axios.get('https://example.com/api/v1/posts')
    const postCollection = actions.addCollection("Post")

    for(const post of data) {
      postCollection.addNode({
        id: post.id,
        title: post.title
      })
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

After you start the server, it will create Post collection. To get the collection, you call getCollection method with the collection's name

actions.getCollection("Post")

Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay