Giter Club home page Giter Club logo

Comments (23)

ernest-okot avatar ernest-okot commented on August 14, 2024 7

Hi guys, I was able to find a workaround. Hope it can help someone out there

// gatsby-node.js
const crypto = require(`crypto`);

const digest = data => {
  return crypto
    .createHash(`md5`)
    .update(JSON.stringify(data))
    .digest(`hex`);
};

exports.onCreateNode = ({ node, boundActionCreators }) => {
  const { createNode } = boundActionCreators;
  if (node.internal.type === "StrapiArticle") {
    createNode({
      ...node,
      id: node.id + "-markdown",
      parent: node.id,
      children: [],
      internal: {
        type: "Article",
        mediaType: "text/markdown",
        content: node.content,
        contentDigest: digest(node)
      }
    });
  }
};
// index.js
export const query = graphql`
  query IndexQuery {
    allArticle {
      edges {
        node {
          title
          content
          createdAt
          childMarkdownRemark {
            html
            excerpt(pruneLength: 320)
          }
        }
      }
    }
  }
`;

On my Strapi backend, I have a model Article with a WYSIWYG field content

from gatsby-source-strapi.

nickroberts avatar nickroberts commented on August 14, 2024 6

If anyone is still having trouble, here is my implementation:

Post content type in Strapi with:

title: string;
// comma-separated values to handle urls.
// e.g. a post with title of 'My Cool Post',
// with 'cat-one, cat-two' for categories,
// creates a slug of '/cat-one/cat-two/my-cool-post'
categories: string
// WYSIWYG text
content: text;
cover: media
// gatsby-node.js
const crypto = require(`crypto`);
const _ = require(`lodash`);
const path = require(`path`);

const buildSlug = node => {
  let slug = `/${_.kebabCase(node.title)}`;
  if (node.categories) {
    slug += `/${node.categories
      .split(',')
      .map(n => _.trim(n))
      .join('/')}`;
  }
  return slug;
};

exports.createPages = async ({ actions, graphql }) => {
  const { createPage } = actions;
  try {
    const posts = await graphql(`
      {
        allPost {
          edges {
            node {
              id
              title
              categories
            }
          }
        }
      }
    `);
    posts.data.allPost.edges.forEach(({ node }) => {
      createPage({
        path: buildSlug(node),
        component: path.resolve(`src/templates/post.js`),
        context: {
          id: node.id
        }
      });
    });
    return Promise.resolve(posts);
  } catch (e) {
    console.error(`Error getting posts from Strapi: {$e.message}`);
    return Promise.reject(e);
  }
};

exports.onCreateNode = async ({ node, actions }) => {
  const { createNode } = actions;
  if (node.internal.type === 'StrapiPost') {
    createNode({
      ...node,
      slug: buildSlug(node),
      id: node.id + '-markdown',
      parent: node.id,
      children: [],
      internal: {
        type: 'Post',
        mediaType: 'text/markdown',
        content: node.content,
        contentDigest: crypto
          .createHash(`md5`)
          .update(JSON.stringify(node))
          .digest(`hex`)
      }
    });
  }
};
// src/templates/post.js
import React from 'react';
import { graphql } from 'gatsby';
import styled from 'styled-components';

import Layout from '../components/layout';
import Img from 'gatsby-image';

const WrappedImage = styled(Img)`
  margin: 0 0 1rem;
`;

const PostTemplate = ({ data }) => {
  return (
    <Layout>
      {data.post.cover && <WrappedImage fluid={data.post.cover.childImageSharp.fluid} />}
      <h1>{data.post.title}</h1>
      <p dangerouslySetInnerHTML={{ __html: data.post.childMarkdownRemark.html }} />
    </Layout>
  );
};

export default PostTemplate;

export const query = graphql`
  query PostTemplate($id: String!) {
    post(id: { eq: $id }) {
      title
      childMarkdownRemark {
        html
      }
      cover {
        childImageSharp {
          fluid(maxWidth: 1600) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  }
`;

Hopefully this helps anyone having issues.

This comes with an as-is warranty. 😈

from gatsby-source-strapi.

bzhr avatar bzhr commented on August 14, 2024 1

Probably best to examine how the Contentful source plugin handles this.

from gatsby-source-strapi.

