DEV Community

loading...
Cover image for SquidexCMS to Gridsome using Content API

SquidexCMS to Gridsome using Content API

garpunkal profile image Gareth Wright Updated on ・4 min read

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": 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": 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();
    }
  }

  async function GetAsync(url, config) {
    return await axios.get(url, config)
      .then(function (response) { return response; })
      .catch(function (error) { console.log(error); });
  }
}

Enter fullscreen mode Exit fullscreen mode

I use 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:

const config = {
      headers: {
        "X-Flatten": true,
        "X-NoResolveLanguages": 1,
        "X-Languages": "en"
      }
    };
Enter fullscreen mode Exit fullscreen mode

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:

  // 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);
Enter fullscreen mode Exit fullscreen mode

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

  // 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;
  }
Enter fullscreen mode Exit fullscreen mode

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 page as a PageQuery with 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
        }       
      }
    }
  } 
}
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)

pic
Editor guide