DEV Community

Cover image for SquidexCMS to Gridsome using Content API
Gareth Wright
Gareth Wright

Posted on • Updated on

SquidexCMS to Gridsome using Content API

I've recently created a portfolio website and needed a CMS to populate certain areas of my website.

I've been using Gridsome to generate a static website, so I wanted to hook that up to a headless CMS.

I chose SquidexCMS for the starter free pricing:

  • 20.000 API Calls per Month
  • 2 GB Traffic per Month
  • 500 MB Storage
  • 2 Contributors

This enabled me to use it for a basic portfolio website, as the stats above covered me.

It was quite easy to setup SquidexCMS, using schemas and content and it didn't take too long to populate with my content (I'll write this up in another post soon).

Next I needed to connect Squidex to my local website. In Gridsome you can do this within the gridsome.server.js file docs, which is located in the root of the solution.

This is my solution to connecting to the Content API used within Squidex and Gridsome JS to add GraphQL collections.

gridsome.server.js


const axios = require('axios');

module.exports = function (api) {

  api.loadSource(async actions => {

    // config
    const baseApiUrl = 'https://cloud.squidex.io/api/content/garpunkaldev/';
    const config = {
      headers: {
        "X-Flatten": true,
        "X-NoResolveLanguages": 1,
        "X-Languages": "en"
      }
    };

    // gather data from api
    const { data: companyData } = await GetAsync(baseApiUrl + 'company', config);
    const { data: projectData } = await GetAsync(baseApiUrl + 'project', config);
    const { data: experienceData } = await GetAsync(baseApiUrl + 'experience', config);
    const { data: highlightData } = await GetAsync(baseApiUrl + 'highlight', config);

    // experiences
    const expCollection = actions.addCollection({ typeName: 'Experiences' })
    for (const item of experienceData.items) {

      // filter relations
      const company = companyData.items.find(function (x) { return x.id === item.data.company[0] });
      const projects = BuildList(item.data.projects, projectData.items);
      const contribs = BuildList(item.data.contributions, projectData.items);
      // map
      expCollection.addNode(MapExperience(item, company, projects, contribs))
    }

    // projects
    const proCollection = actions.addCollection({ typeName: 'Projects' })
    for (const item of highlightData.items) {

      // filter relations
      const projects = BuildList(item.data.projects, projectData.items);

      // map
      proCollection.addNode(MapProject(item, projects));
    }
  })

  function BuildList(selection, source) {
    var items = [];
    selection.forEach(function (item) {
      const found = source.find(x => x.id == item);
      if (found != null)
        items.push(found);
    });

    return items;
  }

  function MapProject(item, projects) {
    return {
      "id": item.data.id,
      "orderNumber": item.data.orderNumber,
      "projects": projects.map(p =>
      ({
        "title": p.data.title,
        "position": p.data.position,
        "url": p.data.url,
        "large": GetBool(p.data.large),
        "image": {
          "url": "https://cloud.squidex.io/api/assets/garpunkaldev/" + p.data.image[0] + "?cache=2592000",
          "alt": p.data.title,
          "width": p.data.large ? 615 : 300,
          "height": p.data.large ? 340 : 165,
        }
      }))
    }
  }

  function MapExperience(item, company, projects, contribs) {
    return {
      "id": item.data.id,
      "title": company.data.title,
      "job": item.data.job,
      "location": company.data.location,
      "logo": {
        "url": "https://cloud.squidex.io/api/assets/garpunkaldev/" + company.data.logo[0] + "?cache=2592000",
        "background": company.data.logoBackgroundColour,
        "alt": company.data.title
      },
      "url": company.data.url,
      "shortUrl": company.data.shortUrl,
      "from": GetMonthYear(item.data.from),
      "to": GetMonthYear(item.data.to),
      "isCurrent": GetBool(item.data.isCurrent),
      "description": item.data.description,
      "projects": {
        "title": item.data.projectsLabel,
        "items": projects.map(p => ({ "name": p.data.title, "url": p.data.url }))
      },
      "contributions": {
        "title": item.data.contributionsLabel,
        "items": contribs.map(p => ({ "name": p.data.title, "url": p.data.url }))
      },
      "orderDate": item.data.from
    }
  }

  function GetMonthYear(date) {
    if (date === null || date === undefined) {
      return "";
    } else {
      var dt = new Date(date);
      return dt.toLocaleString('default', { month: 'short' }) + " " + dt.getFullYear();
    }
  }

  function GetBool(value) {
    return (value === null || value === undefined) ? false : value;
  }

  async function GetAsync(url, config) {

    retryWrapper(axios, { retry_time: 3 })
    const result = await axios.get(url, config)
      .then(function (response) { return response; })
      .catch(function (error) { console.log(error); });

    return result;
  }

  const retryWrapper = (axios, options) => {
    const max_time = options.retry_time;
    let counter = 0;
    axios.interceptors.response.use(null, (error) => {
      const config = error.config
      if (counter < max_time) {
        counter++
        return new Promise((resolve) => {
          resolve(axios(config))
        })
      }
      return Promise.reject(error)
    })
  }
}
~~~{% endraw %}