theshire-io avatar theshire-io commented on August 14, 2024 1

I was getting an error at childMarkdownRemark so what worked for me was:

{
  allMarkdownRemark {
    edges {
      node {
        html,
        excerpt
      }
    }
  }
}

from gatsby-source-strapi.

ryanbraving avatar ryanbraving commented on August 14, 2024 1

@ernest-okot Thanks for the workaround.
I am using the below code in my component to show a bold and italic text coming from Strapi CMS. But I get actual html code in my browser. Any idea how I can convert the html into preview?

const IndexPage = ({ data }) => (
    <ul>
       {data.allArticle.edges.map(document => (
         <li key={document.node.id}>
           <p>{document.node.childMarkdownRemark.html}</p>
         </li>
       ))}
    </ul>
)
export default IndexPage



export const pageQuery = graphql`
 query IndexQuery {
   allArticle {
     edges {
       node {
         id
         childMarkdownRemark {
            html
          }
       }
     }
   }
 }
`

The markdown is coming from the Strapi Api is as below:
***You may be*** familiar with the clean eating movement

And after using the above code it gets converted to the html code as below:
<p><strong><em>You may be</em></strong> familiar with the clean eating movement

And I exactly get the same html code in my browser. I am actually looking for a way to get the below statement in my browser (instead of html code):

You may be familiar with the clean eating movement

from gatsby-source-strapi.

bzhr avatar bzhr commented on August 14, 2024

can somebody confirm that this issue is seen?
Regards

from gatsby-source-strapi.

davidostermann avatar davidostermann commented on August 14, 2024

Yes, I have the problem with the wysiwyg node that should be typed as Markdown to be transformable by gatsby-transformer-remark.

from gatsby-source-strapi.

pierreburgy avatar pierreburgy commented on August 14, 2024

Good catch, it would be great to update the plugin to support the WYSIYG! Does any of you have time to submit a pull request?

from gatsby-source-strapi.

bzhr avatar bzhr commented on August 14, 2024

WYSIYG -> Markdown
Images -> Image types
Files -> File types

@pierreburgy - Do you know where can I find more info on defining these types? I think I can provide the pull request, I just need to see an implementation example.

This is what I was told in the Gatsby Discord channel:

not sure about the details of the source plugin for Strapi but it needs to set the mediaType of the markdown field to text/markdown and then if you have gatsby-transformer-remark installed, it'll automatically process that field to html

from gatsby-source-strapi.

davidostermann avatar davidostermann commented on August 14, 2024

You can find it in gatsby-source-cockpit too : https://github.com/mpartipilo/gatsby-source-cockpit/blob/master/gatsby-node.js#L20

from gatsby-source-strapi.

bzhr avatar bzhr commented on August 14, 2024

@pierreburgy I have forked this plugin and started working on introducing the missing types. I can see that images have mime:'image/png', but wysiwyg fields do not have a media type. How can it be recognized that a field is markdown?

from gatsby-source-strapi.

bzhr avatar bzhr commented on August 14, 2024

Here's an example Node created with the data from Strapi API:

Node { description: 'Програма за првата недела оваа сезона во клуб Сектор909.',
  from: '2018-05-30T00:00:00.000Z',
  to: '2018-06-02T00:00:00.000Z',
  sreda: 'Uzun Brothers\r\nMaci Stojanovic',
  createdAt: '2018-05-09T17:13:20.779Z',
  updatedAt: '2018-05-09T17:13:20.790Z',
  cetvrtok: 'Aleksandar Miskoski\r\nTomi Bojadzi',
  petok: 'Bruv\r\nUlterior',
  sabota: 'Soul Case\r\nBodan Jamakoski',
  path: '1',
  fblink: 'https://www.facebook.com/events/1903315409987706/',
  flyer: 
   { related: [ '5af32c3086bd117b287ad77c' ],
     name: 'twitter+header.jpeg',
     hash: 'ebb162cc9fe547daa6db07d0156edd1e',
     ext: '.jpeg',
     mime: 'image/jpeg',
     size: '130.10',
     url: '/uploads/ebb162cc9fe547daa6db07d0156edd1e.jpeg',
     provider: 'local',
     createdAt: '2018-05-09T17:39:11.949Z',
     updatedAt: '2018-05-09T17:39:11.957Z',
     id: '5af3323fb48c170296f468c4' },
  strapiId: '5af32c3086bd117b287ad77c',
  id: '5af32c3086bd117b287ad77c',
  parent: '__SOURCE__',
  children: [],
  internal: 
   { type: 'StrapiPrograma',
     contentDigest: '0cd085be30cb2c0872f3523fe4920941' } }

