【问题标题】:Strapi graphql mutation Syntax Error: Unterminated stringStrapi graphql 突变语法错误:未终止的字符串
【发布时间】:2020-01-22 07:49:18
【问题描述】:

当我尝试使用 javascript strapi sdk 更新我的数据库时,我总是得到Syntax Error: Unterminated stringthis.chapter.content 是 ckeditor 生成的 html 字符串。如何转义此字符串以使用 graphql 更新我的数据库?

async updateChapter() {
      const q = `
            mutation {
              updateChapter(input: {
                where: {
                  id: "${this.$route.params.chapterId}"
                },
                data: {
                  content: "${this.chapter.content.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/(?:\r\n|\r|\n)/g, '\n')}"
                  title: "${this.chapter.title}"
                }
              }) {
                chapter{
                  title
                  id
                  content
                }
              }
            }
      `;
      const res = await strapi.request("post", "/graphql", {
        data: {
          query: q
        }
      });
      this.chapter = res.data.chapter;
    }

【问题讨论】:

    标签: vue.js graphql strapi


    【解决方案1】:

    从技术上讲,您可以使用block string notation 来解决此问题。但是,您确实应该使用 variables 而不是字符串插值来提供动态输入值。通过这种方式,您可以轻松地提供任何类型的值(字符串、数字、对象等),GraphQL 会相应地解析它们——包括带有换行符的字符串。

    const query = `
      mutation MyMutation ($chapterId: ID!, $content: String!, $title: String!) {
        updateChapter(input: {
          where: {
            id: $chapterId
          },
          data: {
            content: $content
            title: $title
          }
        }) {
          chapter{
            title
            id
            content
          }
        }
      }
    `
    const variables = {
      chapterId: '...',
      content: '...',
      title: '...',
    }
    const res = await strapi.request("post", "/graphql", {
      data: {
        query,
        variables,
      },
    })
    

    请注意,$chapterId 可能需要是 String! 类型,如果这是架构中所要求的。由于变量也可以是输入对象类型,而不是提供 3 个不同的变量,您还可以提供一个变量来传递给 input 参数:

    const query = `
      mutation MyMutation ($input: SomeInputObjectTypeHere!) {
        updateChapter(input: $input) {
          chapter{
            title
            id
            content
          }
        }
      }
    `
    const variables = {
      input: {
        where: {
          id: '...',
        },
        data: {
          content: '...',
          title: '...',
        },
      },
    }
    

    同样,只需将 SomeInputObjectTypeHere 替换为架构中的适当类型即可。

    【讨论】:

    • 变量中的三个点有什么作用?我应该改变它吗?
    • 它只是实际字符串值的占位符。您可以将字符串文字替换为对某些变量的引用(例如this.chapter.title)。为简单起见,我只是在示例中省略了这一点。
    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多