I use [Axios](https://github.com/axios/axios) to connect to Squidex and pull the response. 

It's easier to consume the Squidex content source for single language based content, if you use these headers:{% raw %} 

~~~javascript
const config = {
      headers: {
        "X-Flatten": true,
        "X-NoResolveLanguages": 1,
        "X-Languages": "en"
      }
    };
~~~

This will flatten the output so you don't need to be concerned about multilingual content. 

I then pulled in all of the sources at once to reduce API calls, as you're limited on these within the starter plan: 

~~~javascript
  // gather data from api
    const { data: companyData } = await GetAsync(baseApiUrl + 'company', config);
    const { data: projectData } = await GetAsync(baseApiUrl + 'project', config);
    const { data: experienceData } = await GetAsync(baseApiUrl + 'experience', config);
    const { data: highlightData } = await GetAsync(baseApiUrl + 'highlight', config);
~~~

Once I had the data locally, I could filter this based on my requirements. 

~~~javascript
  // experiences
    const expCollection = actions.addCollection({ typeName: 'Experiences' })
    for (const item of experienceData.items) {

      // filter relations
      const company = companyData.items.find(function (x) { return x.id === item.data.company[0] });
      const projects = BuildList(item.data.projects, projectData.items);
      const contribs = BuildList(item.data.contributions, projectData.items);
      // map
      expCollection.addNode(MapExperience(item, company, projects, contribs))
    }

    // projects
    const proCollection = actions.addCollection({ typeName: 'Projects' })
    for (const item of highlightData.items) {

      // filter relations
      const projects = BuildList(item.data.projects, projectData.items);

      // map
      proCollection.addNode(MapProject(item, projects));
    }
  })

  function BuildList(selection, source) {
    var items = [];
    selection.forEach(function (item) {
      const found = source.find(x => x.id == item);
      if (found != null)
        items.push(found);
    });

    return items;
  }
~~~

I filtered the contents down, building up a list and then adding to a collection. 

These collections would then be used on the [Index.vue](https://github.com/garpunkal/garpunkal.dev/blob/main/src/pages/Index.vue) page as a PageQuery with GraphQL.

~~~graphql
query {
   experiences: allExperiences(sortBy: "orderDate", order: DESC) {
    edges {
      node {
        id
        title
        job
        location       
        logo {
          url              
      background
      alt
        }
        url
        shortUrl
        from
        to
        isCurrent
        description
        projects {
          title
          items {
            name
            url
          }
        }       
        contributions {
           title
          items {
            name
            url
          }
        }
        orderDate
      }
    }
   }
  projects : allProjects(sortBy: "orderNumber", order: ASC) {
    edges {
      node {
        id 
        orderNumber
        projects {
          title
          image {
            url
            alt
            width
            height
          }
          url
          position
          large
        }       
      }
    }
  } 
}
~~~

This was a real quick example of how to import data into Gridsome from Squidex. 

I hope it helps, and if you have any questions, please feel free to ask! :) 

Thanks

Enter fullscreen mode Exit fullscreen mode

Discussion (0)