The image has a mime type, but the first field description which is wysiwyg doesn't.

from gatsby-source-strapi.

hugo-marques-m3 avatar hugo-marques-m3 commented on August 14, 2024

@bzhr did you manage to make images work on your fork?

from gatsby-source-strapi.

bzhr avatar bzhr commented on August 14, 2024

@hugo-marques-m3 not yet 🙁 I've been investigating Prismic plugin and it seems it downloads images and then processes these.

from gatsby-source-strapi.

theshire-io avatar theshire-io commented on August 14, 2024

The disadvantage with what I wrote is that I can't get the title that way, which pretty much renders this approach useless.

@ernest-okot Could you please share what you did to get childMarkdownRemark available on StrapiArticle?

from gatsby-source-strapi.

vobango avatar vobango commented on August 14, 2024

@theshire-io I was having the same issue as you (childMarkdownRemark not showing up).

Turns out I was querying the "old" node (AllStrapiService in my case) but the new node created in gatsby-node.js had a type Service.

Basically you need to query whatever the type you set in internal: { type: 'YOUR_TYPE' }.

So in @ernest-okot 's example you'd query AllArticle instead of AllStrapiArticle.

from gatsby-source-strapi.

vobango avatar vobango commented on August 14, 2024

@ryanacme I found the fastest solution was to use React's dangerouslySetInnerHTML prop.
https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

from gatsby-source-strapi.

ryanbraving avatar ryanbraving commented on August 14, 2024

@vobango Thanks. Yes it worked. For other fellow who might have same issue, I just changed the line:
<p>{document.node.childMarkdownRemark.html}</p>
to:
<p dangerouslySetInnerHTML={{__html:document.node.childMarkdownRemark.html}} />

from gatsby-source-strapi.

ryanbraving avatar ryanbraving commented on August 14, 2024

I encountered with another challenge and I appreciate if someone can help. My StrapiUser node is like below:

{
    strapiUser {
       id
       username
       articles{
           content
      }
   
   }
}

It has a list of articles (each user has many articles). How I can create a new node and have list of childMarkdownRemark for each article in the list?
The code below does the job on only one item in the articles list. But I need a way like getting a list of childMarkdownRemark not only one object.

exports.onCreateNode = ({ node, actions }) => {
   const { createNode } = actions;
   if (node.internal.type === "StrapiUser") {
       createNode({
          ...node,
          id: node.id + "-markdown",
          parent: node.id,
          children: [],
          internal: {
             type: "User",
             mediaType: "text/markdown",
             content: node.articles[0].content,
             contentDigest: digest(node)
         }
       });
   }
};

@ernest-okot & @vobango, Guys could you please have a look at above code and help me with that.
Cheers

from gatsby-source-strapi.

nickroberts avatar nickroberts commented on August 14, 2024

Any word on integrating something so we can use the remark transformer on WYSIWYG fields?

I'm having some issues with the workaround and page urls.

I'm not familiar enough to throw something together in a MR...yet.

from gatsby-source-strapi.

nickroberts avatar nickroberts commented on August 14, 2024

After looking into this a bit more, it looks like Strapi itself would need to return the field type so we could act on it (e.g. markdown, string, number, json, image, etc...)

from gatsby-source-strapi.

qq781548819 avatar qq781548819 commented on August 14, 2024

@ernest-okot hi,Can you take a look at it for me,I'm going to add a tableOfContents field,
throw catch Skipping TableOfContents. Field 'fields.slug' missing from markdown node

query IndexQuery {
  allArticle {
    edges {
      node {
        title
        content
        chapter_num
        
        childMarkdownRemark {
          html
          tableOfContents
          excerpt(pruneLength: 320)
        }
      }
    }
  }
}

from gatsby-source-strapi.

olee avatar olee commented on August 14, 2024

See #89 (comment)

from gatsby-source-strapi.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.